Issue
I have an activity to add an object to a database in my application, and the database is displayed in activity which calls an AddActivity
. My problem is I need to refresh ArrayList after i update a database, but i can't have access to it inside my AddActivity
. So i wanted to track in MainActivity
when the AddActivity
has ended and then call the refreshing function
. For now i tried using code below and this is working, but i don't think this is the way i should do it, I feel like there is better function for that but I couldn't find it.
Code in MainActivity inside onClickListener
:
Intent intent = new Intent(mContext, ExerciseAdd.class);
startActivityForResult(intent, 1);
Code in AddActivity also inside onClickListener
:
dataBaseAccess = ExercisesDataBaseAccess.getInstance(getApplicationContext());
dataBaseAccess.open();
dataBaseAccess.addExercise(nameString, typeString, "NULL");
dataBaseAccess.close();
Intent intent = new Intent();
intent.putExtra("result", 1);
setResult(1, intent);
finish();
And refhresing function in MainActivity
:
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
dataBaseAccess.open();
exercises = dataBaseAccess.getAllExercises();
dataBaseAccess.close();
adapter.setExercises(exercises);
adapter.notifyDataSetChanged();
}
Or maybe is there any way to pass an reference to ArrayList
to AddActivity
? it was hard to me to find any information about this
Solution
The way you are doing it is the most robust and clean way. You are storing your data in the database and you have one Activity
that adds items to the database and another Activity
that reads the data from the database and displays it. This may seem like overkill, but this architecture is more robust than sharing data in memory between activities.
Of course, it is possible to share data in memory between activities. You can store a reference to your ArrayList<Exercise>
in a public static
variable and it can be accessed by both activities. This is a simple way to share data but can be tricky if your app goes to the background and Andriod kills off the OS process hosting the app and then the user returns to the app. If he was last using the AddActivity
, when he returns to the app, Android will create a new OS process to host the app and instantiate the AddActivity
, but MainActivity
is not yet instantiated and your shared public static
data will be gone. So this approach is error-prone.
Another approach would be to use Live Data. This is a more complicated approach to sharing data in memory between activities. You can read more about live data here: https://developer.android.com/topic/libraries/architecture/livedata
Answered By - David Wasser
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.