could someone please answer my question. in my activity class.java, I have an intent and i want to send an object using intent. when I searched for it, the results were I have to implement parcelable to the class "object" that I want to send it. I did that but the thing is I want to put two objects to be sent to main2activity.java, when I tried to do that, my app crashed, when I debugged it said that main2activity has much intent? so my question is how can I send two objects using put extra, and get them in the other java using getintent.getparcelableextra()?
mainactivity.java
clickedplace is an object of class called Place
Intent myintent = new Intent(getApplicationContext(), localpopup.class);
myintent.putExtra("localprice",clickedplace.getTicketId().getLocalPrice());
myintent.putExtra("placeobject", clickedplace.getId());
main2activity.java
localpriceplace of type double
getpressplace of type Place
localpriceplace= getIntent().getParcelableExtra("localprice");
getpressedplace= (Place) getIntent().getParcelableExtra("placeobject");
You should be able to do this by creating a Bundle and putting each Intent into it with a String key. In "main2activity" you should retrieve them by name.
But the bundle into a new Intent and send that to main2activity
Otherwise, if you are putting data into each Intent and then sending the Intent directly to main2activity, you will need to implement "onNewIntent" in main2activity to get the new data.
Hi Please follow below link which is useful to you and solved your problem.
http://www.vogella.com/tutorials/AndroidParcelable/article.html
Hope above link helps you.
If you want to auto generate those parcelable model class then follow below link which saves your time.
https://github.com/mcharmas/android-parcelable-intellij-plugin
Please check below code:
1) You need to create your model class as a parcelable follow by above link.
2) To pass data to other activity:
intent.putExtra("student", new Student("1","Mike","6") // which is your model class object passing);
3)GetData into Other Activity Using intent:
Bundle data = getIntent().getExtras();
Student student = (Student) data.getParcelable("student");
// after you get all data from student.
Hope you understand.
Try this implements Parcelable to your Place Model
Intent myintent = new Intent(getApplicationContext(), localpopup.class);
myintent.putExtra("placeModel",clickedplac);
Receive
placeModel= getIntent().getParcelableExtra("placeModel");
String price=placeModel.getTicketId().getLocalPrice();
String Id=placeModel.getId()
ActivityB.java
public class ActivityB {
private static final String ARG_DATA1 = "Data1";
private static final String ARG_DATA2 = "Data2";
public static startActivityB (Context context, Data1 data1, Data2 data2) {
Bundle bundle = new Bundle();
bundle.putParcelable(ARG_DATA1, data1);
bundle.putParcelable(ARG_DATA2, data2);
Intent intent = new Intent(context, ActivityB.class);
intent.putExtras(bundle);
context.startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
Data1 data1 = bundle.getParcelable(ARG_DATA1);
Data2 data2 = bundle.getParcelable(ARG_DATA2);
}
}
Data1.java
public static class Data1 implements Parcelable {
public static final Creator<Data1> CREATOR = new Creator<Data1>() {
#Override
public Data1 createFromParcel(Parcel in) {
return new Data1(in);
}
#Override
public Data1[] newArray(int size) {
return new Data1[size];
}
};
protected Data1(Parcel in) {
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
}
}
and Data2.java should also implement Parcelable.
And lastly, to start ActivityB from ActivityA,
Data1 data1;
Data2 data2;
ActivityB.startActivityB(ActivityA.this, data1, data2);
Related
I am trying to pass the top50TrendsList to another activity via Intent as shown below in the code, but it is marked with red and I am getting an error message which says:
2nd parameter cant be cast to Serializable
despite the class Trend implements Serializable interface.
Please let me know how to pass top50TrendsList via Intent to another activity? Thanks.
code:
List<Trend> top50TrendsList = this.mTrendsList.subList(0, 2);
Collections.sort(this.mTrendsList);
Intent intentSendBroadcast = new Intent();
intentSendBroadcast.setAction(ActMain.CONST_BROADCAST_ACTION_ON_LIST_READY);
Bundle b = new Bundle();
b.putSerializable(TwitterTrendsAPIService.CONST_BUNDLE_KEY_SERIALIZED_LIST, top50TrendsList);
intentSendBroadcast.putExtras(b);
sendBroadcast(intentSendBroadcast);
Well your Trend should be Parcelable, and then you can do it like
intent.putParcelableArrayListExtra("myArrayList" , top50TrendsList);
Have a look at this to know about parceable, and how to make your class parceable.
Hope this helps.
ArrayList implements Serializable, not List. You are providing an object via List (interface) reference (and Java has single dispatch, so the overloaded method variant to invoke is being identified in compile time by reference type, not actual object type in runtime). Pass it via ArrayList reference and it will be ok for your goals I suppose.
Use Parcelable
public class Test implements Parcelable
{
List<String> list;
protected Test(Parcel in) {
list = in.createStringArrayList();
}
public Test()
{}
public static final Creator<Test> CREATOR = new Creator<Test>() {
#Override
public Test createFromParcel(Parcel in) {
return new Test(in);
}
#Override
public Test[] newArray(int size) {
return new Test[size];
}
};
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringList(list);
}
}
setList on Model class and pass to another actiivty:
List<String> list = new ArrayList<>();
Test test = new Test();
test.setList(list);
Intent intent = new Intent(this, Main2Activity.class);
intent.putExtra("list", test);
startActivity(intent);
For getting data from 2nd activity:
if (getIntent().hasExtra("list"))
{
List<String> list = new ArrayList<>();
Test test = getIntent().getParcelableExtra("list");
list.addAll(test.getList());
}
Your Trend class should implements Serializable like this
public class Trend implements
Serializable
I want a list object that not allow duplicate value, which Set<String> is what I need.
However it can't pass to other activity via bundle or extra because it's not serializable?
how can I achieve this ?
Set<String> foo = new HashSet<String>();
Intent i = new Intent();
i.putExtra("key", foo);
startActivity(..., i);
Edit
Instead of..
Set<String> foo = new HashSet<String>();
Change to this..
HashSet<String> foo = new HashSet<String>();
Problem Solved Thank to all .
What are you talking about...
public class
HashSet
extends AbstractSet<E>
implements Set<E> Cloneable Serializable
Hash set is serializable... You need not pass in a Set, just use a HashSet OR if you want to STILL use a Set, as the datatype, then cast it to HashSet when its passed in the intent.
Ref
http://developer.android.com/reference/java/util/HashSet.html
You can do something like this:-
In the activity from which you want to send data
ArrayList userlist= new ArrayList();
Intent intent = new Intent(context, Dashboard.class);
intent.putExtra("userlist", userlist);
The activity in which you want to get the data
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
userlist = (ArrayList<User>) getIntent().getSerializableExtra("userlist");
}
The User Bean
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3200348961839049924L;
/**
*
*/
private String name;
private String phoneNo;
private String emailId;
}
I have searched a few topics but not found a solution to my problem.
public class Series implements Parcelable {
private String name;
private int numOfSeason;
private int numOfEpisode;
/** Constructors and Getters/Setters have been removed to make reading easier **/
public Series(Parcel in) {
String[] data = new String[3];
in.readStringArray(data);
this.name = data[0];
this.numOfSeason = Integer.parseInt(data[1]);
this.numOfEpisode = Integer.parseInt(data[2]);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] { this.name,
String.valueOf(this.numOfSeason),
String.valueOf(this.numOfEpisode) });
}
private void readFromParcel(Parcel in) {
name = in.readString();
numOfSeason = in.readInt();
numOfEpisode = in.readInt();
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
#Override
public Series createFromParcel(Parcel in) {
return new Series(in);
}
#Override
public Series[] newArray(int size) {
return new Series[size];
}
};
}
In my MainActivity I have an ArrayList. To make the list dynamically editeable I need to pass it to another activity where I can edit it.
ArrayList<Series> listOfSeries = new ArrayList<Series>();
public void openAddActivity() {
Intent intent = new Intent(this, AddActivity.class);
intent.putParcelableArrayListExtra(
"com.example.episodetracker.listofseries",
(ArrayList<? extends Parcelable>) listOfSeries);
startActivity(intent);
}
I need to cast the list, otherwise Eclipse gives me the following Error message.
The method putParcelableArrayListExtra(String, ArrayList) in the type Intent is not applicable for the arguments (String, List)
Is this the correct way to do it?
ArrayList<Series> list = savedInstanceState
.getParcelableArrayList("com.example.episodetracker.listofseries");
This is the way I try to read the data in another activity.
It's crashing on the line above. namely the getParcelableArrayList part.
The problem is in writing out to the parcel and reading in from the parcel ...
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(numOfSeason);
dest.writeInt(numOfEpisode);
}
private void readFromParcel(Parcel in) {
name = in.readString();
numOfSeason = in.readInt();
numOfEpisode = in.readInt();
}
What you write out has to match what you read in...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this,SecondActivity.class);
ArrayList<testparcel> testing = new ArrayList<testparcel>();
i.putParcelableArrayListExtra("extraextra", testing);
startActivity(i);
}
/**********************************************/
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<testparcel> testing = this.getIntent().getParcelableArrayListExtra("extraextra");
}
}
The above code is having onCreate() from two different activities. The first one launches the second one; and it works fine I was able to pull the parcelable without issue.
You should use the putParcelableArrayListExtra() method on the Intent class.
I've used putParcelableArrayList(<? extends Parcelable>) from a Bundle Object. Not directly from an Intent Object.(I don't really know what's the difference). but i use to use in this way:
ArrayList<ParcelableRow> resultSet = new ArrayList<ParcelableRow>();
resultSet = loadData();
Bundle data = new Bundle();
data.putParcelableArrayList("search.resultSet", resultSet);
yourIntent.putExtra("result.content", data);
startActivity(yourIntent);
Later on your new activity you can populate the data recently inserted on the Bundle object like this:
Bundle data = this.getIntent().getBundleExtra("result.content");
ArrayList<ParcelableRow> result = data.getParcelableArrayList("search.resultset");
Just remember that your ArrayList<> must contain only parcelable objects. and just to make sure that your have passed the data you may check if the data received is null or not, just to avoid issues.
Maybe this helps someone.. else my problem was that I used write and readValue but it should match type like writeInt, readInt writeString, readString and so forth
I am doing it in this way:
var intent = Intent(this#McqActivity,ResultActivity::class.java)
intent.putParcelableArrayListExtra("keyResults", ArrayList(resultList))
// resultList is of type mutableListOf<ResultBO>()
startActivity(intent)
And for making the class Parcelable . I simply do two operation first I used #Parcelize Annotation above my data class and secondly I inherit it with Parcelable like below..
import kotlinx.android.parcel.Parcelize
import android.os.Parcelable
#Parcelize // Include Annotion
data class ResultBO(val questionBO: QuestionBO) : Parcelable {
constructor() : this(QuestionBO())
}
And at receiving end
if (intent != null) {
var results = intent.getParcelableArrayListExtra<Parcelable>("keyResults")
}
You can pass Parcelable ArrayList
Sender Activity ->
startActivity(Intent(this, SenderActivity::class.java).apply { putExtra("getList",list)})
Receiver Activity ->
private lateinit var list: ArrayList<List>
list = this.intent.extras?.getParcelableArrayList("getList")!!
And you will get all Arraylist in list.
How to pass Collections like ArrayList, etc from one Activity to another as we used to pass Strings, int with help of putExtra method of Intent?
Can anyone please help me as i want to pass a List<String> from one Activity to another?
You can pass an ArrayList<E> the same way, if the E type is Serializable.
You would call the putExtra (String name, Serializable value) of Intent to store, and getSerializableExtra (String name) for retrieval.
Example:
ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);
In the other Activity:
ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");
Please note that serialization can cause performance issues: it takes time, and a lot of objects will be allocated (and thus, have to be garbage collected).
First you need to create a Parcelable object class, see the example
public class Student implements Parcelable {
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int arg1) {
// TODO Auto-generated method stub
dest.writeInt(id);
dest.writeString(name);
}
public Student(Parcel in) {
id = in.readInt();
name = in.readString();
}
public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {
public Student createFromParcel(Parcel in) {
return new Student(in);
}
public Student[] newArray(int size) {
return new Student[size];
}
};
}
And the list
ArrayList<Student> arraylist = new ArrayList<Student>();
Code from Calling activity
Intent intent = new Intent(this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("mylist", arraylist);
intent.putExtras(bundle);
this.startActivity(intent);
Code on called activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle bundle = getIntent().getExtras();
ArrayList<Student> arraylist = bundle.getParcelableArrayList("mylist");
}
use putExtra to pass value to an intent. use getSerializableExtra method to retrieve the data
like this
Activity A :
ArrayList<String> list = new ArrayList<String>();
intent.putExtra("arraylist", list);
startActivity(intent);
Activity B:
ArrayList<String> list = getIntent().getSerializableExtra("arraylist");
I tried all the proposed techniques but none of them worked and stopped my app from working and then I finally succedded. Here is how I did it...
In main activity I did this:
List<String> myList...;
Intent intent = new Intent...;
Bundle b=new Bundle();
b.putStringArrayList("KEY",(ArrayList<String>)myList);
intent_deviceList.putExtras(b);
....startActivity(intent);
To get the data in the new Activity:
List<String> myList...
Bundle b = getIntent().getExtras();
if (b != null) {
myList = bundle.getStringArrayList("KEY");
}
I hope this will help someone...
To pass ArrayList from one activity to another activity, one should include
intent.putStringArrayListExtra(KEY, list); //where list is ArrayList which you want to pass
before starting the activity.And to get the ArrayList in another activity include
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
temp = bundle.getStringArrayList(KEY); // declare temp as ArrayList
}
you will be able to pass ArrayList through this.Hope this will be helpful to you.
Use of ViewModel is better fix than Serializable or Parcelable
I am having a class EmployeeInfo as the following:
public class EmployeeInfo {
private int id; // Employee ID
private String name; // Employee Name
private int age;// Employee Age
public int getEmployeeID() {
return id;
}
public void setEmployeeID(int id) {
this.id = id;
}
public String getEmployeeName() {
return name;
}
public void setEmployeeName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age= age;
}
}
ArrayList<EmployeeInfo> employeeInfo object contains the emplyoyee info data for multiple employees.
I want to transfer the data( ArrayList employeeInfo ) from Activity1 to Activity2.
Is using Parcelable the only way to transfer the data from Activity1 to Activity2?
If not , what are the alternatives.
If yes ,kindly provide the prototype code of Parcelable along with the sample code on how to transfer the object data from Activity1 to Activity2.
Here is my implementation of Parceleble:
public class ProfileData implements Parcelable {
private int gender;
private String name;
private String birthDate;
public ProfileData(Parcel source) {
gender = source.readInt();
name = source.readString();
birthDate = source.readString();
}
public ProfileData(int dataGender, String dataName, String dataBDate) {
gender = dataGender;
name = dataName;
birthDate = dataBDate;
}
// Getters and Setters are here
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(gender);
out.writeString(name);
out.writeString(birthDate);
}
public static final Parcelable.Creator<ProfileData> CREATOR
= new Parcelable.Creator<ProfileData>() {
public ProfileData createFromParcel(Parcel in) {
return new ProfileData(in);
}
public ProfileData[] newArray(int size) {
return new ProfileData[size];
}
};
}
and how I transfer data:
Intent parcelIntent = new Intent().setClass(ActivityA.this, ActivityB.class);
ProfileData data = new ProfileData(profile.gender, profile.getFullName(), profile.birthDate);
parcelIntent.putExtra("profile_details", data);
startActivity(parcelIntent);
and take data:
Bundle data = getIntent().getExtras();
ProfileData profile = data.getParcelable("profile_details");
You can simply let your EmployeeInfo class implement Serializable. Or you can send data like this
intent.putExtra("id", employInfo.getEmployeeID());
intent.putExtra("name", employInfo.getEmployeeName());
intent.putExtra("age", employInfo.getAge());
If you need to transfer a list of your custom classes, i'd use the first approach. So you would be able to put entire list as Serializable.
However they said that everyone should use Parcelable instead because it's "way faster". Tbh, I'd never used it, because it needs more effort and I doubt somebody can realize the difference in speed in a regular application w/o a load of data sending via intent
Good question. Looking at the docs and doing armchair coding:
It may be possible to pass an object between Activities by calling putExtras(Bundle) and myBundle.putSerializable. The object and the entire object tree would need to implement serializable.
JAL
EDIT: The answer is yes:
It is possible to pass an immutable object between Activities by calling putExtras(Bundle) and myBundle.putSerializable. The object and the entire object tree would need to implement serializable. This is a basic tenet of Object Oriented Programming, passing of stateful messages.
First we create the immutable object by declaring a new class:
package jalcomputing.confusetext;
import java.io.Serializable;
/*
* Immutable messaging object to pass state from Activity Main to Activity ManageKeys
* No error checking
*/
public final class MainManageKeysMessage implements Serializable {
private static final long serialVersionUID = 1L;
public final int lengthPassword;
public final long timeExpire;
public final boolean isValidKey;
public final int timeoutType;
public MainManageKeysMessage(int lengthPassword, long timeExpire, boolean isValidKey, int timeoutType){
this.lengthPassword= lengthPassword;
this.timeExpire= timeExpire;
this.isValidKey= isValidKey;
this.timeoutType= timeoutType;
}
}
Then we create an immutable stateful instance of the class, a message, in the parent activity, and send it in an intent as in:
private void LaunchManageKeys() {
Intent i= new Intent(this, ManageKeys.class); // no param constructor
// push data (4)
MainManageKeysMessage message= new MainManageKeysMessage(lengthPassword,timeExpire,isValidKey,timeoutType);
Bundle b= new Bundle();
b.putSerializable("jalcomputing.confusetext.MainManageKeysMessage", message);
i.putExtras(b);
startActivityForResult(i,REQUEST_MANAGE_KEYS); // used for callback
}
Finally, we retrieve the object in the child activity.
try {
inMessage= (MainManageKeysMessage) getIntent().getSerializableExtra("jalcomputing.confusetext.MainManageKeysMessage");
lengthPassword= inMessage.lengthPassword;
timeoutType= inMessage.timeoutType;
isValidKey= inMessage.isValidKey;
timeExpire= inMessage.timeExpire;
} catch(Exception e){
lengthPassword= -1;
timeoutType= TIMEOUT_NEVER;
isValidKey= true;
timeExpire= LONG_YEAR_MILLIS;
}
Well there is another way to transfer an object.We can use application to transfer object and this is way is far better way in my opinion.
First of all create your custom application in your main package.
public class TestApplication extends Application {
private Object transferObj;
#Override
public void onCreate() {
super.onCreate();
// ACRA.init(this);
}
public Object getTransferObj() {
return transferObj;
}
public void setTransferObj(Object transferObj) {
this.transferObj = transferObj;
}
}
Now use setTransfer and get transfer methods to move abjects from one activity to other like:
To Transfer:
((TestApplication) activity.getApplication()).setTransferObj(Yous object);
ToRecieve:
Object obj=((TestApplication) activity.getApplication()).getTransferObj();
NOTE
Always remember to make entry of this application in manifest application tag:
<application
android:name=".TestApplication">
</application>
You can convert your object to jsonstring using Gson or Jakson and pass using intent as string and read the json in another activity.