Sending arraylist of objects using serializable - android

I am storing my JSON data into a arraylist of objects, my object class is Venue and I am passing that data into another activity using serializable from fragment but I am not receiving any values in the actvity. It is receiving the extra. bundle is not null.
My code is:
Fragment:
Intent intent = new Intent(getActivity(), SearchVenueActivity.class);
//pass values
Bundle bundle = new Bundle();
bundle.putSerializable("arrayListVenue",arrayListVenue);
intent.putExtras(bundle);
startActivity(intent);
Activity:
if (getIntent().hasExtra("arrayListVenue")) {
Bundle bundle = getIntent().getExtras();
if(bundle!=null)
rowItems = (ArrayList<Venue>) bundle.getSerializable("arrayListVenue");
else
Log.e("null","null");
}
Venue Class:
public class Venue implements Serializable{
String venue_id;
String venue_name;
String venue_address;
String venue_city;
public String getVenue_city() {
return venue_city;
}
public void setVenue_city(String venue_city) {
this.venue_city = venue_city;
}
public Venue(String venue_id, String venue_name, String venue_address, String venue_city, String venue_zip, String venue_phone, String venue_mobile) {
this.venue_id = venue_id;
this.venue_name = venue_name;
this.venue_address = venue_address;
this.venue_city = venue_city;
this.venue_zip = venue_zip;
this.venue_phone = venue_phone;
this.venue_mobile = venue_mobile;
}
public String getVenue_id() {
return venue_id;
}
public void setVenue_id(String venue_id) {
this.venue_id = venue_id;
}
public String getVenue_name() {
return venue_name;
}
public void setVenue_name(String venue_name) {
this.venue_name = venue_name;
}
}

try this way may this help you
First you want to make
Class Venue implements Serializable
public class Venue implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
}
In your FirstActivity do this way
ArrayList<Venue> VenueArrayList = new ArrayList<Venue>();
Intent intent = new Intent(this,secondActivity.class);
intent.putExtra("VenueArrayList", VenueArrayList);
In your SecondActivity do this way
ArrayList<Venue> VenueArrayList;
VenueArrayList = (ArrayList<Venue>) getIntent().getSerializableExtra(
"VenueArrayList");

Learn from my mistakes.
I've tried to send Arrays and big objects using Serializablethen my app got really slow. Did some tests and found out that when it took a lot of cpu and time to parse it. Therefore (altough its not what you would call best practice) i've created a CacheManager that store object for short time periods and used it to pass larger object between fragments activities.
If you want to make a more readical change to your design (later on in my project i did exactly that) then seperate the data from your fragment/activity completely and load it by LoaderManagers and pass only specific id's or stuff like that (stored stuff in the db in my case so it was easier).

Use intent.putParcelableArrayListExtra("arrayListVenue",arrayListVenue); for putting arraylist to intent and use intent.getParcelableArrayExtra("arrayListVenue") for get arraylist back from intent in your SearchVenueActivity activity
Edit
Tutorial for using parcelable

Use Array List instead of Bundle Elements.
In your Main Activity, try this:
Intent intent = new Intent(this, newactivity.class);
intent.putParceableListArrayExtra("your_array_list_name", arrayList);
In the next activity where you want to retreive it, just use:
getIntent().getExtra("your_array_list_name", new ArrayList<> arrayList2);

Related

Not ablet to pass Parcelable object as putExtra from IntentService to another Activity

