I use SharedPreferences to pass some data from Activity1
to Activity2
when button
clicked. Then I add these data to ArrayList
in Activity2
.
//Basically I have ListView with images.
//When user ckick on any image, Activity1 opens and it contains this image and it's name
Activity1 {
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String imageName = intent.getStringExtra("name"); //imageName has different vavues, depends on which image user clicked in previous activity.
int imageId = intent.getIntExtra("image", 0); //imageId has different vavues, depends on which image user clicked in previous activity.
String str = Integer.toString(imageId); //convert imageId to use it as a key in SharedPreferences
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("MyPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", str); //save current key,
editor.putInt(str, receivedImage);
editor.putString(str + "a", receivedName);
editor.apply();
}
}
Activity2{
onCreate{
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("MyPref", Context.MODE_PRIVATE);
String key1 = sharedPref.getString("key", null);
String imageName = sharedPref.getString(key1 + "a", null);
int imageId = sharedPref.getInt(key1, 0);
mDrinkArrayList.add(new Drink(imageName, imageId));
listAdapter = new CustomAdapter(this, mDrinkArrayList);
listAdapter.notifyDataSetChanged();
ListView listDrinks = findViewById(R.id.list_drinks);
listDrinks.setAdapter(listAdapter);
}
}
The problem is that mArrayList
doesn't save Data
added before. For example I click on button
of 3 different images and I expect that mArrayList
will have 3 Data
objects. But actually it always has only last Data
object.
I understand why it happens - SharedPreferences overrides old data. I saw many advices like I have to use different keys but I did it (put imageResourseId as a key). I thought about ways to solve this problem. The ways that I can understand now are:
1) somehow let SharedPreferences to store previous data (I heard about using SQL database, but I don't have so many images to use database).
2) override mDrinkArrayList
after receiving new data, so it basically have old data when Activity2 starts again.
3) create mDrinkArrayList
in Activity1, add new Data when button clicked, and pass mDrinkArrayList
to Activity2 using SharedPreference.
Could someone suggest what shoud I do in this situation? Thanks in advance.