Trying to pass an int between two classes on Android platform - java

I'm trying to pass an int between two classes using a bundle. I have looked online and it seems like it should be easy to do, its just not working for me :( any help is much appreciated! I am trying to pass the int life from one page to another in a simple game.
here is the code for the first page where I am passing it from
int life = 5;
....
if(input.equalsIgnoreCase(teststr))
{
Intent i = new Intent("com.name.PAGETWO");
i.putExtra("com.name.PAGETWO.life", life);
startActivity(i);
mpButtonClick.stop();
}
And on the second page, trying to receive the int
Intent i = new Intent("com.name.PAGETWO");
Bundle extras = i.getExtras();
int temp2 = extras.getInt("life");
int life = temp2;
when i try to run it, it tries to go on to the second page and then just says the application has unexpectedly stopped, but when i comment out the code it continues running as normal, so i know i am definitely putting in the code here wrong somewhere. thanks in advance!

Why would a brand new intent object contain the int you've passed? In the receiver activity, use getIntent() to retrieve the intent that the activity was started with. That intent would contain your extras.

You're creating a brand new Intent on the second page, which of course doesn't have the bundle. Instead, you need to retrieve the calling Intent using getIntent().
Here's how your second page's code could look:
int life = getIntent().getExtras().getInt("life");
EDIT: Looking at your code again, make sure the key name of the extra is consistent on both ends. To be sure, I usually use a final variable for this. So in your second activity (let's say it's ActivityTwo), declare this at the top (outside of onCreate()):
final static public String EXTRA_LIFE = "life";
Then in the calling activity:
Intent i = new Intent(this, ActivityTwo.class);
i.putExtra(ActivityTwo.EXTRA_LIFE, life);
startActivity(i);
(You may have also been constructing your Intent incorrectly; compare my example).
And in the second activity, inside of onCreate():
int life = getIntent().getIntExtra(EXTRA_LIFE, 0);
(You can replace 0 with what you want the default value to be if the extra doesn't exist.)
That way you don't have to worry about typos and can rely on Eclipse's suggestions to make sure you're consistent.

Related

How to make an arraylist of arraylists parcelable in android

My problem is that I have an arraylist of arraylists with custom objects that needs to be passed from one activity to another.
Clearly, let's say I have something like:
ArrayList<ArrayList<Statement>> data;
in one activity and I want to pass it to another. So, first what I have done is to make Statement implement the Parcelable class.
Then in the first activity (sender) I call the putExtra() method by passing it the data.
In the second activity (receiver) I call the getSerializableExtra() method to get data.
That works. But I have read that Parcelable would be better for efficiency etc. and so I tried to call putParcelableArrayListExtra() in the sender activity and the getParcelableArrayListExtra() method on the receiver activity.
But when I do that, I get red underlines indicating sth. like
ArrayList< android.os.Parcelable > is required
in the first activity which is the sender I have the line:
Intent intent = new Intent(SenderActivity.this, ReceiverActivity.class);
intent.putParcelableArrayListExtra(SenderActivity.EXTRA_LISTOFSTATEMENTLISTS, dataListOfStatementLists);
In the receiver activity I have sth. like:
myList = ( ArrayList<ArrayList<Statement>>) getIntent().getParcelableArrayListExtra(EXTRA_LISTOFSTATEMENTLISTS);
What I need to fix ? I know the basics about how to send Parcelable objects from one activity to another. But that was all things like
ArrayList<ParcelableObject> data
I have never done it for nested data like this
ArrayList<ArrayList<ParcelableObject>>
I hope someone can help.
Thanks in advance
This is just another way to do it. I suppose you know how to get the values in other activity.
ArrayList<ArrayList<Statement>> data;
Bundle bundle = new Bundle();
bundle.putInt("size", data.size());
for (int i = 0; i < data.size(); i++) {
bundle.putParcelableArrayList("item"+i, data.get(i));
}
Try this to send Data
Intent intent = new Intent(SenderActivity.this, ReceiverActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("object", List);
in.putExtra("list", bundle);
startActivity(in);
For Recieving Data
Intent i=getIntent();
Bundle bundle= i.getBundleExtra("list");
ArrayList<Statement> list = bundle.getParcelable("object");
Every time you want to pass data from one activity to another one via Intent you have to make sure that the classes where you create the objects that you want to send are implementing Serializable, otherwise it won't work. Your problem could be something related to this so I recommend you to implement Serializable on your classes.

My app skips starting an intent and executes the next code lines?

So I have the following currently:
public void addProject(View v) {
String pn = "";
Bundle extras = new Bundle();
Intent i = new Intent(mMainContext, AddProject.class);
mMainContext.startActivity(i, extras);
if(extras.getString("projectName") != null) {
pn = extras.getString("projectName");
}
}
This is just an example, the first bit is correct though the if statement may not be but this isn't about that block.
What I have noticed is that if I place breakpoints on the new intent, start activity and then the if statement,
Android seems to skip past the startActivity and go onto the if statement.
If I then remove the if statement and run it again, it then launches the intent.
So what I've realised is that it runs to the end of the addProject block and then actually launches the intent...
Why is this? And more importantly, how I do stop it doing that?
Intended outcome is as follows:
1) user presses "Add Project" button
2) intent launched and user inputs project name and presses submit
3) calling intent then receives the p name for use later in the function.
Why is this?
startActivity() is asynchronous. When it returns, the activity is not yet started.
how I do stop it doing that?
You can't.
Intended outcome is as follows: 1) user presses "Add Project" button 2) intent launched and user inputs project name and presses submit 3) calling intent then receives the p name for use later in the function.
Having separate activities may not be the best plan for this (compared with using fragments).
If you wish to use activities, the most natural approach is:
Use startActivityForResult() instead of startActivity()
Have AddProject use setResult() to create a result Intent to deliver back to your first activity
Have your first activity override onActivityResult(), where it can receive a copy of that result Intent and get the results from it
Note that this still will all happen after addProject() returns. However, you will (eventually) get your results.
The Android documentation does not cover this very well, but this is what it has on the subject.
you must use onActivityResult for such task.
From your main Activity use: startActivityForResults(intent) in place
of startActivity();
In your AddProject Activity when user inputs project name and press the
button .
Intent i = new Intent();
i.putExtra("projectName",userInputTextFromEditText);
setResults(RESULT_OK,i)
In your MainActivity
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data){
pn = intent.getExtras.getStringExtra("projectName","");
}
this way you will find your result

