I am passing data from AsyncTask
to a fragment of tabbed activity. Why onEvent()
of EventBus is not being called?
BackgroundWorker.java
doInBackground() is called by MainActivity
public class BackgroundWorker extends AsyncTask<String,Void,String> {
@Override
protected void onPostExecute(String line) {
userResult = line.split(" ");
String result = userResult[0];
if(result.equals("Success")){
CustomMessageEvent event = new CustomMessageEvent();
event.setCustomMessage(line);
Intent intent = new Intent(context,TabActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
EventBus.getDefault().post(event);
}
}
}
ProfileTab.java
This file is a fragment of tabbed activity. Is there anything that should be done in tabbed activity or should doInBackground must be called again.
public class ProfileTab extends Fragment {
public TextView t1;
private View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.profile, container, false);
t1 = (TextView) rootView.findViewById(R.id.textView4);
EventBus.getDefault().register(this);
Log.d(TAG, "onCreateView: ");
return rootView;
}
@Subscribe(threadMode = ThreadMode.ASYNC)
public void onEventAsync(CustomMessageEvent event) {
Log.d(TAG, "onEvent: ");
t1.setText(event.getCustomMessage());
}
}
Tried LocalBroadcastManager and the result was same, onReceive()
was not called. Where am I going wrong?
If you start Activity in your onPostExecute
, I suggest pass data by intent, not events - it is simpler. Your subscribed method isn't called, because event is posted before you register - use postSticky
instead of post
, and you will get an event.
I assume, you want to pass line
( String
). So construct intent:
Intent intent = new Intent(context,TabActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("LINE", line);
context.startActivity(intent);
Than, in your TabActivity
in onCreate read passed value:
String line = getIntent().getStringExtra("LINE", "");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.