AsyncTask : passing value to an Activity (onCreate method )

你离开我真会死。 提交于 2020-01-22 15:45:28

问题


Update1

activity:

public Integer _number = 0;
@Override
    public void onCreate(Bundle savedInstanceState) {
if (_number >0)
        {
            Log.d("onSuccessfulExecute", ""+_number);
        }
        else
        {
            Log.d("onSuccessfulExecute", "nope empty songs lists");
        }
}

public int onSuccessfulExecute(int numberOfSongList) {

_number = numberOfSongList;

if (numberOfSongList >0)
{
    Log.d("onSuccessfulExecute", ""+numberOfSongList);
}
else
{
    Log.d("onSuccessfulExecute", "nope empty songs lists");
}
    return numberOfSongList;
}

end Update1

UPDATE: AsynchTask has its own external class.

How to pass an value from AsyncTask onPostExecute()... to activity

my code does returning value from onPostExecute() and updating on UI but i am looking for a way to set the activity variable (NumberOfSongList) coming from AsynchTask.

AsyncTask class:

@Override
    public void onPostExecute(asynctask.Payload payload)
    {  
         AsyncTemplateActivity app = (AsyncTemplateActivity) payload.data[0];

             //the below code DOES UPDATE the UI textView control
             int answer = ((Integer) payload.result).intValue();
             app.taskStatus.setText("Success: answer = "+answer);

            //PROBLEM:
            //i am trying to populate the value to an variable but does not seems like the way i am            doing:
            app.NumberOfSongList = payload.answer;
            ..............
            ..............
    }

Activity:

  public Integer NumberOfSongList;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 

        //Several UI Code   
        new ConnectingTask().execute();
        Log.d("onCreate", ""+NumberOfSongList);

    } 

回答1:


What about using a setter method? e.g.

private int _number;
public int setNumber(int number) {
    _number = number;
}

UPDATE:

Please look at this code. This will do what you're trying to accomplish.

Activity class

public class TestActivity extends Activity {
    public int Number;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.test);

        Button btnDisplay = (Button) findViewById(R.id.btnDisplay);
        btnDisplay.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Toast toast = Toast.makeText(v.getContext(), "Generated number: " + String.valueOf(Number), Toast.LENGTH_LONG);
                toast.show();               
            }
        });

        new TestTask(this).execute();
    }
}

AsyncTask class

public class TestTask extends AsyncTask<Void, Void, Integer> {
    private final Context _context;
    private final String TAG = "TestTask";
    private final Random _rnd;

    public TestTask(Context context){
        _context = context;
        _rnd = new Random();
    }

    @Override
    protected void onPreExecute() {
        //TODO: Do task init.
        super.onPreExecute();
    }

    @Override
    protected Integer doInBackground(Void... params) {
        //Simulate a long-running procedure.
        try {
            Thread.sleep(3000);         
        } catch (InterruptedException e) {
            Log.e(TAG, e.getMessage());
        }

        return _rnd.nextInt();
    }

    @Override
    protected void onPostExecute(Integer result) {
        TestActivity test = (TestActivity) _context;
        test.Number = result;       
        super.onPostExecute(result);
    }
}



回答2:


Just a word of caution: Be very careful when attempting to hold a reference to an Activity instance in an AsyncTask - I found this out the hard way :). If the user happens to rotate the device while your background task is still running, your activity will be destroyed and recreated thus invalidating the reference being to the Activity.




回答3:


Create a listener.

Make a new class file. Called it something like MyAsyncListener and make it look like this:

 public interface MyAsyncListener() {
      onSuccessfulExecute(int numberOfSongList);
 }

Make your activity implement MyAsyncListener, ie,

 public class myActivity extends Activity implements MyAsyncListener {

Add the listener to the constructor for your AsyncTask and set it to a global var in the Async class. Then call the listener's method in onPostExecute and pass the data.

 public class MyCustomAsync extends AsyncTask<Void,Void,Void> {

      MyAsyncListener mal;

      public MyCustomAsync(MyAsyncListener listener) {
           this.mal = listener;
      }

      @Override
      public void onPostExecute(asynctask.Payload payload) {
           \\update UI
           mal.onSuccessfulExecute(int numberOfSongList);
      }
 }

Now, whenever your AsyncTask is done, it will call the method onSuccessfulExecute in your Activity class which should look like:

 @Override
 public void onSuccessfulExecute(int numberOfSongList) {
      \\do whatever
 }

Good luck.



来源:https://stackoverflow.com/questions/9742446/asynctask-passing-value-to-an-activity-oncreate-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!