Reivewed all the similar question, and yet no result.
I cannot pass one ojbect that implements parcelable from an intentService to an Activity. The Same code works fine when passing data from an activity to another activity. Even can pass ParcelableArrayListExtra also but not the parcelable Object. Its a requirment to pass the object in my project.
Code is given below(Dont have right to publish whole code,and whole code is working except these lines)
CODE:
IntentService:
Intent action = new Intent(this, QuizActivity.class);
intent.putParcelableArrayListExtra("userList",name);
Random position = new Random();
int randomPosition =position.nextInt(3);
intent.putExtra("selectedUser",name.get(randomPosition));
action.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SecondActivity:
List<User> userList= getIntent().getParcelableArrayListExtra(EXTRA_INSECTS);
Insect selected = getIntent().getExtras().getParcelable("selectedUser");
I suposse that problem can be with putting a custom Parcelable on API 25+ from service to activity.
This answer has a workaround, in the form of converting the Parcelable yourself to/from a byte[].
Begin with passing single Parcelable object, not ArrayList.
public static void putExtra(Intent intent, String key, Parcelable parcelable) {
byte[] bytes = marshall(parcelable);
intent.putExtra(key, bytes);
}
and
public static <T> T getExtra(Intent intent, String key, Parcelable.Creator<T> creator) {
byte[] bytes = intent.getByteArrayExtra(key);
return ParcelableUtils.unmarshall(bytes, creator);
}
Try below and when you get getParcelableArrayListExtra use same name.you have to implement User class with Parcelable.
Intent action = new Intent(this, QuizActivity.class);
intent.putParcelableArrayListExtra("userList",name);
Random position = new Random();
int randomPosition =position.nextInt(3);
intent.putExtra("selectedUser",name.get(randomPosition));
action.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
In SecondActivity :
ArrayList<User> userList = getIntent().getParcelableArrayListExtra("userList");
for(User user : post){
Log.d("user", user.getString());
}

send data from one activity to another from SQLite database

I want to retrieve all the records from table and show it in another activity,but when I do I am getting one record at a time and in reverse order.
I want all the records in single activity
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ViewAllActivity.class);//
while (c.moveToNext()) {
i.putExtra("rollno", c.getString(0));
i.putExtra("name", c.getString(1));
i.putExtra("marks", c.getString(2));
startActivity(i);
}
}
});
ViewAllActivity
String rollno=getIntent().getStringExtra("rollno");
String name=getIntent().getStringExtra("name");
String marks=getIntent().getStringExtra("marks");
TextView text;
text=(TextView) findViewById(R.id.text);
String str="Roll no:"+rollno+"\nName:"+name+"\nmarks:"+marks;
text.setText(str);
You have to create a model for doing the same..
example :
ArrayList<myModel> modelList = new ArrayList<>();
while(c.moveToNext()){
MyModel myModel = new MyModel();
myModel.setRollNumber(c.getString(0));
myModel.setName(c.getString(1));
myModel.setMark(c.getString(2));
modelList.add(myModel);
}
}
});
intent.putParcelableArrayListExtra(TAG, modelList);
startActivity(intent);
MyModel
public class MyModel implements Parcelable{
private String rollNumber;
private String name;
private String mark;
public void setRollNumner(String rollNumber){
this.rollNumber = rillNumber;
}
.....
}
the model should implement Parcelable or Serializable
I'l prefer just start your activity in the button click, and retrieve the data in the second activity.
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ViewAllActivity.class);
startActivity(i);
}
});
ViewAllActivity
//retrieve data to your cursor
String str = "";
while(c.moveToNext()){
str = str + "Roll no:" + rollno + "\nName:" + name + "\nmarks:" + marks;
text.setText(str);
}
If i were you i just start new intent activity and in some method in the second activity, oncreate or onstart retrieve your data from db.
But if you want to send your data in a bundle to the another one, you have to consider something
1.- you have to create a lis of your objets to send.
2.- to send arraylist or objects with a bundle you have to implement and extend Parcelable interface, otherwise will fail.
3.- if you use to send data vía bundle, is not good idea, could weak your performance, just think if your list are many objects, and you want to send vis bundle, app will bd slow. So think about.
Regards.

Global variables not passing properly

