I have two activities (Activity1
and Activity2
) and one AsyncTask (AsyncTask1
)
Activity1
has a button that on click gives control to Activity2
, Activity2
has an AsyncTask
and in that task's onPostExecute()
I want to handle a TextView
that is in Activity1
.
Example:
Activity1
public class Activity1 extends RoboSherlockActivity {
@Inject (R.id.name) EditText name;
@Inject (R.id.mybutton) Button button;
public void onCreate (Bundle savedInstanceState) {
...
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent activity2 = new Intent(context, Activity2.class);
startActivity(activity2);
}
});
....
}
}
Activity2
public class Activity2 extends RoboSherlockActivity {
@InjectView (R.id.name) EditText secret;
....
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("Save")
return true;
}
...
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getTitle().toString().equalsIgnoreCase("Save")) {
new AsyncTask1(this, secret.getText().toString()).execute();
}
return true;
}
}
AsyncTask1
public class AsyncTask1 extends RoboAsyncTask<String> {
Activity2 activity;
String secret;
public AsyncTask1 (Activity2 activity, String secret) {
this.activity = activity;
this.secret = secret;
}
public String call() throws Exception {
//call the server here
return "";
}
protected void onSuccess(String result) {
activity.finis();
//HERE I WANT TO SET THE NAME: name.setText(result); //How can I do this??
}
}
Question
How can I set the name in the onSuccess
of the AsyncTask?
Activity2 has an AsyncTask and in that task's onPostExecute() I want to handle a TextView that is in Activity1.
No you can't. You can use startActivtiyForResult
in Activtiy1 and update textview
In Activity1
Intent intent=new Intent(Activity.this,Activity2.class);
startActivityForResult(intent, 2);
Then
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=data.getStringExtra("key");
textView1.setText(message);
}
}
In Activity2
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
intent = getIntent();
...// rest of the code
}
In onSuccess
protected void onSuccess(String result) {
intent.putExtra("key",value);
setResult(2,intent);
activity.finish();
}