Reputation: 3
I'm trying to develope some very basic code using startActivityForResult and I am always getting an annoying problem : from the main activity (contains only a "hello word" editText) I call a new activity which contains only a TextView, an empty listView and an ImageButton. When I click on the ImageButton it supposes to return "ok" inside an intent to my mainActivity and print it into the "hello word" editText but nothing happens. I already have read all the threads on how to use "StartActivity for result" but I found nothing helpful.Please help me.
My Code below is:
MainActivity
public class MainActivity extends AppCompatActivity {
TextView hw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hw = (TextView) findViewById(R.id.hw);
hw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),DeviceListActivity.class);
int resultCode = -1;
startActivityForResult(intent,resultCode);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
hw.setText(result);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
}
DeviceListActivity:
public class DeviceListActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_list);
final ImageButton nextBtn = (ImageButton) findViewById(R.id.nextBtn);
nextBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent returnIntent = new Intent();
String result = "Tout va bien!";
returnIntent.putExtra("result",result);
onActivityResult(1,1,returnIntent);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
}
Upvotes: 0
Views: 5062
Reputation: 13593
in your MainActivity change:
Intent intent = new Intent(getApplicationContext(),DeviceListActivity.class);
int resultCode = -1;
startActivityForResult(intent,resultCode);
to
Intent intent = new Intent(getApplicationContext(),DeviceListActivity.class);
int resultCode = 1;
startActivityForResult(intent,resultCode);
and in your DeviceListActivity replace your code with:
Intent returnIntent = new Intent();
String result = "Tout va bien!";
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK, returnIntent);
finish();
Hope it will help you out.
Upvotes: 1