Opening apps on buttons

Im trying to open. Google Search on my application. But the problem is. when I click the button. the COMPLETE ACTION USING windows is popping up instead of the google search.. search the net for more than an hour but it seems I cant find the solution.. here is my code..
#Override
public void onClick(View view) {
Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(ComponentName.unflattenFromString("com.google.android.googlequicksearchbox"));
intent.addCategory("android.intent.category.LAUNCHER");
startActivity(intent);
This is due to Android's nature to allow users to make their own decisions. If, for instance, they have Bing installed and prefer it as a search engine over Google, they will have the option to select it. As far as I know, there is no way to open a specific app this way. If the user selects Google and makes it the default app for this action, it will auto-open in successive times, but they must make that conscious decision first.
have you probably tried to follow this guide..?
It describes well about what you might need..
hope it helps..
List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(intent, 0);
for(int i = 0; i < resolveInfoList.size(); i++) {
ResolveInfo info = resolveInfoList.get(i);
if (info.activityInfo.packageName.equals("com.google.android.googlequicksearchbox") {
// that's the one you want
}
}
I don't have Eclipse available right now to test it, but this should help you get there. Also check out the documentation for queryIntentActivities()
PS: I'm not sure about that packageName for google search
Try this. This code will search the meaning of value of query variable on google.
String url = "http://www.google.com/search?q=" + "Meaning of " +query;
Intent intentSearch = new Intent(Intent.ACTION_VIEW);
intentSearch.setData(Uri.parse(url));
startActivity(intentSearch);

Reading string values under if/else commands

Im new to android so im gonna need a little help.
I created four activities in my app.
First activity is the MainActivity.
I assigned a ListView in the first Activity.
From the listView you are redirected to the second activity with a string which says which item you clicked. It doesn't matter which item you selected, but you will be redirected to that second activity only. Only diffrence is that the values of the strings passed are different.
I used this code in the ListView's onItemClick function:
String item = (String) listView.getAdapter().getItem(position);;
Intent i = new Intent(MainActivity.this, Activity2.class);
i.putExtra("item_selected", item);
startActivity(i);
This code redirects me to the second activiy with the string without any problem.
In the second Activity there are two options "Launch Type 1" and "Launch type 2" inside a radioButton group and a button to perform the function.
So i used this code inside the button's onClick method to determine which Activity to go next:
Intent intent = getIntent();
String item = intent.getExtras().getString("item");
RadioButton launch1 = (RadioButton) findViewById(R.id.launch1);
//The problem code:..
if(launch1.isChecked()){
if(item=="ListView_Item1"){Intent launch1=new Intent(this, Launch_activity1.class); startActivity(launch1);}
}
else{
if(item=="Item 1"){Intent launch2=new Intent(this, Launch_activity2.class); startActivity(launch2);}
}
In Eclipse it shows that there are no errors in the code. But when I run it in the Emulator it starts off fine till it reaches the second activity.
When i click the button nothing is done and it does not redirect to any new page...
:(
Please help me in constructing the "if/else" statements in the button...and please do tell me if there are any better ways to achive the task...
Thanks in advance.
Waiting for replies....
In Java, you compare strings using equals() and not ==.
if(item.equals("ListView_Item1"))
Using == you're comparing references and not content.
Use Object#equals() for checking if an object contains same data as another one and == for comparing if two references are referencing the same object.
use equals() for comparison of String or Objects in java !
so your code should be :
if(launch1.isChecked()){
if(item.equals("ListView_Item1")){Intent launch1=new Intent(this, Launch_activity1.class); startActivity(launch1);}
}
else{
if(item.equals("Item 1")){Intent launch2=new Intent(this, Launch_activity2.class); startActivity(launch2);}
}

How to save an intent from one class to another class

I am new to Android so apologies if I am asking something silly. I am trying to develop an alarm clock application - basically, it's my final project and I am trying to develop an alarm like there is in API level 2.3.3.
I have designed the list view that takes input through a dialog box like time. I have also coded it to set an alarm.
Now I want to save that alarm as an intent in the other class, and I don't have any idea how to save different alarms in the other activity. I have also checked for the desk-clock alarm code but I didn't get that too.
Please help me someone, I am stuck here for the code for more than a week. Please someone help me, I shall be thankful to you.
If you want to send an Intent from one Activity to another, and then retrieve information from inside the Intent, the best way is use the Bundle object inside the intent:
Let's supose you send the intent from Activity1 to Activity2...
In Activity 1:
Intent intent = new Intent(Activity1.class,Activity2.class);
//I use the String class name as a key value, but you can use whatever key
intent.putExtra(String.class.getCanonicalName(), myString);
startActivity(intent);
//Or this other method if you want to retrieve a result from Activity2
//startActivityForResult(intent,Activity2);
In Activity 2:
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
String myString = bundle.getString(String.class.getCanonicalName());

Categories