Search code examples
javaandroidandroid-activityandroid-asynctaskrefresh

Refresh running activity with new data from AsyncTask result


I have a class, that executes some command in background. Class method is executed asynchronously (by using AsyncTask) and when command finishes, it posts event with command result. Then, new activity is started. To do this, I added inside OnCreate method to MainActitity:

ssh = new SshSupport();
ssh.Connect();
ssh.ExecuteCommand(commandType);
//..................................
ssh.eventHandler = new ISshEvents()
{

  @Override
  public void SshCommandExecuted(SshCommandsEnum commandType, String result)
  {
    if (progressDialogExecuting.isShowing()) progressDialogExecuting.dismiss();
    
    Intent intent = new Intent(MainActivity.this, ResultListActivity.class);
    intent.putExtra("result", result);
    intent.putExtra("commandType", commandType);
    startActivity(intent);
  }

So it works as should. My commands starts in background and when finished, my event fires and displays new activity with results (all results are received via getIntent().getExtras() and then formatted to be displayed as should).

Problem: on result activity I have "Refresh" button. When pressed, all data should be refreshed. So I need to execute ssh.ExecuteCommand(commandType); again to get refreshed data. Note that I don't want to open new ssh connection for this. Instead, I want to use already opened connection and simply execute my command again. So I made my 'ssh' static and I used MainActivity.ssh.ExecuteCommand(commandType); on refresh button press. It works, but obviously, it causes to create second instance of ResultListActivity, instead of refreshing data on existing one.

I can even avoid to creating result activity again by checking if it's already exists (for example by adding 'active' boolean static variable to it). However, it won't help me because I still have no any possibility to refresh data inside my existing activity.

So, how can I do it?


Solution

  • No responses, so I'm answering to my own question. My solution was: - Change my activity launchMode to singleTop - Override method onNewIntent

    In this case each time I start this activity: if activity already exists it won't be created again. Instead, onNewIntent method will be called.

    http://developer.android.com/guide/topics/manifest/activity-element.html#lmode http://developer.android.com/reference/android/app/Activity.html#onNewIntent%28android.content.Intent%29

    However, I'm not sure if approach like this is good. How do you think?