i would like to send the values from one activity to another but i got null in the second activity please solve my problem.the first activity contains blog_info the details of that
blog is send to second activity based on these values the second activity search places .
final ArrayList<Blog> blogList = (ArrayList<Blog>) message
.getResultList("Blog");
for (Blog blog : blogList) {
int i=0;
latitude_Array[i] = Double.parseDouble(blog.getLatitude_zzs());
longitude_Array[i]=Double.parseDouble(blog.getLongitude_zzs());
i++;
}
btn = (Button) findViewById(R.id.main_top_map_list);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
MainActivity_MapList.class);
//The method putDoubleArray(String, double[]) in the type Bundle is not applicable for the arguments (String, Double[])
bundle.putDoubleArray("latitude_Array", latitude_Array);
// intent.putExtras(bundle);
finish();
startActivity(intent);
}
});
i have used a series of method such as :
bundle.putDoubleArray(key, value)
bundle.putSparseParcelableArray(key, value)
bundle.putParcelableArray(key, value)
bundle.putSerializable(key, value)
but i just get 'null' or '0.0' in the second activity.
first, in the code you posted, you are putting an arraylist of lists of doubles, but then casting it to an arraylist of ? extends parcelable. those aren't the same type.
i assume you just want to pass a list (or array) of doubles. you can either use putDoubleArray() or putSerializable(). if you want to deal with an array of doubles, you need to have your doubles in a double[], like,
double[] doubles = ...; // whatever
bundle.putDoubleArray(key, doubles);
to get them out on the other side,
double[] doubles = bundle.getDoubleArray(key);
if you want to pass your doubles in an array list, you must have your doubles in an ArrayList<? implements Serializable> ... e.g., ArrayList<Double>. like this,
ArrayList<Double> doubles = ...; // whatever
bundle.putSerializable(key, doubles);
to get them out of the bundle on the other side,
ArrayList<Double> doubles = (ArrayList<Double>)bundle.getSerializableExtra(key);
Related
I would like to parse a list of data from one intent to another intent
However, with my code,
I'm only manage to pass the first item in the listview .
I use a log.d to check for the items, and realised that only one items is being pass.
In my listview there's 2 items,when I pass it over to my next intent, only one item was shown in the log..
I did a serializable in my class.
I make a log in my summary,
however,
when I click on summary, the log that was shown in not all the data.
logcat:
01-28 18:20:49.218: D/Bundle(20278): bundle : Bundle[{clickedpreOdometer=, clickedID=2, clickedCost= 12.0, clickedDate=27/12/2014, pojoArrayList=[com.example.fuellogproject.fuelLogPojo#43bf3f18, com.example.fuellogproject.fuelLogPojo#43bf5b68], clickedPump=3, clickedPrice=4, clickedFCon= 0.0, clickedOdometer=3}]
listview
public void summaryClick (View v)
{
Intent sum = new Intent(this, summary.class);
fuelLogPojo clickedObject = pojoArrayList.get(0);
Bundle dataBundle = new Bundle();
dataBundle.putString("clickedID", clickedObject.getid());
dataBundle.putString("clickedDate", clickedObject.getdate());
dataBundle.putString("clickedPrice", clickedObject.getprice());
dataBundle.putString("clickedPump", clickedObject.getpump());
dataBundle.putString("clickedCost", clickedObject.getcost());
dataBundle.putString("clickedOdometer", clickedObject.getodometer());
dataBundle.putString("clickedpreOdometer",
clickedObject.getpreodometer());
dataBundle.putString("clickedFCon", clickedObject.getfcon());
dataBundle.putSerializable("pojoArrayList", pojoArrayList);
Log.i("FuelLog", "dataBundle " + dataBundle);
// Attach the bundled data to the intent
// sum.putExtras(dataBundle);
sum.putExtras(dataBundle);
Log.i("Exrrass", "dataBundle " + dataBundle);
// Start the Activity
startActivity(sum);
}
summary.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.summary);
//month = (TextView)findViewById(R.id.month);
avgPrice = (TextView)findViewById(R.id.showavfPriceTV);
exFuel = (TextView)findViewById(R.id.showexFuelTV);
avgFC = (TextView)findViewById(R.id.showavgFCTV);
doneButton = (Button)findViewById(R.id.doneBTN);
exitButton = (Button)findViewById(R.id.exitBTN);
Bundle takeBundledData = getIntent().getExtras();
// First we need to get the bundle data that pass from the UndergraduateListActivity
bundleID = takeBundledData.getString("clickedID");
/*bundleDate = takeBundledData.getString("clickedDate");
bundlePrice = takeBundledData.getString("clickedPrice");
bundlePump = takeBundledData.getString("clickedPump");
bundleCost = takeBundledData.getString("clickedCost");
bundleOdometer = takeBundledData.getString("clickedOdometer");
bundlePreOdometer = takeBundledData.getString("clickedpreOdometer");
bundleFcon = takeBundledData.getString("clickedFCon");*/
Log.d("Bundle","bundle : "+ takeBundledData);
}
fuelLogpojo.java
public class fuelLogPojo implements Serializable{
fuelLogPojo should implement either Parcelable or Serializable
Bundles can accept custom classes, if they implement either Parcelable or Serializable, Parcelable is faster but more work to implement and Serializable is easier to implement, but slower.
I'm going to imagine that fuelLogPojo extends Serializable in this example, just because its easier to setup but you should really consider Parcelable
Then you can do this:
dataBundle.putSerializable("pojoArrayList", pojoArrayList);
sum.setArguments(bundle);
Also, you should reconsider the naming convention for your classes.
EDIT:
Here's how to access that pojoArrayList in summary.
List<fuelLogPojo> pojoArrayList = (List<fuelLogPojo>)extras.getSerializable("pojoArrayList");
If you want to pass array of Custom Objects You have to implements Parcerable interface
Take a look here
And then pass array like
Intent i=...
i.putParcelableArrayListExtra("ARRAY", array);
and read it
getIntent().getParcelableArrayListExtra("ARRAY")
This question already has answers here:
What is a "bundle" in an Android application
(12 answers)
Closed 7 years ago.
I am new to android application development, and can't understand what does bundle actually do for us.
Can anyone explain it for me?
I am new to android application development and can't understand what
does bundle actually do for us. Can anyone explain it for me?
In my own words you can image it like a MAP that stores primitive datatypes and objects as couple key-value
Bundle is most often used for passing data through various Activities. Provides putType() and getType() methods for storing and retrieving data from it.
Also Bundle as parameter of onCreate() Activity's life-cycle method can be used when you want to save data when device orientation is changed (in this case activity is destroyed and created again with non null parameter as Bundle).
More about Bundle at its methods you can read reference at developer.android.com where you should start and then make some demo applications to get experience.
Demonstration examples of usage:
Passing primitive datatypes through Activities:
Intent i = new Intent(ActivityContext, TargetActivity.class);
Bundle dataMap = new Bundle();
dataMap.putString("key", "value");
dataMap.putInt("key", 1);
i.putExtras(dataMap);
startActivity(i);
Passing List of values through Activities:
Bundle dataMap = new Bundle();
ArrayList<String> s = new ArrayList<String>();
s.add("Hello");
dataMap.putStringArrayList("key", s); // also Integer and CharSequence
i.putExtras(dataMap);
startActivity(i);
Passing Serialized objects through Activities:
public class Foo implements Serializable {
private static final long serialVersionUID = 1L;
private ArrayList<FooObject> foos;
public Foo(ArrayList<FooObject> foos) {
this.foos = foos;
}
public ArrayList<FooObject> getFoos() {
return this.foos;
}
}
public class FooObject implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
public FooObject(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Then:
Bundle dataMap = new Bundle();
ArrayList<FooObject> foos = new ArrayList<FooObject>();
foos.add(new FooObject(1));
dataMap.putSerializable("key", new Foo(foos));
Pass Parcelable objects through Activities:
There is much more code so here is article how to do it:
Parcel data to pass between Activities using Parcelable classes
How to retrieve data in target Activity:
There is one magic method: getIntent() that returns Intent (if there are any data also with extended data) that started Activity from there method is called.
So:
Bundle dataFromIntent = getIntent().getExtras();
if (dataFromIntent != null) {
String stringValue = dataFromIntent.getString("key");
int intValue = dataFromIntent.getInt("key");
Foo fooObject = (Foo) dataFromIntent.getSerializable("key");
// getSerializble returns Serializable so we need to cast to appropriate object.
ArrayList<String> stringArray = dataFromIntent.getStringArrayList("key");
}
Usage of Bundle as parameter of onCreate() method:
You are storing data in onSaveInstanceState() method as below:
#Override
public void onSaveInstanceState(Bundle map) {
map.putString("key", "value");
map.putInt("key", 1);
}
And restore them in onCreate() method (in this case is Bundle as parameter not null) as below:
#Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
String stringValue = savedInstanceState.getString("key");
int intValue = savedInstanceState.getString("key");
}
...
}
Note: You can restore data also in onRestoreInstanceState() method but it's not common (its called after onStart() method and onCreate() is called before).
In general english: "It is a collection of things, or a quantity of material, tied or wrapped up together."
same way in Android "It is a collection of keys and its values, which are used to store some sort of data in it."
Bundle is generally used for passing data between various component. Bundle class which can be retrieved from the intent via the getExtras() method.
You can also add data directly to the Bundle via the overloaded putExtra() methods of the Intent objects. Extras are key/value pairs, the key is always of type String. As value you can use the primitive data types.
The receiving component can access this information via the getAction() and getData() methods on the Intent object. This Intent object can be retrieved via the getIntent() method. And
the component which receives the intent can use the getIntent().getExtras() method call to get the extra data.
MainActivity
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putString(“Key“, myValue);
intent.putExtras(bundle);
startActivity(intent);
SecondActivity
Bundle bundle = getIntent().getExtras();
String myValue= bundle.getString(“key“);
A collection of things, or a quantity of material, tied or wrapped up together. it is the dictionary meaning...By the same Bundle is a collection of data. The data may be of any type i.e String, int,float , boolean and any serializable data. We can share& save the data of one Activity to another using the bundle Bundle.
Consider it as a Bundle of data, used while passing data from one Activity to another.
The documentation defines it as
"A mapping from String values to various Parcelable types."
You can put data inside the Bundle and then pass this Bundle across several activities. This is handy because you don't need to pass individual data. You put all the data in the Bundle and then just pass the Bundle, instead of sending the data individually.
It's literally a bundle of things; information: You put stuff in there (Strings, Integers, etc), and you pass them as a single parameter (the bundle) when use an intent for instance.
Then your target (activity) can get them out again and read the ID, mode, setting etc.
A mapping from String values to various Parcelable types.Click here
Example:
Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);
Send value from one activity to another activity.
I'd like to pass a custom Object from one activity to another, the Object consists of a String and a List of another custom Object which consists of an array of strings and an array of ints. I've read https://stackoverflow.com/a/2141166/830104, but then I've found this answer https://stackoverflow.com/a/7842273/830104. Which is better to use Bundle or Parcelable? What is the difference? When should I use this each? Thanks for your replies, Dan
Parcelable and Bundle are not exclusive concepts; you can even deploy both on your app at a time.
[1] Term Parcelable comes with Serialization concept in Java (and other high-level language such as C#, Python,...). It ensures that an object - which remains in RAM store - of such Parcelable class can be saved in file stream such as text or memory (offline status) then can be reconstructed to be used in program at runtime (online status).
In an Android application, within 2 independent activities (exclusively running - one starts then other will have to stop):
There will be NO pointer from current activity to refer to previous one and its members - because previous activity is stopped and cleared out form memory; so that to maintain object's value passed to next activity (called from Intent) the object need to be parcelable (serializable).
[2] While Bundle is normally the Android concept, denotes that a variable or group of variables. If look into lower level, it can be considered as HashMap with key-value pairs.
Conclusion:
Bundle is to store many objects with related keys, it can save any object in native types, but it doesn't know how to save a complex object (which contains an ArrayList for example)
Parcelable class is to ensure a complex instance of it can be serialized and de-serialized during runtime. This object can contains complex types such as ArrayList, HashMap, array, or struct,...
[UPDATED] - Example:
//Class without implementing Parcelable will cause error
//if passing though activities via Intent
public class NoneParcelable
{
private ArrayList<String> nameList = new ArrayList<String>();
public NoneParcelable()
{
nameList.add("abc");
nameList.add("xyz");
}
}
//Parcelable Class's objects can be exchanged
public class GoodParcelable implements Parcelable
{
private ArrayList<String> nameList = new ArrayList<String>();
public GoodParcelable()
{
nameList.add("Can");
nameList.add("be parsed");
}
#Override
public int describeContents()
{
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags)
{
// Serialize ArrayList name here
}
}
In source activity:
NoneParcelable nonePcl = new NoneParcelable();
GoodParcelable goodPcl = new GoodParcelable();
int count = 100;
Intent i = new Intent(...);
i.putExtra("NONE_P",nonePcl);
i.putExtra("GOOD_P",goodPcl);
i.putExtra("COUNT", count);
In destination activity:
Intent i = getIntent();
//this is BAD:
NoneParcelable nP = (NoneParcelable)i.getExtra("NONE_P"); //BAD code
//these are OK:
int count = (int)i.getExtra("COUNT");//OK
GoodParcelable myParcelableObject=(GoodParcelable)i.getParcelableExtra("GOOD_P");// OK
How to resolve this fault . And how to get data of array from 'for(Blog blog:blogList)' .
Can you tell me ,which fault in my code ?
//The method putDoubleArray(String, double[]) in the type Bundle is not applicable for the arguments (String, Double[])
final ArrayList<Blog> blogList = (ArrayList<Blog>) message
.getResultList("Blog");
for (Blog blog : blogList) {
int i=0;
latitude_Array[i] = Double.parseDouble(blog.getLatitude_zzs());
longitude_Array[i]=Double.parseDouble(blog.getLongitude_zzs());
i++;
}
btn = (Button) findViewById(R.id.main_top_map_list);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
MainActivity_MapList.class);
//The method putDoubleArray(String, double[]) in the type Bundle is not applicable for the arguments (String, Double[])
bundle.putDoubleArray("latitude_Array", latitude_Array);
// intent.putExtras(bundle);
finish();
startActivity(intent);
}
});
It's just what the error message says. Evidently, your latitude_Array variable is declared to be Double []. One fix is to declare your latitude_Array (and probably also longitude_Array to be of type double [] instead of Double []. (Case, as always, is significant. A Double is an object that holds a primitive double value. It's main use is for collections, that cannot hold primitives.)
If you absolutely need them to be of type Double [], then you'll have to copy the values over to a primitive array before stuffing it into a Bundle.
i'm continuously running into problems trying to pass an ArrayList from one Activity to another. My code is failing with a Null Pointer Exception when i try to iterate through the ArrayList in my XMLParser Class. I've put print statements into the Activity that generates the ArrayList and it looks fine. Can anyone see what i'm doing wrong or why i get a Null pointer Exception when retrieving the ArrayList?
public void onClick(View v) {
if (selItemArray[0] == null) {
Toast.makeText(getApplicationContext()," Please make a Selection ", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(Recipes2.this, XMLParser.class);
Log.v("Recipes2", "selItemArray[0] before call to XML Parser : " + selItemArray[0]);
//Log.v("Recipes2", "selItemArray[1] before call to XML Parser : " + selItemArray[1]);
intent.putExtra("items_to_parse", selItemArray);
startActivityForResult(intent, 0);
}
}
public class XMLParser extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Bundle b = getIntent().getExtras();
//itemsToParse = b.getStringArrayList("items_to_parse");
ArrayList<String> itemsToParse = new ArrayList<String>();
itemsToParse = getIntent().getExtras().getStringArrayList("items_to_parse"); Iterator<String> iterator = itemsToParse.iterator(); while(iterator.hasNext())
Log.v("XMLParser", iterator.next().toString());
It looks like you're putting a String array, not a ArrayList<String>.
You used a string array on the "sender" side and are trying to get it back as an ArrayList on the receiver side. That won't work. Use a String array on both sides and -- if necessary -- pull it into an array list.
The procedure for passing the data is here:
Passing String array between two class in android application
To convert it to a List - simply do:
List<String> = Arrays.asList(stringArray);