passing data between android activities - java

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.

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

How the first activity get data of the second activity but only when return of this second one [duplicate]

I have an application that has this transition:
A -> B -> C -> D-> C
Upon entering C , i have to check a flag. Then I have to pass it as intent (let us say intentX = false) to D. After doing something in D , it will then go back to C after pressing a button.
What i did was just pass again the intentX with value true, then startActivity C again.
So what happen is that it created another Activity C.
What i want to happen is that i will not have to start a new Activity C, but use the previous C by just calling super.onBackPressed(). But I cannot pass the new value of the intentX. Is there other way, to achieve what i want. I might have missed some.
What you want is startActivityForResult(). When you go from C to D, instead of using startActivity() use instead startActivityForResult(). Then when you want to return from D to C you use setResult() which can include an Intent object with extras to pass back to C.
I don't recommend doing this in onBackPressed() if you don't have to because this will not be what the user expects. Instead, you should return with this data with an event such as a Button click.
So, in C you will do something like
Intent i = new Intent(new Intent(C.this, D.class);
startActivityForResult(i, 0);
then in D when you are ready to return
Intent i = new Intent();
i.putExtra(); // insert your extras here
setResult(0, i);
then when you return to C you will enter this method (taken from the Docs)
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
// A contact was picked. Here we will just display it
// to the user.
startActivity(new Intent(Intent.ACTION_VIEW, data));
/*
can also get the extra sent back through data
using data.getStringExtra("someKey");
assuming the extra was a String
*/
}
There are some cases where startActivityForResult is not really needed or it is not practical to change all startActivity calls for startActivityForResult.
If the simple case of just starting a previous activity 'again' is needed, my recommendation is: Use the FLAG_ACTIVITY_CLEAR_TOP flag.
Quoting a brief description:
If set, and the activity being launched is already running in the
current task, then instead of launching a new instance of that
activity, all of the other activities on top of it will be closed and
this Intent will be delivered to the (now on top) old activity as a
new Intent.
For example, consider a task consisting of the activities: A, B, C, D.
If D calls startActivity() with an Intent that resolves to the
component of activity B, then C and D will be finished and B receive
the given Intent, resulting in the stack now being: A, B.
So this example
// From ActivityD
Intent intent = new Intent(getApplicationContext(), ActivityB.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // The flag we wanted
intent.putExtra(ActivityB.SOME_EXTRA_THAT_I_NEED_CHANGED, SomeValue); // Example of changing the intent to get something new..
startActivity(intent);
Where you will get that new intent is defined by which launch mode and which flags where used to start it (in this case our ActivityB).
The currently running instance of activity B in the above example will
either receive the new intent you are starting here in its
onNewIntent() method, or be itself finished and restarted with the new
intent. If it has declared its launch mode to be "multiple" (the
default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same
intent, then it will be finished and re-created; for all other launch
modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be
delivered to the current instance's onNewIntent().

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.);

How to send String values to another Activity?

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

Categories