I have a weird problem in the setup of my Android application which is to do with me passing values between differen classes(or screens). Basically i have a menu class that passes to this class(classA) and then third class(classB). ClassA has a button to go to classB which will then do an operation and pass doubles back to classA.
The problem lies within these lines of code:
Intent it = getIntent();
if (it != null)
{
Bundle b = getIntent().getExtras();
double result = b.getDouble("weight");
double result2 = b.getDouble("height");
if((result > 0)&&(result2 > 0))
{
mDateDisplay.setText("weight: "+result+"height"+result2);
}
}
else
{
//do nothing
}
the problem is that it crashed the app when i come to the screen from the menu i have set up. initailly i had no idea what the problem was but then i realised that the problem lies with the intent. due to me coming from a previous screen there is an intent sent to this class. so when it checks for null intent it finds the intent sent from the menu. this means that running the if statement will happen and cause an error.
i’m wondering if there is a solution to this problem.
As I understand it, this code is failing because it receives an Intent that it’s not equipped to handle. It tries to get a double from an Intent that doesn’t contain a double.
The solution is to differentiate your Intents so that you only call code when you know you’ve received the Intent that goes with that code. That is, some aspect of each Intent you use should be unique, so that you can tell Intent A from Intent B.
The best way to do this is to create your own custom Intent action, using a namespace you own or control, such as “com.example.mydomain.intent.intent1”. That way, you can test to see if the incoming intent is the one you want to handle.
If you’re passing intents around in your application, and you don’t outsiders to use them, then don’t use intent filters. Instead, create the intent based on the ComponentInfo of the target activity. You can still use actions.
A fault of the code you’re showing here is that it will get called for any incoming intent, and if you’re using intent filtering, you could accidentally receive an intent from another application! In general, either use strong intent filtering or send intents by component name, and always test intents in your code before you act on them.