I tried to change a SharedPreference
that is set up in my MainActivity
in my Adapter. So I thought with an instance of the MainActivity
I could access and change it from there. When an item is clicked a dialog pops up and then when it is confirmed, the variable shall be stored in the SharedPreference
. Unfortunately I get an error in the part where this variable should be edited:
android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()' on a null object reference
The 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;
}
}
My Adapter:
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();
}
}