Search code examples
androidandroid-activityandroid-listviewservicebackground-service

refresh activity after receiving the response from the background service


I am working on an application where i use a background service to send a request to a server the response is then stored in a database and display the data dynamically as receiving the answers from the background service and saving them in the database, knowing that i'm using a

ListView

to display the data from the database. how can i refresh the activity every time i save new data in the database? i have triyed displaying the data after a click it's working how can i do it dynamically?


Solution

  • Assuming you are using a true service or not an AsyncTask.

    Use a BroadcastReceiver pattern. Send the broadcast in your service.

    LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("data_changed"));
    

    Declare your receiver in activity containing your listview

      private BroadcastReceiver dataChangeReceiver= new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // update your listview
        }
    };
    

    Register and unregister it

        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        IntentFilter inF = new IntentFilter("data_changed");
        LocalBroadcastManager.getInstance(this).registerReceiver(dataChangeReceiver,inF);
    
    
    
    }
     @Override
    protected void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(dataChangeReceiver);
    }