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) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);

    BackgroundWorker worker = new BackgroundWorker(SearchActivity.this);
    worker.execute("Searchfirst");
    ////////// My message is empty below
Toast.makeText(SearchActivity.this,getIntent().getExtras().getString("searchresult"),Toast.LENGTH_SHORT).show();
}

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
Toast.makeText(context,w.result.toString(),Toast.LENGTH_SHORT).show(); 
        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?

Answers


Shayan_Aryan February 2016

You can add this lines:

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

then register a broadcast reciever in your activity:

registerReceiver(new BroadcastReceiver() {
            @Override
            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

Search




Leave an answer