I'm trying to pass multiple data items in one Intent:
if (strActStat == "Sedentary") {
// passactStat.putString("keySedentary", strActStat);
// passSeden.putString("keyMale", gender);
i = new Intent(CalorieTrackerTargetWeight.this, TargetWeightResults.class);
i.putExtra("keyGender", gender);
i.putExtra("keyAct", strActStat);
//i.putExtra("keyAct", strActStat);
startActivity(i);
}
Why doesn't this work? Why can't I pass multiple items in one Intent?
You can't compare strings with ==.
if (strActStat.equals("Sedentary")) { // should work
Edit:
#Hesam has written a pretty detailed answer but his solution is not really usable. Instead of using an ArrayList<String> you should stick with the putExtra(key, value). Why? Well there are some advantages over the ArrayList solution:
you are not limited to the type of the ArrayList
you are not forced to keep a static order in you list. As you can only work with index values to get a list you need to make sure that the put() was in the same order as get(). Think of the following case: You you often send 3 values, but in some cases you don't want to send the second value. When you use the ArrayList solution, you end up sending null as the second value to ensure that the third value will stay in his place. This is highly confusing coding! Instead you should just send two values and when the receiving activity tries to receive the second value, it can handle the returning null like it want... for example replace it with a default value.
Naming of the key will grant you the knowledge of always knowing what should be inside...
Your key should be declared in the receiving Activity as a constant. So you always know by looking at this constants what intent data the activity can handle. This is good programming!
Hope this helps in clarifying the intent usage a bit.
I think this is not the only problem, first, if (strActStat == "Sedentary") this is wrong. you can't compare to string in this way. Because in this way objects are comparing not the string. Correct way is if (strActStat.equalIgnoreCase("Sedentary")).
If you use Parcelable then you can pass multiple data in just 1 intent.
Also you can use ArrayList<String>.
Here is a skeleton of the code you need:
Declare List
private List<String> test;
Init List at appropriate place
test = new ArrayList<String>();
and add data as appropriate to test.
Pass to intent as follows:
Intent intent = getIntent();
intent.putStringArrayListExtra("test", (ArrayList<String>) test);
Retrieve data as follows:
ArrayList<String> test = data.getStringArrayListExtra("test");
Hope that helps.
Try this:
done.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
namevalue=name.getText().toString();
overvalue=over.getText().toString();
audiostatus=audio.getText().toString();
Intent intent=new Intent(Settings.this,home.class);
Bundle bundle = new Bundle();
bundle.putString( "namevalue",namevalue);
bundle.putString("overvalue",overvaluse);
bundle.putInt("value",variablename);
intent.putExtras(bundle);
startActivity(intent);
}
});
I faced the same problem.
My mistake was that one of the variable I was transferring was not initialized.
Like gender or strActStat in your case.
Related
I'm trying to transfer ArrayList between activities, but nothing I've tried works as well.
This was my best shot, but this didn't work either.
I'm calling the external action here:
getComics getComicInfo = new getComics(charName, pageNum);
getComicInfo.execute();
getIntentData()
and here i'm trying to put data, but the problem is due the fact that this is an external action, so I can't shift through activits.
if(counter == comicInfoObject.length()){
Log.v("check arr length =>" , Integer.toString(comicList.size()));
Intent i = new Intent();
i.putExtra("comicArrayList", (ArrayList<Comics>)comicList);
}
and here i'm tring to retrive the data, but it doesn't get inside the "if"
public void getIntentData(){
Intent i = getIntent();
if(i != null && i.hasExtra("comicArrayList")){
comicList2 = i.getParcelableExtra("comicArrayList");
int size = comicList2.size();
}
}
first code is where I call an external class that using api and in the bottom line creates the arrayList
second code is inside the external class, where I'm trying to pass the arrayList with putExtra
third code is where i'm tring to retrive the data after getIntentData().
Pack at the sender Activity
intent.putParcelableArrayListExtra(<KEY>, ArrayList<Comics extends Parcelable> list);
startActivity(intent);
Extract at the receiver Activity
getIntent().getParcelableArrayListExtra(<KEY>);
You need make a Comics class that implements Parcelable, then use put ParcelableArrayListExtrato pass arraylist.
Here is a sample link for Pass data between activities implements Parcelable
However be careful if your array list too big, you could get intent exception, for this case you could think about a static reference to store your array list.
I am trying to send an array of objects to a new intent, but the problem is that I don't know how to send the whole array at once. The method I managed to get it working is adding object by object, in a for loop, and in the second activity I have to get them one by one, something like this:
Main activity:
Intent newIntent = new Intent(mainA.this, secondA.class);
for(int i=0;i<numberOfObjects;i++)
newIntent.putExtra("object"+i,myObjects[i]);
newIntent.putExtra("length", x);
startActivity(newIntent);
Second activity:
Serializable n = getIntent().getSerializableExtra("length");
int x = Integer.parseInt(n.toString());
myObjects = new objClass[x];
for(int i=0;i<x;i++)
myObjects[i] = (objClass) getIntent().getSerializableExtra("object"+i);
Even if this method works, and gets me the right results, isn't there a better/faster/cleaner solution?(I searched a lot, but haven't found a better way, maybe I don't know what exactly to look for).
Make your object serializable and put all objects in a Arraylist and send it.ArrayList itself implements serializable.
Intent newIntent = new Intent(mainA.this, secondA.class);
newIntent.putExtra("list",listOfObjets);
startActivity(newIntent);
Second Activity:
ArrayList<YourObjects> list = (ArrayList<YourObjects>)getIntent().getSerializableExtra("list");
Hi you can try this as well.. Create setter getter class which will set and get your object. next create the array list of your setter getter class.next add all objects into arraylist using set method in for loop. next add that arraylist object into bundle using setArguments.
Same you can access that bundle using getArguments that's it.
I have a problem with with sharing data between two different activities. I have data like :
int number
String name
int number_2
int time
int total
I'm trying to make something like order list with this set of data . So it will take one set of data , then back to previous activity , move forward and again add data to it .
I have an idea of making it in array of object - but data inside was cleared after changing activity.
How can I make it ?
I don't know if and how to add Array of object to SharedPreferences , and get value of one element from there.
You should have a look at the documentation of the Intent(s) if you want to do that on the fly associating a key to the value(s) that you want to pass to your second activity.
Anyway, you can think any(sharedpref, database,...) way to pass your parameters but for those kind of things it's a convention and a good practice to follow that.
Don't used share preferences for this...Use the singleton pattern, extend Application, or just make a class with static variables and update them...
You can use .putExtra but since you are communicating with more than one activity the above suggestions are probably the best.
public class ShareData {
private String s;
private int s;
private static ShareData shareData = new ShareData();
private ShareData(){}
public static ShareData getInstance(){ return shareData}
//create getters and setters;
}
Why not to use Intents
Intent intent = new Intent(FirstActivity.this, (destination activity)SecondActivity.class);
intent.putExtra("some_key", value);
intent.putExtra("some_other_key", "a value");
startActivity(intent);
in the second activity
Bundle bundle = getIntent().getExtras();
int value = bundle.getInt("some_key");
String value2 = bundle.getString("some_other_key");
EDIT if you want to read more about adding array to shared preferences check this
Is it possible to add an array or object to SharedPreferences on Android
also this
http://www.sherif.mobi/2012/05/string-arrays-and-object-arrays-in.html
So I'm still working on my first little app here, new to Android and Java, so I'm stuck on a basic little problem here. Answers to my first questions were really helpful, so after researching and not coming up with anything, I thought I'd ask for some more help!
The idea is that on another screen the user makes a choice A, B, C, or D, and that choices is passed as a string through the intent. OnResume checks if the choice is not null and sets an integer that corresponds to that string. Later when the user pushes another button, some if else logic checks that int and performs and action based on which was chosen. The problem is that the App crashed at onResume.
I learned that I have to use equals(string) to compare string reference, but maybe the problem is that I am trying to compare a string in reference to a literal string? Any help would be greatly appreciated.
Thanks!
protected void onResume() {
super.onResume();
// Get the message from the intent
Intent intent = getIntent();
String choice = intent
.getStringExtra(ExtensionSetupSlector.TORQUE_SETUP);
// Create the text view
TextView displayChoice = (TextView) findViewById(R.id.displayChoice);
if (!choice.equals("")){
displayChoice.setText(choice);
if (choice.equals("A")) {
myChoice = 1;
}
if (choice.equals("B")) {
myChoice = 2;
}
if (choice.equals("C")) {
myChoice = 3;
}
if (choice.equals("D")) {
myChoice = 4;
}
}
}
myChoice is declare right after ...extends Activity{ Also I'm not quite sure If this should really be in onResume, but it was working before I started try to set myChoice in the onResume (when I was just displaying the choice). Thanks again!
Change if (!choice.equals("")) to check for null instead. Otherwise your app attempts to access an empty reference and crashes.
I have an android context menu with various selections and depending on the user selection I want to start an intent. The intent starts the same activity for all the buttons but will contain different String variables depending on the selection. I am currently using a switch, case methodology for my click listener but keep running into 'duplicate local variable' problems as I try to eliminate code repetition! If anyone could provide a-bit of pseudo-code that would be even better!
It's hard to tell without seeing some code, but "duplicate local variables" together with "switch case" makes me think you're declaring a variable in one of the cases with the same name as a variable from another case.
Code within different cases of the same switch is all in the same scope, unless you surround the code within a case with brackets, like this:
switch(VALUE) {
case A: {
String string = "";
}
case B: {
//Same variable name, possible since it's in a different scope now.
String string = "";
}
}
So either use brackets, or simply make sure you're using different variable names across the cases.
you can use intent.putExtra(String name, String value) and push it to the other activity.
Pseudo code:
Button1.value = "X" ;
Button2.value = "Y" ;
onClickListner(View v) {
Intent intent = new Intent() ;
intent.putExtra("ButtonValue",
v.value() ) ;
// extra code goes here...
}
Hope this is what you were looking for..
VInay
I like to use set/getTag(Object), as you can put any type you like into it (as long as you're careful about getting it out again):
button1.setTag(MyClass.STATIC_INT_1);
button2.setTag(MyClass.STATIC_INT_2);
button1.setOnClickListener(Click);
button2.setOnClickListener(Click);
private OnClickListener Click(View v) {
Intent intent = new Intent() ;
intent.putExtra("Value", Integer.parseInt(v.getTag().toString()) ) ;
ยทยทยท
}