Intent Extras.getString() not comparing correctly -- Android - android

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 ===

Related

Passing data from two activities to a third activity in android

have total 3 activites. I pass the data from the first activity like this:
Intent intent = new Intent(getActivity(), Movie_rev_fulldis_activity.class);
intent.putExtra("mov_pos", position + "");
startActivity(intent);
this working fine all data visible to my second activity but i want to display
one filed item to third activity when i click second activity image
here my second activity
youtube_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent youtube= new Intent(getApplicationContext(),PlayYouTube1st.class);
youtube.putExtra("youtubeLink",youtubeLink);
startActivity(youtube);
// Toast.makeText(Movie_rev_fulldis_activity.this,
// youtubeLink, Toast.LENGTH_LONG).show();
}
});
youtubeLink=Reviews_update.revData.get(mov_pos).getYoutubeLink();
Toast.makeText(Movie_rev_fulldis_activity.this,
Reviews_update.revData.get(mov_pos).getYoutubeLink(), Toast.LENGTH_LONG).show();
mov_pos=Integer.parseInt((getIntent().getExtras()).getString("mov_pos"));
in second activity i am getting values but when i send one filed to third activity that value passing null any one please help me i stuck in their,
I want to show YoutubeLink field sencnd activity to third activity how to parse that any one please help
In FastActivity:
Intent in = new Intent(FastActivity.this, SecondActivity.class);
in.putExtra("a", yourdata);
startActivity(in);
In SecondActivity:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String a = extras.getString("a");
}
You can also use any static variable and use it in any class
static int a = 5;
And in any other class
int b = classname.a;
classname is the class where static variable is declared.
Make that variable static and then pass
Your variable object reference get change in the THIRD Activity so, it returns null

Start intent activity back to same activity

I am creating an application, surprising I know, and using a quick back button to return the user to a previous listing. The code below is the intent portion that starts the activity. Now it is sending the activity back to itself with an "LvPos" variable to determine which position it just re-start itself at.
Spinner spinMe = (Spinner)findViewById(R.id.spinner1);
Intent backIntent = new Intent(null, null, getBaseContext(), MainActivity.class);
int itemSelected = spinMe.getSelectedItemPosition();
backIntent.putExtra("LvPos", itemSelected);
startActivity(backIntent);
Now the code below is the reference in the onCreate method that gets teh LvPos variable. The problem is, when I get to this portion, the LvPos is null. I have the same code for various other intents and all work fine. If anyone can see any glaring issues, let me know as I have to be severely overlooking something.
int positionID = 0;
Bundle extras = getIntent().getExtras();
if (extras != null){
String LvPosBundle = extras.getString("LvPos");
if (LvPosBundle != null)
positionID = Integer.parseInt(LvPosBundle);
}
Thank you in advance.
You are Using the putExtra(String, int) when you are putting the extra.
When retrieving you use:
extras.getString("LvPos");
instead use:
extras.getInt("LvPos");
Store that in an integer instead of string. Then you also don't have to do the parseInt.
Hope this Helps.
-Travis

Passing a String value across Activities?

