How to send String values to another Activity? - java

I want to send string values of latitude and longitude to another class but I'm a little bit confused about how to use it with put extra intent.
Here's my code:
Intent i = new Intent(getApplicationContext(), PlacesMapActivity.class);
//Sending data to another Activity
String latitude = Double.toString(placeDetails.result.geometry.location.lat);
String longitude = Double.toString(placeDetails.result.geometry.location.lng);
i.putExtra("user_lat", latitude);
i.putExtra("user_lng", longitude);
startActivity(i);
Is it right if I try to retrieve the string value like this?
// Getting intent data
Intent i = getIntent();
// Users current geo location
String user_lat = i.getStringExtra("user_latitude");
String user_lng = i.getStringExtra("user_longitude");
Please give me your opinion. Thanks.

You must use the same name for the extra in put and in get. For example you put user_lat but then try to get user_latitude, this obviously won't work. Otherwise, it looks fine to me.
Note that you can put double values directly, there is no need to convert to a String. To get them back use getDoubleExtra.

According to your question - yes, it is correct way to pass data from Activity to another one, but you have to remember that your name argument should be the same for putting and retrieving data.
Also the second way to do this is to use getExtras() method. In the second Activity, in which you want to retrieve data:
// Getting intent data
Intent i = getIntent();
Bundle extras = i.getExtras();
// Users current geo location
if(extras != null) { // Check if extras were found
String user_lat = extras.getString("user_latitude");
String user_lng = extras.getString("user_longitude");
}
The difference between both ways is:
getStringExtra() method returns null if String with specified name could not be found
getExtras() method returns null if no extras was found

Related

Android Runtime error on passing info between activities

I have 2 activities in my assignment: MainActivity and Country_Activity.
I'm trying to pass 2 inputs the user puts in MainActivity:
int counter
String Country
But the app always crashes here: (this is Country_Activity)
private void Update(){
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intCounter", 0);
String country = mIntent.getStringExtra("country");
counterTextView.setText(intValue);
countryTextView.setText(country);
if (country.equals("canada")){
flagView.setImageResource(R.drawable.canada);
}
else if (country.equals("us")){
flagView.setImageResource(R.drawable.us);
}
}
Specifically on the lines "setText" for each variable.
Everything else works. I can't figure out why they wouldn't.
Thanks!
Usually the extras that are passed from one activity to another are read inside on onCreate() where all the needed initialization of variables and views is made.
In your case I see that you get the extras inside another method (maybe it's called inside onCreate()?).
So you forgot to initialize the textviews:
TextView counterTextView = findViewById(R.id.countersomething);
TextView countryTextView = findViewById(R.id.countrysomething);
also another error that you will encounter later is this:
counterTextView.setText(intValue);
change it to:
counterTextView.setText(String.ValueOf(intValue));
Don't pass an integer value inside setText() because it will be treated as the id of a resource.

is it possible to retrieve google links from strings?

i currently have a menu item that looks like the following
case R.id.action_settings_rate_app:
Intent intent3 = new Intent(Intent.ACTION_VIEW);
intent3.setData(Uri.parse("market://details?id=com.raptools.app.raptools"));
startActivity(intent3);
bRet=true;
break;
where it says .setData(Uri.parse i would like to call a string and place the link market://details?id=com.raptools.app.raptools in the string.... is this possible to do?
the reason i want to do this is because i have over 25 java files that all call the menu and have the same links in them..... if i could call the string i would only need to change the one string value instead of having to change all the menu items one by one
thanks in advance
It's totally possible, for that you need handle the links, see this link.
So, in your Activity you can get the parameters.
eg.:
MyActivity1
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("my-scheme://my-domain.com/params1"));
startActivity(intent);
MyActivity2
#Override
protected void onCreate(Bundle savedInstanceState) {
...
Uri data = getIntent().getData();
String p = data.getLastPathSegment(); // Variable p is params1.
}
Look into using a Java Properties file to store this value (and possibly others) for your application. If you do this, you can just change the values in the .properties file and your code can pick up the changes.
Hi as per my understanding with your
You want to place link into string.so that it will be easy for you to change at one place
Let me know if I misunderstand your question
You can add link into String/ String builder
For example
Initialize string variable with link
Like
String urlLink="market://details?id=com.raptools.app.raptools";
case R.id.action_settings_rate_app:
Intent intent3 = new Intent(Intent.ACTION_VIEW);
intent3.setData(Uri.parse(urlLink));
startActivity(intent3);
break;
You can add string variable into separate class and declared String variable as public static into it
So that using class name you will get the urlLink wherever you want in the application

Extract.String Null? No Luck.

I get a nullPointerException on status variable on this line of code : if (view.getId() == R.id.button && status.equals("Dorado"). Now ive looked on many threads in here and i havnt really gotten much luck with this exception. Like many others, i pass a string from activity 1 to activity 2, except this string is extracted from the textview when it is pressed(Dorado).
Activity 1:
TextView text = (TextView) view;
String selection = text.getText().toString();
Bundle b = new Bundle();
b.putString("Selection", selection);
Intent i = new Intent(MunicipioList.this,SubestacionInfo.class);
i.putExtra("extra", b);
startActivity(i);
Acitivity 2:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subestacion_info);
Bundle extras = getIntent().getExtras();
if (extras != null) {
extras = extras.getBundle("extra");
status = extras.getString("Selection");
}
}
I know the bundle isnt necessary i was just experimenting since i was still getting Null with other codes. Ah one more thing, the status varoable is global, declared right at the beginning of the activity as "public String status;" so i dont believe that to be the issue here, Any help? :)
Lets break this down. If you get an NPE in this line:
if (view.getId() == R.id.button && status.equals("Dorado"))
then either:
view is null, or
R.id is null (which I think is impossible), or
status is null.
You should be able to work out which with a debugger, or by adding a traceprint. But I suspect that it is status.
You say:
Ah one more thing, the status variable is global, declared right at the beginning of the activity as "public String status;" so I don't believe that to be the issue here.
That declaration does not initialise status. Did you initialize status following the declaration? If not, its initial value will be null, and that would be sufficient to cause an NPE ... if you never changed it!

