Android intent problem: why arent these 2 variables equal? - android

Im going a little crazy with this. In my app, i take a string which represents a bus stop, and then have an algorithm that matches it and displays its schedule. I needed to make that window an activity instead of a dialog and am using intents. Heres my code to send the intent:
Intent intent = new Intent(context, StopDialogActivity.class);
intent.putExtra("stop name", stopName);
context.startActivity(intent);
and heres my code to retrieve the string (in my onCreate):
Bundle extras = getIntent().getExtras();
departureStopName=extras.getString("stop name");
The string displays properly, but it isnt equal to a test string i have which is the same stop. The intent sends an integer over correct, what am i doing wrong with processing strings?

Make sure when comparing strings to use testName.equals(stopName) and not testName == stopName.
Using .equals() uses the equals method in the String class which compares the content. Using == compares the String Objects themselves, which need to be the same object in memory to evaluate to true.

Ah, my problem was while I use .equals() as a test to see if it was coming through okay, i was using == in the part of my code that broke.

Related

Passing variables using intents - Android

I'm currently developing an android application that makes use of Google Places API.
I have 2 activities that I want to pass a variable between. I have tried passing by Intent using putExtras and getExtras.
I have been having issues with the getExtras. I have debugged my code, used breakpoints and an output of the variable to the log.
Here is my code for the activity of which I want to pass the variable from:
Intent mapIntent = new Intent(getBaseContext(), MapsActivity.class);
Spinner distanceSpinner = (Spinner) findViewById(R.id.spinner_distance);
String radius = distanceSpinner.getSelectedItem().toString();
mapIntent.putExtra("radius", radius);
Log.e("Passer", String.valueOf(radius)); //Shows that value is not = null.
startActivity(mapIntent);
The log out put for this class is correct and displays the variable.
Here is the code for my class that I want to pass the variable to:
Intent filterIntent = new Intent(getBaseContext(), LocateFilterActivity.class);
Bundle bd = filterIntent.getExtras();
String radius= (String) bd.get("radius");
Log.e("TESTER", String.valueOf(radius));
startActivity(placeIntent);
The log does not actually output anything for this class. I know it can reach and execute the line of code through debugging.
I have tried coding this several different ways following previous SO questions/answers but not having much luck.
Any help would be much appreciated :)
You can access data which were passed to an activity with getIntent().getExtras() method which you can call in a newly created activity that you have created with startActivity(intent) call. :)

Android: why use intent.putExtra() method?

