AsyncTask:将值传递给Activity(onCreate方法)

时间:2012-03-16 18:12:34

标签: android android-asynctask

UPDATE1

活性:

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;
}

结束Update1

更新:AsynchTask有自己的外部类。

如何将值从AsyncTask onPostExecute()...传递给activity

我的代码从onPostExecute()返回值并在UI上更新,但我正在寻找一种方法来设置来自AsynchTask的活动变量(NumberOfSongList)。

AsyncTask类:

@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;
            ..............
            ..............
    }

的活动:

  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);

    } 

3 个答案:

答案 0 :(得分:2)

使用setter方法怎么样? e.g。

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

更新:

请查看此代码。这将完成你想要完成的任务。

活动类

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类

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);
    }
}

答案 1 :(得分:1)

请注意:在尝试在AsyncTask中保存对Activity实例的引用时要非常小心 - 我发现这很困难:)。如果用户在后台任务仍在运行时碰巧旋转设备,您的活动将被销毁并重新创建,从而使参与活动无效。

答案 2 :(得分:0)

创建一个监听器。

制作一个新的类文件。称它为MyAsyncListener,并使其如下所示:

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

让您的活动实现MyAsyncListener,即

 public class myActivity extends Activity implements MyAsyncListener {

将侦听器添加到AsyncTask的构造函数中,并将其设置为Async类中的全局var。然后在onPostExecute中调用监听器的方法并传递数据。

 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);
      }
 }

现在,无论何时完成AsyncTask,它都会调用Activity类中的onSuccessfulExecute方法,该方法如下所示:

 @Override
 public void onSuccessfulExecute(int numberOfSongList) {
      \\do whatever
 }
祝你好运。