gpt4 book ai didi

android - 初始化 SharedPreferences 给出 : Attempt to invoke virtual method on a null object reference

转载 作者:太空宇宙 更新时间:2023-11-03 11:55:40 24 4
gpt4 key购买 nike

当我启动我的应用程序时,它崩溃了,并给我这个错误代码。

Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

这是我的主要 Activity :

package com.awplicity.testappshared;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences = getSharedPreferences("", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Button button1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

private void onClick(View v) {
switch(v.getId()) {
case R.id.nextAct:
editor.putString("mystring", "Hi");
editor.commit();
startActivity(new Intent("com.awplicity.testappshared.Main2Activity"));
break;
}
}
}

这是第二个 Activity :

package com.awplicity.testappshared;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class Main2Activity extends AppCompatActivity {

TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tv = (TextView) findViewById(R.id.tv_main2);
setText();
}

public void setText() {
SharedPreferences sharedPreferences = getSharedPreferences("", Context.MODE_PRIVATE);
tv.setText(sharedPreferences.getString("mystring", ""));
}
}

最佳答案

一般来说,在 onCreate() 内部之前,您不能调用从 Activity(或子类,如 AppCompatActivity)继承的方法方法。到那时,事情还没有准备好。

因此,改变:

SharedPreferences sharedPreferences = getSharedPreferences("", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();

到:

SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;

并在 onCreate() 中初始化这些字段:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

sharedPreferences = getSharedPreferences("", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}

关于android - 初始化 SharedPreferences 给出 : Attempt to invoke virtual method on a null object reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35246963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com