This is a real noob question I'm sure, but I am finding it quite perplexing.
Why an earth would you want to ever use intent.putExtra method to share information between classes in Android?
Let me explain. I am making my first Android app following the instructions from the developers guide (I am already at a moderate level with Java) and I am using some code that looks like this:
//Class field
//key holds string????? not fully understanding this...
public static final String EXTRA_MESSAGE = "self.anon.myfirstapp.MESSAGE";
//this method is activated by a button being pressed
public void sendMessage(View view) {
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
//puts string message inside the string EXTRA_MESSAGE - why????
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
OK firstly I want to point out I see what is happening and for the most part how it works (am just confused by the field declaration = "myClassPath" why?)...
BUT....
Surely it would be easier just to have a static field called:
public static String message;
then my method would look like this:
public void sendMessage(View view) {
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
message = editText.getText().toString();
startActivity(intent);
}
Then when my class DisplayMessageActivity needs the string message he just calls for:
String message = myClass.message;
That seems so much more straight forward. What is with the creation of the new string EXTRA_MESSAGE which just seems to hold the string message and why send it with the intent when my other class can access this info directly anyway -- and what does the field declaration with the "self.anon.myfirstapp.MESSAGE" mean? I can find no such folder or path leading to anything.
As someone else stated there are often situations (such as a screen rotate) in which the android system destroys and restarts the app - so all variable data is lost. It would only work consistently the way you suggest if your data is hard coded as a final variable. That is not the only reason for using intents though.
The great thing with using an intent to pass information is that you can use the intent not just to communicate with sub-activities within your own application but to any activity installed on that android system. For example you may want to launch an intent which starts the phone application and include as an extra the number that you want to call.
Perhaps a better question than yours though is "why would you not use intents to pass information?" The intent.putExtra() method allows you a convenient flexible and straight forward method to pass as much information as you like in a safe and secure way to any other activity.
intent.putExtra(EXTRA_MESSAGE, message);
works like a key value pair, when you want to retrieve the information from the intent you can simply do intent.get<type>Extra and get said information, in this case, intent.getStringExtra("self.redway.myfirstapp.MESSAGE'). its simply the key to retrieve the information, it does not have to be your entire classpath.
it could just as easily be intent.putExtra("message",message).
They are helpful when passing information that you don't necessarily want to reveal to another class but you do want it to be able to get that information in another manner from what i have found.
message = myClass.message It is not always certain that this will retain its value especially when it extends Android framework classes like Activity. When your activity is recreated(change of screen orientation) then message can lose its current value and be assigned a default value. myClass.message would work if message was a static field or else you would need to provide getter and setter methods for object of the Activity Class. Well creating objects of activity class is unheard of in my experience.

getStringExtra - Public Static Final - The Busy Coder's Guide to Android

I am on page 301 of this book and it is an example of an Activity getting "extras" from the intent that started it. I am fairly new to Java so maybe am missing something pretty obvious but...
I thought that when you declare a variable as "final" it meant that it doesn't change.
There is a line of code initialising a final variable:
public static final String EXTRA_MESSAGE="msg";
and then later in onCreate method:
tv.setText(getIntent().getStringExtra(EXTRA_MESSAGE));
The text displayed in the activity is not "msg" but is the string passed from the intent "I am the other activity". Why do you have to have the variable declaration above for the code to work? I don't understand what its doing.
Thanks
You are getting the extra received from another Activity indexed by the key 'msg'.
Like when you do this with the Intent used to start your Activity:
intent.putExtra("msg", "text going in the TextView");
The key is 'msg', but the value you get for the TextView is 'text going in the TextView'
Yes, final means EXTRA_MESSAGE value won't change, but you're not displaying EXTRA_MESSAGE value, but
getIntent().getStringExtra(EXTRA_MESSAGE)
which actually contains the value put in the previous activity. Regarding your question
Why do you have to have the variable declaration above for the code to work?
You don't actually need that variable for the code to work, but it's a good practice to use constant values instead of just hardcoding string values such in.-
getIntent().getStringExtra("msg")
The parameter you pass to getStringExtra is the key to which the String is mapped. All the extras you put in an Intent are mapped as key-value, so if you want to get a value you have to know the key, which must be the same key you used in the previous activity to save the value (with putStringExtra).
http://developer.android.com/reference/android/content/Intent.html#getStringExtra(java.lang.String)

Passing data between activities android [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I pass data between activities in Android?
I have been banging my head across the table for days trying to figure this out. I'm new to both Java and the Android platform and I am writing my second application. In a nutshell, I want the user to enter in some information in the first activity. That activity then takes those inputs and runs a series of mathematical computations and then displays the results in several editTexts in a separate activity. In my mind, the application takes the input, runs the computations and then stores them in some variables. The variables then need to be passed to the second activity which then displays the results. I have most of the application coded and I can get it to work properly if I keep the inputs and displayed results in one activity. Any Ideas on how I can get the displayed results to show up on another activity? Any direction here is much appreciated.
This can be done with use of intent. one of the use of Intent is to pass the data between activities. In your scenario what you need to do is
STEP 1
After taking input from the user, do computation, store result in
the variables
bundle that in the intent which you are using to
start next activity. You can achieve this by below code
Intent intent = new Intent();
intent.putExtra("KeyForResult1", <your variable>);
intent.putExtra("KeyForResult2",<your variable>);
startActivity(this, nextactivity.class);
in the nextactivity you need to get the intent and extract the values in the variable
which can be achieved
variabletype variable = getIntent().getExtras().get("KeyForResult1");
variabletype variable = getIntent().getExtras().get("KeyForResult2");
You can use this:
ActivityOne.class:
//compute the data and get the result here
//suppose results are,
int resultInt=24;
String resultString="abc";
Intent intent=new Intent(getApplicationContext(),ActivityTwo.class);
intent.putExtra("ResultInInteger",resultInt);
intent.putExtra("ResultInString",resultString);
startActivity(intent);
this will open ActivityTwo.class,where you can get the data like:
int resultInt=getIntent().getIntExtra("ResultInInteger");
String resultString=getIntent().getStringExtra("ResultInString");
I was able to figure it out with a mixture of data I had researched. It seems what finally worked was
int resultInt=24;
Intent myIntent = new Intent(CalPalActivity.this, ResultsActivity.class);
myIntent.putExtra("intVariableName", resultInt);
startActivity(myIntent);
in the first activity and
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
in the second. Why it worked like this and kept giving me errors such as "the method getIntExtra(String, int) in the type Intent is not applicable for the arguments (String)" in the second activity I'll never know. Even the Quick-fixes didn't fix it (I just kept getting new errors). All in all, it's an expensive (5 hour +) but well learned lesson. All of your help was much appreciated. I was able to understand and learn a great deal more about the language. Thank you!
You should read up on Intents. You can store extras in an intent, much like URL parameters. If you use that intent to start your next activity, it will be able to extract the data from the intent's extras.
There are several options. For your task I'd choose passing the data in Intent's extras.
For all options read this
Here is an option.
In first Activity:
Intent yourNextActivityIn=new Intent(this,yourNextActivity.class);
yourNextActivityIn.putExtra("tag",valueToBePassed);
startActivity(yourNextActivityIn);
In second Activity:
//If value is an Integer with default value 1
int value = getIntent().getIntExtra("tag", 1);
else
//if value is a string
String value = getIntent().getStringExtra("tag");

Most effective way of storing Strings in Android

In my app I have 5 String arrays that represent different fields of objects.
i.e.
String_A[1],
String_B[1],
String_C[1],
String_D[1],
String_E[1],
All are attributes of the same object (which is not really an object).
Now I want to store those in order to be able to use them in a new activity that I am creating. Since you are not able to pass objects around I thought that i should save them in Shared preferences.
My question is: Should I save them as separate strings or create a new class with all those fields and then serialize the objects?
Which is the best way in terms of memory usage? In fact is there any other way that you might achieve similar functionality?
Thanks in advance
Mike
If each of those String Arrays are big "enough" and it appears you do want to store them - have you considered Sqlite? SharedPreferences is most effective to store primitive data in key-value pairs. Check this link - it has neat comparison about the options you have - http://developer.android.com/guide/topics/data/data-storage.html
You can pass around objects via an intent. The extras function of an intent can store a bundle and send it to specified activities, however they cannot be called at any time (like from a later activity without being explicitly sent). If this is a one time pass to a different activity, the you'd probably want to use that.
http://developer.android.com/reference/android/content/Intent.html#putExtras%28android.content.Intent%29
Here is an example from a test app I made a while back:
public void onClick(View v) {
switch(v.getId()) { //this references the unique ID of the view that was clicked
case R.id.Button01: //this is what happens when the Button in the XML with android:id="#+id/Button01" is clicked
Intent nameGreet = new Intent(this, MainMenu.class);//creates Intent which will send the EditText input
String theName = firstName.getText().toString();// creates a new string named "theName" which is the text from an EditText called "firstName"
nameGreet.putExtra("helloName", theName);//puts the input from EditText into the Intent, this is a key/value pair
this.startActivity(nameGreet);//setting off the Intent
break;
Then you catch it like so:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main_menu);
String personsname = this.getIntent().getStringExtra("helloName");
welcome = (TextView)this.findViewById(R.id.TextView01);
welcome.setText(personsname);
Hope this helps.
You can pass a Serializable using an Intent.
Intent.putExtra(String name, Serializable value).

Categories

Resources