I'm new to android . This might be the simplest question of all !! but I couldn't figure out whats gone wrong here,
I was trying to create a basic example for passing values through intent.So I need to pass data to Main Activity when I close my Second Activity here is the code
IntentTest1(MainActivity)
public void onClick(View arg0) {
// TODO Auto-generated method stub
MyClass.myToast("Clicked",getApplicationContext());
Intent myIntent = newIntent(getApplicationContext(),SecondPage.class);
startActivityForResult(myIntent,0);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == 0 && resultCode == RESULT_OK)
if(data.hasExtra("title"))
{
MyClass.myToast(""+resultCode+""+requestCode, getApplicationContext());
String str = data.getExtras().getString("title").toString();
titleText.setText(str);
}
super.onActivityResult(requestCode, resultCode, data);
}
SeconPage
public void finish()
{
Intent returnIntent = new Intent(getApplicationContext(),Intenttest1.class);
returnIntent.putExtra("Welcome Back!!","title");
setResult(RESULT_OK, returnIntent);
// below was for tosting and it works!!
MyClass.myToast("finally",getApplicationContext());
super.finish();
}
I think there is some mistake in receiving the intent ,I couldn't figure out. Answers and Advises are needed thanks in advance
The first problem is when you create your
Intent
to send back to the firstActivity
. Since you are usingstartActivityForResult()
you want to use an empty constructor. So changeto
The second problem is that you have your
key/value
pair backwards in yourExtras
. Thekey
, which is what you look for withgetStringExtra()
etc... should be the first in the pair. So thisshould be
Off-topic
I would consider using relevant names as your
params
. For example, I would change youronClick()
fromto
view
,v
, or something similar makes more sense since the argument actually is a view and it will be more readableI would also recommend using the
Activity
Context
for yourIntent
which you can get from the argument (theView
) passed intoonClick()
. So change it toYou have to use
instead of
in
onActivityResult
.Welcome Back!!
is the key andtitle
is the value for that key in your extras.try this code:
}