getStringExtra() always throws NullPointerException

Main activity:
Intent intent = new Intent(Main.this, Secondary.class);
intent.putExtra("name",value);
startActivity(intent);
Secondary activity:
String value = getIntent().getStringExtra("name")
What's wrong here? I've searched a lot without success...
Thanks
Try this:
In the MainActivity:
//Make sure Secondary is an Activity name. Secondary.class.
Intent intent = new Intent(MainActivity.this, Secondary.class);
intent.putExtra("name",value);
startActivity(intent);
In the Secondary Activity:
String value = getIntent().getExtras().getString("name");
You need to get the bundle first and then extract the string from it.
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
bundle.getString("name");
}
Both should work. The second one is to check if the bundle is null.
When you call putExtra(...), make sure the value object is a String. If you're passing any other object, make sure to explicitly call value.toString(), especially if dealing with GUI components.
See here for more information: Android Intent.getStringExtra() returns null
I have used this method times. Just make sure value has a value or initialized.You can use Log or System.out.println(value); after .putExtra to see(in console tab) if value is null. and in second activity too.
Change this line
String value = getIntent().getStringExtra("name");
TO this line
String value = getIntent().getString("name");
I have discovered I have an issue in my code it was my fault. It wasn't an Intent problem. Thank you all.
You can try this -->
intent.putExtra("name", textView.getText().toString());
If the error still occurs, check-in the Second Activity that you are using the right id path...:-
value = findViewById(R.id.);

passing data between android activities

I am trying to pass data between two activities in my android application however when
i try the run the on click method that sends the data the app crashes.
This is the code of the activity that works out my calculation is trying to send it to another activity called result. The variable output I am trying to send is a double.
Intent myIntent = new Intent(BMIMetric.this, result.class);
BMIMetric.this.startActivity(myIntent);
myIntent.putExtra("key", output);
Then on the results page I am trying to take the variable with this code
Intent myIntent = getIntent();
double output = (Double) getIntent().getExtras().get("Key");
First, you have an order issue (edited code):
Intent myIntent = new Intent(BMIMetric.this, result.class);
myIntent.putExtra("key", output);
BMIMetric.this.startActivity(myIntent);
You need to set extras before starting the new Activity.
Then in your other Activity do:
Intent myIntent = getIntent();
double output = getDoubleExtra ("key", -1.0);
getDoubleExtra() seems like a better fit since you're assigning to a primitive data type.
Also, as Blumer mentioned, "key" had a different spelling. You need the same spelled key, that's how it works. Otherwise you're mentioning something different and it won't be found.
And as an addition to using getExtras() - if you use getExtras().get() and the key is not found, you will get null in return. Although Doubles can auto-box/unbox nowadays, if you do
Double doubleObject = null;
double d = doubleObject;
You will still get a NullPointerException.

Categories