I am currently attempting to pass a string across activities. The string is used to set an image in the second activity. So the user is clicking a button in the first activity and then the appropriate image is loaded in the second activity based upon what was selected. There are three buttons in the first activity all which should send a String value to the next activity.
This is what I have in my first activity:
Button archerButton = (Button) findViewById(R.id.Button_Archer);
archerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String selection = "archer";
Bundle basket = new Bundle();
basket.putString("key", selection);
Intent i = new Intent(SelectCharacterActivity.this, LevelOneActivity.class);
i.putExtras(basket);
startActivity(i);
finish();
}
});
}
The receiving activity has the following code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.level_one);
ImageView img = (ImageView) findViewById(R.id.Character_Chosen);
Bundle extras = getIntent().getExtras();
String Toon = extras.getString("key");
if(Toon=="archer"){
img.setImageResource(R.drawable.archer);
}
if(Toon=="mage"){
img.setImageResource(R.drawable.mage);
}
if(Toon=="warrior"){
img.setImageResource(R.drawable.warrior);
}
}
I know that the receive if statements section works because if I manually set the value Toon the image will load. So somewhere the information is not being sent or read properly. I followed a tutorial online and but am stumped on this.
issue is Java 101. string equality test is done using the equals method.
Toon.equals("archer");
Extra tip : inverse your test to avoid null pointer exception :
"archer".equals(Toon);
Extra extra tip : considering your cases are mutually exclusive, use if else if to avoid testing all cases.
You are comparing your strings wrong,
Toon=="Anything"
will never be true, you need to use
Toon.equals("Anything")
for it to work.
EDIT:
This is true because "==" will just compare the memory addresses of the Strings, and "Anything" will just have been allocated and definitely won't match Toon. .equals however actually compares the chars in the string.
Also to test things like this try putting in a
Log.i("YourAppName", "Toon value is: " + Toon);
after
String Toon = extras.getString("key");
try to use SharedPreferences, Set it after/with the button-click and get it on 2. Activity OnCreate
If you just want to pass a simple String, you can use the following:
On sending:
Intent i = new Intent(SelectCharacterActivity.this, LevelOneActivity.class);
i.putExtra("key", selection);
startActivity(i);
On receiving:
String selection = getIntent().getStringExtra("key");
If there is no parameter with this key, selectionwill be null.
Try this
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putExtra("email", "lol#hotmail.com");
startActivity(i);
and
Intent i = getIntent();
String myemail = i.getStringExtra("email");
Furthermore, to compare String, use .equals() not ==

Why does the Intent that starts my activity not contain the extras data I put in the Intent I sent to startActivity()?

I explained this badly originally. This is my question: The Intent I send to the startActivity() method, contains a private field, mMap, which is a Map containing the strings I sent to putExtra(). When the target activity starts, a call to getIntent() returns an Intent that does not contain those values. The mMap field is null. Obviously, something in the bowels of the View hierarchy or the part of the OS that started the new activity created a new Intent to pass to it, since the object IDs are different.
But why? And why are the putData() values not carried fowrard to the new Intent?
The activity that starts the new activity extends Activity. Here's the startup code:
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case 4:
i = new Intent(this, StatList.class);
i.putExtra("Name1", "Test1");
i.putExtra("Name3", "Test2");
startActivity(i);
}
}
I've tried the key values with and without the (recommended) complete package name prefix.
In the Eclipse debugger, I have verified the values for the player names are being inserted into i.mExtras.mMap properly.
Here's the code from the startee:
public class StatList extends ListActivity {
private final StatsListAdapter statsAdapter;
public StatList() {
statsAdapter = StatsListAdapter.getInstance(this);
} // default ctor
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent i = getIntent();
final Bundle extras = i.getExtras();
< more code here >
}
When execution gets to this method, mIntent.mExtras.mMap is null, and mIntent.mExtras.mParcelledData now contains some values that don't look sensible (it was null when startActivity() was called). getIntent() returns mIntent.
I've also tried startActivityForResult(), with the same result.
From the docs and the samples I've seen online & in the sample apps, this should be easy. I've found another way to meet my immediate need, but I'd like to know if anyone can help me understand why something this simple doesn't work.
In your main Activity:
i = new Intent(this, StatList.class);
i.putExtra("Name1", "Test1");
i.putExtra("Name3", "Test2");
startActivity(i);
Then in StatList.class
Bundle extras = getIntent().getExtras();
String name1 = extras.getString("Name1");
String name3 = extras.getString("Name3");
Log.i("StatList", "Name1 = " + name1 + " && Name3 = " + name3)
Update the following two line
final Intent i = getIntent();
final Bundle extras = i.getExtras();
Replace it with
Bundle extras = getIntent().getExtras();
if(extras!= null){
String var1= extras.getString("Name1");
String var2= extras.getString("Name2");
}

getIntent.getExtras() does not return null but has no values.

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 .

Categories

Resources