【发布时间】:2016-12-16 13:11:17
【问题描述】:
我不知道如何在另一个不是片段或任何东西的类中使用共享首选项
这是我的主要活动代码:
public class MainActivity extends AppCompatActivity {
Backgrounds backs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
backs = new Backgrounds(this);
bg = (LinearLayout) findViewById(R.id.background);
bg.setBackgroundColor(getResources().getColor(backs.getBackground()));
}
}
这是我的背景课程:
public class Backgrounds {
Integer colors[] = {
R.color.red,
R.color.pink,
R.color.purple,
};
private context;
SharedPreferences sharedPref = context.getSharedPreferences("file", 0);
SharedPreferences.Editor editor = sharedPref.edit();
int i = sharedPref.getInt("background", -1);
public Backgrounds(Context context)
{
this.context = context
}
public int getBackground()
{
i++;
try{
editor.putInt("factIndex", i);
editor.commit();
return colors[i];
}catch (Exception e){
i = 0;
editor.putInt("factIndex", i);
editor.commit();
return colors[i];
}
}
}
我已经尝试了很多方法。当我收到此错误时,我几乎可以肯定代码的上下文部分存在问题:
原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)'
我也尝试过使用 context.getApplicationContext() 但错误相似。我认为这可能是因为我需要将 Backs 对象的分配移动到 onCreate() 中,但这仍然不起作用。我已经清理了项目并使用 gradle 同步了文件,但程序在加载之前仍然崩溃。删除任何 SharedPrefrences 内容时,该代码可以完美运行。
【问题讨论】:
-
在您分配
sharedPref时,context是null。将sharedPref和editor的赋值移到构造函数中
标签: java android android-studio sharedpreferences android-context