Search code examples
javaandroidlistviewlistadapter

Updating ListAdapter from different activity


I am working on my hobby project to learn more about android programming and stuffs. So i recently ran into a simple problem but couldn't find a solution for it.

My project for now have 2 activity [MainActivity], [CommentActivity].

In MainActivity, I have a listadapter (cusAdapter) will fetch all the content from a database and display it on a listview. Everything works fine there. It will fetch all the comments and total comments for a certain post based on the post id. In the same MainActivity, i have a comment button and a onclick listener which when clicked will bring user to the next activity [CommentActivity] and load all the comments and data needed using another custom adapter. I also have a total comment TextView that will show the total comment fetched by the json and display it in my listview.

When a user posted a comment on CommentActivity, it will save into the database via AsyncTask.

Now the problem is, when i press back button and navigate back from CommentActivity to MainActivity, i use intent with flag (intent.flag_activity_reorder_to_front). So it will never reload the MainActivity again when back button is pressed. Also it will never update the total comment in the MainActivity. What i want to do is when back button is pressed on CommentActivity, i want it to refresh/reload the ListAdapter in MainActivity to fetch the latest data from database.

Also i don't want to reload the whole MainActivity, i just wanna update the view without reloading the whole activity.

I believe there must be some easy way to do this. I can post codes if you guys need it to assists me.

Thank you.


Solution

  • Yes, there is an easy way. Start your sencond activity using:

    • startActivityForResult(intent, RESULT_CODE)
    • use setResult(RESULT_OK) in your second activity after doing the commit of the changes to the database
    • override onActivityResult() in your first activity to check when the second activity returns properly
    • update the first adapter as needed.

    Hope it helps.