【发布时间】:2018-09-18 13:40:45
【问题描述】:
我试图更改在我的适配器中的MainActivity 中设置的SharedPreference。所以我想通过MainActivity 的一个实例,我可以从那里访问和更改它。单击一个项目时会弹出一个对话框,然后当它被确认时,变量应存储在SharedPreference 中。不幸的是,我在应该编辑此变量的部分出现错误:
android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()' 在空对象引用上
MainActivity:
public class MainActivity extends AppCompatActivity {
SharedPreferences favE;
int x;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
favE = MainActivity.this.getSharedPreferences("myFavEName",
Context.MODE_PRIVATE);
x = favE.getInt("favKey", 0);
}
public int getFavE(){
return x;
}
}
我的适配器:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<GetDataAdapter> getDataAdapter;
MainActivity ma = new MainActivity();
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
final int a = getDataAdapter1.getId();
int x = ma.getFavE();
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addDialog(a);
});
}
public void addDialog(final int a) {
Context context = this.context;
LayoutInflater inflater = LayoutInflater.from(this.context);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setPositiveButton("Exit Group", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ma.favE.edit().putInt("favKey", 0)
.apply();
}
});
builder.show();
}
}
【问题讨论】:
-
适配器中的
MainActivity实例与实例化 SharedPreferences 的实例不同... -
@Shark 你能给我解释一下吗?
-
是的。您发布的第一个 sn-p,您在其
onCreate()方法中实例化(初始化)SharedPreferences 成员favE。在您发布的第二个 sn-p 中,您通过执行MainActivity ma = new MainActivity();创建了一个新的MainActivity实例 - 它没有运行它的onCreate()方法,因为该活动尚未由操作系统启动。因此,它的favE成员仍未初始化(空)。这就是你获得 NPE 的原因。 -
如果你真的想这样做,只需在
MainActivity中设置favE静态 - 但你也应该知道简单的SharedPrefUtil类可以在这两种情况下工作并避免所有您遇到的这些问题 -
如果你确实做到了
static一个简单的MainActivity.getSharedPref()就可以了,你不需要从适配器实例化活动。将MainActivity实例传递给适配器而不是在那里实例化一个新实例可能会更好。
标签: java android sharedpreferences android-context