Home Ask Login Register

Developers Planet

Your answer is one click away!

KKKK February 2016

Cannot pass data from asyncTask to my activity

In searchactivity: I declared a background worker class to connect to the remote mysql database and get some data

protected void onCreate(Bundle savedInstanceState) {

    BackgroundWorker worker = new BackgroundWorker(SearchActivity.this);
    ////////// My message is empty below

In backgroundworker.class, the backgroundworker class did get the data but fails to pass to my activity

protected void onPostExecute(Wrapper w) {
    else if(w.result.contains("Searchfirst successfully!")){
        ////////// My message can be showed correctly here
        Intent colleges = new Intent(context,SearchActivity.class);
        colleges.putExtra("searchresult", w.result);

Also I found out that if i put the data to the intent and start that activity immedicately by calling startActivity(intent) in onPostExecute(), the data can be passed to that intent, however, if i did not start that activity, the data is lost?


Shayan_Aryan February 2016

You can add this lines:

Intent intent = new Intent("myAction");
intent.putExtra("searchResult", w.result);

then register a broadcast reciever in your activity:

registerReceiver(new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                Object result = intent.getExtras().get("searchResult");
        }, new IntentFilter("myAction"));

Besides, You can define a listener interface and pass it to the async task, then call the listener's method in onPostExecute() method. There is no need to calling an intent this way.

Post Status

Asked in February 2016
Viewed 2,929 times
Voted 10
Answered 1 times


Leave an answer

Quote of the day: live life