编辑来自其他 class 的 SharedPreference 值

Edit SharedPreference value from other class

我试图在我的适配器中更改 MainActivity 中设置的 SharedPreference。所以我想通过 MainActivity 的一个实例,我可以从那里访问和更改它。单击某个项目时会弹出一个对话框,然后在确认后,该变量将存储在SharedPreference中。不幸的是,我在应该编辑这个变量的部分得到了一个错误:

android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()' on a null object reference

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 的实例。您可以指定一个构造函数,该构造函数仅从 activity 获取上下文以使用共享首选项。因此,当您创建适配器时,您将为适配器提供 MainActivity 上下文。我认为在您的情况下,因为您正在创建新实例,所以您在正确初始化 MainActivity 之前使用上下文。所以它给了你错误的上下文。 你的构造函数将是这样的

public RecyclerViewAdapter(Context context) {
        this.context = context;
    }