I have created a class that holds common variables and functions and is inherited by the activity classes that interface with the different UI pages in my app. I have been passing information between classes and activities using getVariable() and setVariable(input) functions. Suddenly, I can no longer pass information this way (it had been working well until recent edits, and now I can't figure out which change screwed this up). I have used Log outputs to determine that the data is storing properly - with the setVariable(input) functions - but when called later with the getVariable() functions it returns null. Any thoughts?
*Note, I recently started incorporating fragments into my project, extending FragmentActivity instead of Activity on my main class. I don't think this is causing the problem, but could it? If it does, whats the best practice to pass global variable info, and use fragments?
Code samples:
Main Inherited class:
public class MenuBarActivity extends FragmentActivity {
private String keyA;
private String keyB;
private int token;
private String Salt;
private long expires;
public String getKeyB() {
return keyB;
}
public String getKeyA() {
return keyA;
}
public int getTokenID() {
return token;
}
public void setToken(int tkn) {
token = tkn;
}
public void setKeyB(String kyB) {
keyB = kyB;
}
public void setKeyA(String kyA) {
keyA = kyA;
}
//Other common functions
}
LogIn Activity Class (gets log in info from web, stores into global variables):
public class WebContentGet extends MenuBarActivity{
public int tryLogOn(String uEmail, String pw) {
//call to get new keys on start up
JSONObject jObSend = new JSONObject();
try {
jObSend.put("email", uEmail);
jObSend.put("password", pw);
t.start();
t.join();
if(getStatus() == USER_STATUS_SUCCESSFULLOGIN){
String data = getData();
JSONObject jObReturn = new JSONObject(data);
String kyA = jObReturn.getString("keyA");
String kyB = jObReturn.getString("keyB");
int tkn = Integer.parseInt(jObReturn.getString("tokenID"));
String salt = jObReturn.getString("salt");
long exp = Long.parseLong(jObReturn.getString("expiration"));
int uID = Integer.parseInt(jObReturn.getString("userID"));
// Log outputs confirm data being read properly, and reported to setX() functions
setToken(tkn);
setKeyA(kyA);
setKeyB(kyB);
setSalt(salt);
setExpires(exp);
Log.d("WebContentGet tryLogIn","login values stored");
}
return getStatus();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return getStatus();
}
}
Activity Class, checks if keyA/B/etc stored:
public class UserLogIn2 extends MenuBarActivity implements EmailListener {
String emailIn;
String pwIn;
Context context = this;
#Override
public void onEmailLogInClick(String email, String pw) {
Log.d("UserLogin2", "onEmailLogInClick");
emailIn = email;
pwIn = pw;
emailIn = emailIn.trim();
emailIn = emailIn.toUpperCase();
Log.d("prepped email", emailIn);
pwIn = pwIn.trim();
WebContentGet webOb = new WebContentGet();
int webLog = webOb.tryLogOn(emailIn, pwIn);
if (webLog == USER_STATUS_SUCCESSFULLOGIN) {
int tkn = getTokenID();
long exp = getExpires();
String kya = getKeyA();
String kyb = getKeyB();
String slt = getSalt();
Log.d("UserLogIn2 - token", String.valueOf(tkn));
//Log statements confirm that getX() functions returning null
session.storeLoginSession(emailIn, pwIn, thisUser, tkn, exp, kya, kyb, slt);
Intent intent1 = new Intent(context, MainActivitiy.class);
startActivity(intent1);
} else {
showDialog(this, "Log in failure", "Incorrect Password");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userlogin2);
}
}
This cannot work, because you have two differend instances of your MenuBarActivity. Also that is not the way to pass data from one activity to another in android.
If you want to use data from one activity in another activity, you have to add them to an intent in the activity which provides the data, and extract them in the other. For more information see here: How do I pass data between Activities in Android application?
If you don't want to start the activity and send the data with the intent, you have to store the data somewhere e.g. SharedPreferences and fetch them again: How to use SharedPreferences in Android to store, fetch and edit values

passing a list of data from one intent to another using serializable

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")

What does bundle mean in Android? [duplicate]

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.

Categories

Resources