how can i pass different value from different intent inside another activity. i.e
Activity A:
ButtonA .onclick{
intent.putExtra("name", screenname);
intent.putExtra("email", description);
intent.putExtra("pic", twitterImage);
startActivity(intent);
}
ButtonB. onClick{
intent.putExtra("anothervalue", json_object.toString())
}
Activity B:
Intent intent = getIntent();
String getValue = intent.getStringExtra("value from any of the button clicked")
While David Rauca answer is essentially correct, you will likely face NullPointerException.
getIntent().getStringExtra("firstvalue") will cause NPE if there is no value with name 'firstvalue'.
You should check whether or not value exist like this.
if(getIntent().hasExtra("firstvalue")) {
String firstvalue = getIntent().getStringExtra("firstvalue");
}
#Mandeep answer is correct. But if you have more values coming from activity then here is the solution. Thanks to Mandeep
Intent i = getIntent();
String getValue1,getValue2,getValue3;
if(i.hasExtra("AFirstValue") && i.hasExtra("ASecondValue") && i.hasExtra("AThirdValue")){
getValue1 = i.getStringExtra("AFirstvalue");
getValue2 = i.getStringExtra("ASecondValue");
getValue3 = i.getStringExtra("AThirdValue");
}
if(i.hasExtra("anotherFirstvalue") && i.hasExtra("anotherSecondvalue") && i.hasExtra("anotherThirdvalue")){
getValue1 = i.getStringExtra("anotherFirstvalue");
getValue2 = i.getStringExtra("anotherSecondvalue");
getValue3 = i.getStringExtra("anotherThirdvalue");
}
String getValue = intent.getStringExtra("firstvalue") // in order to get the first value that was set when user clicked on buttonA
or
String getValue = intent.getStringExtra("anothervalue") // in order to get the the value that was set when user clicked on buttonB
Activity B code should be like this
Intent intent = getIntent();
String firstvalue = intent.getStringExtra("firstvalue");
String anothervalue = intent.getStringExtra("anothervalue");
if(firstvalue != null)
// called from Button A click
else if(secondvalue != null)
// called from Button B click
Intent intent = getIntent();
String getValue = null;
if(intent.hasExtra("firstvalue")){
getValue = intent.getStringExtra("firstvalue");
}
if(intent.hasExtra("anothervalue")){
getValue = intent.getStringExtra("anothervalue");
}
Related
I have an Activity called searchProcedures which allows a user to select from a listview of medical procedures. I navigate to this activity from two other activities called searchHome and describeVisit. I needed a way for searchProcedures to know which activity it should navigate back to onClick. So I pass an intent.extra from searchHome or describeVisit (key:"sentFrom" value""). Then in searchProcedures I use the following code to determine which class to navigate to.
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if(!extras.isEmpty()){
if(extras.containsKey("sentFrom")){
if(extras.getString("sentFrom") == "searchHome"){
returnIntent = new Intent(searchProcedures.this, searchHome.class);
}
else if(extras.getString("sentFrom") == "describeVisit"){
returnIntent = new Intent(searchProcedures.this, describeVisit.class);
}
else{
Log.d("failed", "the value of getString is " + extras.getString("sentFrom"));
}
}
}
Checking the Log values, the correct values are being passed to and from activity, but when I check extras.getString("sentFrom") == "searchHome/describeVisit" it comes back as false, and returnIntent remains un-initialized. I have tried putting .toString after the .getString to no avail.
1.
== compares the object references, not the content
You should use:
"searchHome".equals(extras.getString("sentFrom"))
Remeber to check blank space,...
2.
You can use a static variable in your SearchProceduresActivity to check where it comes from
SearchProceduresActivity
public static int sFrom = SEARCHHOME;
SearchHomeActivity:
Intent myIntent = new Intent(SearchHomeActivity.this, SearchProceduresActivity.class);
SearchProceduresActivity.sFrom = SEARCHHOME;
startActivity(myIntent);
DescribeVisitActivity:
Intent myIntent = new Intent(DescribeVisitActivity.this, SearchProceduresActivity.class);
SearchProceduresActivity.sFrom = DESCRIBEVISIT;
startActivity(myIntent);
SEARCHHOME, DESCRIBEVISIT value is up to you
Hope this help!
String compare should use equal not ===
i have to activities:
activity 1 with twoo edit text and
activity 2 with a list view.
Everytime i fill the forms in activity1 and press the button "send" i want that all i have wrote in the two edit texts go in one row of the list view of activity 2.
I have tried and it is the result but i don't know how i have to continue:
this is the code of activity1 when the button is pressed:
buttonSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "Button Send Report Clicked......");
object=object.getText().toString();
description = editDescription.getText().toString();
getCoordinates();
Intent i=new Intent(FirstReporting.this, MyList.class);
i.putExtra("object", object);
i.putExtra("description", description);
startActivity(i);
}
});
this is the code of activity2:
arrayAdapterListReports arrayAdapter = new ArrayAdapterListReports(this, R.layout.item_list_reports, listReports);
listView=(ListView)findViewById(R.id.listView1);
listView.setAdapter(arrayAdapter);
and then?
In that other activity you can do this to get the values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String objStr = extras.getString("object");
String descStr = extras.getString("description");
// Do what you want with these now ...
}
Check out the Receiving Simple Data from Other Apps guide.
In your second Activity, you can retrieve the Intent used to start Activity2 using getIntent().
You can then use that Intent object to get your data like so:
Intent i = getIntent();
Bundle extras = i.getExtras();
String obj = extras.getString("object");
String desc = extras.getString("description");
I want to pass the value of the position in one activity class to another...
My code is as follows:
protected void onListItemClick(ListView listView, View v, int position,
long id) {
switch (position) {
case 1:
Intent newActivity1 = new Intent(this, BucketItemActivity.class);
newActivity1.putExtra("bucketno", position);
startActivity(newActivity1);
break;
case 2:
Intent newActivity2 = new Intent(this, BucketItemActivity.class);
newActivity2.putExtra("bucketno", position);
startActivity(newActivity2);
break;
}
}
The activity class that will receive it..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bucket_item);
String value = getIntent().getExtras().getString("bucketno");
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(value);
setContentView(textView);
}
But i always get a null in the String value...
Please help.
Replace this,
String value = getIntent().getExtras().getString("bucketno");
with
int value = getIntent().getExtras().getInt("bucketno");
You are trying to pass int value but retrieving String Data. That's why you are getting the nullpointerException.
You can use :
In first activity ( MainActivity page )
Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("YourValueKey", yourData.getText().toString());
then you can get it from your second activity by :
In second activity ( SecondActivity page )
Intent intent = getIntent();
String YourtransferredData = intent.getExtras().getString("YourValueKey");
String value = Integer.toString(getIntent().getExtras().getInt("bucketno"));
Bundle extras = getIntent().getExtras();
if (extras != null) {
String data = intent.getExtras().getString("key").toString();
}
From the First Activity
Intent i=new Intent(getApplicationContext(),BookPractionerAppoinment.class);
i.putExtra("prac","test");
startActivity(i);
Getting values in Second ACT Activity
String prac=getIntent().getStringExtra("prac);
For Serialized objects:
Passing
Intent i=new Intent(getApplicationContext(),BookPractionerAppoinment.class);
i.putExtra("prac",pract);
startActivity(i);
Getting
pract= (Payload) getIntent().getSerializableExtra("prac");
Use:
String value = getIntent().getExtras().get("key").toString();
getIntent().getExtras() will give you Boundle. get() method can be used to fetch the values.
In addition who has different sittuation
double userDMH = Util.getInstance(TakeInfoOne.this).calculateBMH(userGender, kg, talll, currentAge, activityy);
Intent intentTogeneral = new Intent(TakeInfoOne.this, TakeInfoTwo.class);
intentTogeneral.putExtra("user_current_age",userDMH );
startActivity(intentTogeneral);
If you put other primitives like double , boolean , int just dont forget to type correct format while geting the value in secont Activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
double value = extras.getDouble("user_current_age");
txt_metabolism.setText(""+value);
}
Here with extras.getDouble() type your concerned value type like
extras.getInt("user_current_age");
extras.getBoolean("user_current_age");
extras.getString("user_current_age");
Question is simple, I am not exactly new to Android but I cannot, for the life of me, retrieve the extras passed via an intent from Activity A to Activity B.
See Activity A: This is actually a ListFragment, that implements onListItemClick() to start another activity via an intent.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
Intent i = new Intent(getActivity(), ExpandedTweetView.class);
twitter4j.Status status = adapter.getItem(position);
Bundle extras = new Bundle();
extras.putString(KEY_TEXT, status.getText());
extras.putString(KEY_HANDLE, status.getUser().getScreenName());
extras.putString(KEY_NAME, status.getUser().getName());
extras.putString(KEY_TIMESTAMPS, status.getCreatedAt().toString());
extras.putLong(KEY_RETWEETS, status.getRetweetCount());
i.putExtra(KEY_EXTRAS, extras);
startActivity(i);
}
This part just works, I tested it usng Log.v(TAG, "status.getText()" to make sure that the error was not coming from the Adapter passing an empty item via getItem().
Here is the code on Activity B:
public class ExpandedTweetView extends Activity {
TextView text;
TextView name;
TextView handle;
TextView createdAt;
TextView retweets;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.expanded_list_item);
Bundle extras = getIntent().getExtras();
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
text = (TextView) findViewById(R.id.h_content);
name = (TextView) findViewById(R.id.h_name);
handle = (TextView) findViewById(R.id.h_handle);
createdAt = (TextView) findViewById(R.id.h_timestamp);
retweets = (TextView) findViewById(R.id.h_retweet_count);
if(extras != null) {
text.setText(extras.getString(TimelineFragment.KEY_TEXT));
name.setText(extras.getString(TimelineFragment.KEY_NAME));
handle.setText(extras.getString(TimelineFragment.KEY_HANDLE));
createdAt.setText(extras.getString(TimelineFragment.KEY_TIMESTAMPS));
retweets.setText(String.valueOf(extras.getLong(TimelineFragment.KEY_RETWEETS)));
}
}
As you can see, I believe I am using the right code to obtain the extras, using the same code on other applications worked. Not sure why, when the ExpandedTweetView is created via an intent, ALL of the textViews are empty. See: https://www.dropbox.com/s/pso6jbyn6rpks9n/empty_activity.png
What is even MORE strange is that I had initially tried checking to see if the bundle was null by calling this:
if (extras == null) {
Log.v(TAG, "Extras are empty :(");
}
But that line was never executed, meaning the bundle is not null. I also thought that maybe the keys being used to retrieve the individual Strings from the bundle were mismatching; however, in order to remedy that I decided to create constants that could be used on both sides. As you can see on the code, both the key to set the Extra and the Key to retrieve the Extra are the same.
Any ideas as to what the heck is going on?
Bundle extras = getIntent().getExtras();
if (extras != null) {
extras = extras.getBundle("KEY_EXTRAS");
String status = extras.getString("KEY_TEXT");
}
Try adding the extra variable to intent rather than in Bundle
Ex:
i.putExtra(KEY_1, a);
i.putExtra(KEY_2, b);
i.putExtra(KEY_3, c);
Then retrieve it from other activity from intent
Ex:
getIntent().getStringExtra(KEY_1) ;
In Activity A:
Intent i = new Intent(MainActivity.this, AnotherActivity.class);
Bundle b = new Bundle();
b.putString("thisc", "my name");
i.putExtra("bundle", b);
startActivity(i);
In Activity B:
**Bundle bun = getIntent().getBundleExtra("bundle");
if (bun.containsKey("thisc")) {
Log.i("TAG", bun.getString("thisc"));
} else {
Log.i("TAG", "no thisc");
}**
Check the first line of code in Activity B, that's the main difference actually!!
//put value
Intent inatent = new Intent(this,text.class);
inatent_logo.putExtra("message","hello");
startActivity(inatent);
//get vale
String msg = getIntent().getStringExtra("message").toString();
It's Difficult to maintain intent to Bundle and Bundle to Intent if number of data you want ti share from one Activity to Other Activity.
just Simply use Intent with PuExtra() with different argument.
you can pass number of data in intent like :
Sender's Side :
Create your Intent.
Intent My_Intent = new Intent(FromClass.this,ToClass.class);
Add your value which you want to share with other activity.
My_Intent.putExtra("VAR_A",a_value);
My_Intent.putExtra("VAR_B",b_value);
My_Intent.putExtra("VAR_C",c_value);
Call your Intent.
StartActivity(My_Intent);
Receiver's Side :
Intent My_Intent = getIntent();
First_Value=My_Intent.getStringExtra("VAR_A");
Sec_Value=My_Intent.getStringExtra("VAR_B");
Thred_Value=My_Intent.getStringExtra("VAR_C");
I Think its Easy for you to Handel your data from one Activity to other .
I've two String Arrays like that ,
String[] htmlArray = {
"file:///android_asset/Pinocchio/OPS/chapter-001.xml",
"file:///android_asset/Pinocchio/OPS/chapter-002.xml",
"file:///android_asset/Pinocchio/OPS/chapter-035.xml",
"file:///android_asset/Pinocchio/OPS/chapter-035.xml"
};
String[] htmlArray1 = {
"file:///android_asset/Harry_Potter/OEBPS/part1.xhtml",
"file:///android_asset/Harry_Potter/OEBPS/part2_split_000.xhtml",
"file:///android_asset/Harry_Potter/OEBPS/part18_split_000.xhtml",
"file:///android_asset/Harry_Potter/OEBPS/part18_split_001.xhtml",
};
then, I put two ImageView in another class,
private void init() {
pino_cover = (ImageView) findViewById(R.id.pino_cover);
pino_cover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reader=new Intent(instance,ReaderScreen.class);
reader.putExtra("pino",true);
startActivity(reader);
}
});
harry_cover=(ImageView) findViewById(R.id.harry_cover);
harry_cover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reader=new Intent(instance,ReaderScreen.class);
reader.putExtra("harry",true);
startActivity(reader);
}
});
}
Then, if I click the Pino Image, I could get the data through htmlArray .
Intent i=getIntent();
Bundle b = i.getExtras();
String newText = b.
String setext=b.getString("harry");
if (newText=="pino")
pages = htmlArray;
else
pages = htmlArray1;
but if I click the Harry Image, it'd been taken to get the data through the htmlArray too. I want to get htmlArray1.
How could I get ?
You are putting only a boolean to your intent, but you could use .putExtra(mStringArray, htmlArray1); as this method exists to pass arrays through intents...?
Plus, to compare two strings in java, you MUST NOT do == but .equals(""). In your case if(newText.equals("harry))...
EDIT
Ok, in an easier version, you have that :
Intent i=getIntent();
Bundle b = i.getExtras();
String newText = b.
String setext=b.getString("harry");
if (newText=="pino")
pages = htmlArray;
else
pages = htmlArray1;
replace it by that :
Intent i=getIntent();
Bundle b = i.getExtras();
String newText = b.
String setext=b.getString("harry");
if (newText.equals("pino"))
pages = htmlArray;
else
pages = htmlArray1;
This should logically work.
I think the error lies in your using "==" to compare 2 string as mentioned above.
Please use str1.equals(str2) instead of str1 == str2.
And the answer by Sephy suggests you pass the 2 html arrays to the called activity as well. If for some reasons, the called activity can still access the 2 arrays then you can just do as you have done.
Also, in the map you passed, if you use 2 different keys (one is "harry", and one is "pino"), it seems to defeat the purpose. I suggest sth like:
on harry event:
i.putExtra("data", harry_html_array)
on pino event:
i.putExtra("data", pino_html_array)
Inside the called activity:
array = extras.getStringArray("data");