I have an ArrayList of CustomInput objects and DataWrapper class with getter and setter for the ArrayList. I want to pass DataWrapper from Non-Activity class to Activity class. I have tried implementing Serializable, but I get Parcelable encountered ioexception writing serializable object cause by NotSerializableException.
DataWrapper.java
public class DataWrapper implements Serializable {
private static final long serialVersionUID = 1L;
private ArrayList<CustomInput> customInputs;
public void setFields(ArrayList<CustomInput> data) {
this.customInputs = data;
}
public ArrayList<CustomInput> getFields() {
return this.customInputs;
}
}
Non-Activiy class
public void showActivity() {
Intent intent = new Intent(request, ActivityKorak.class);
intent.putExtra("title", title);
DataWrapper dw = new DataWrapper();
dw.setFields(fields);
intent.putExtra("data", dw);
request.startActivity(intent);
}
ActivityKorak.class->onCreate()
Intent intent = getIntent();
String title = intent.getStringExtra("title");
DataWrapper dw = (DataWrapper) intent.getSerializableExtra("data");
ArrayList<CustomInput> fields = dw.getFields();
No need to create new class DataWrapper.java. Because ArrayList is serializable.
Non-Activiy class
public void showActivity() {
Intent intent = new Intent(request, ActivityKorak.class);
intent.putExtra("title", title);
intent.putExtra("data", fields);
request.startActivity(intent);
}
ActivityKorak.class->onCreate()
Intent intent = getIntent();
String title = intent.getStringExtra("title");
DataWrapper dw = (DataWrapper) intent.getSerializableExtra("data");
ArrayList<CustomInput> fields = dw.getFields();
hi please check how we can send arraylist in intent
ArrayList<HashMap<String, String>> aldata = new ArrayList<HashMap<String, String>>();
i assumed here data is already added in your arraylist, please check
Send data and start other activity,
Intent intent = new Intent(this,AbcActivity.class);
intent.putExtra("aldata", aldata_TaxiLine);
startActivity(intent);
Get data in your next activity,
ArrayList<HashMap<String, String>> aldata1;
and call this in your oncreate
aldata = (ArrayList<HashMap<String, String>>) getIntent()
.getSerializableExtra("aldata");
hope this will help you.
Related
The problem i've stuck is
I have 4 activities namely A, B ,C and D . the flow is first A then B then C and so on.
I want to pass data of A to B and then data A+B to C , then data of A+B+C to D and so on..
I've used in Activity A Intent of Hashmap
HashMap<String, String> hashMap = new HashMap<>(); //declared Globally
hashMap.put("key", value);
i.putExtra("map", hashMap); (i is the Intent Object)
startActivity(i); //Starting the Intent
And on receiving side i.e Activity B
HashMap<String, String> hashMap = (HashMap<String, String>)i.getSerializableExtra("map");
Here i'm able to get Successfully the data , but when i try to pass on foward this data to next activity i get null values causing NullPointerException.
In the B activity
Hashmap<String,String> hashMap2 = new HashMap<>;
hashMap2.put("key",hashMap.get("key"));
Log.i("Value:",hashMap.get("key"));
Here i get the values successfully put when same way i pass hashmap2 to C activity i get NullPointerException.
Not understanding what's wrong in here.
I want to pass the values and not store them so i'm preferring Intents over Shared Preferences.
Thanks for your help .I've found out why it was giving me null values
1)In B activity I was doing the wrong way to get the values i.e first getIntent and then sum of A+B values i.e putExtra should be used only when I declare the new intent for the C class. As i was first doing putExtra and then new Intent to C , so in C i used to get Null Values.
This might help you.You can simply send values like this and it will work.
In Activity A:
Intent intent=new Intent(ActivityA.this,ActivityB.class);
intent.putExtra("key1","value1");
startActivity(intent);
In Activity B:
String value1=getIntent.getStringExtra("key1");
Intent intent=new Intent(ActivityB.this,ActivityC.class);
intent.putExtra("key1",value1);
intent.putExtra("key2","value2");
startActivity(intent);
In Activity C:
String value1=getIntent.getStringExtra("key1");
String value2=getIntent.getStringExtra("key2");
Intent intent=new Intent(ActivityC.this,ActivityD.class);
intent.putExtra("key1",value1);
intent.putExtra("key2",value2);
intent.putExtra("key3","value3");
startActivity(intent);
In Activity D,
String value1=getIntent.getStringExtra("key1");
String value2=getIntent.getStringExtra("key2");
String value3=getIntent.getStringExtra("key3");
It is really hectic to send value from one activity to another using Intent same code written in every activity but alternative way is to use cache
public class CacheManager {
public static Map<String, Object> cachedData = new HashMap<>();
public static void clearCache() {
cachedData.clear();
}
public static void putIntoCache(String key, Object value) {
CacheManager.cachedData.put(key, value);
}
public static Object getFromCache(String key) {
if (cachedData.containsKey(key)) {
return CacheManager.cachedData.get(key);
} else {
return null;
}
}
}
One of the advantage of this approch is you can modify data where ever you want and put modified data in cache again
step 1- Create class called cacheManager
Step 2- from anywhere you can put value into Cache HashMap
step 3- from anywhere you can get Value From Cache
Enjoy !
use intent.putExtra in intent like this.
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String strName = null;
i.putExtra("STRING_I_NEED", strName);
startActivity(i);/
and retrieve .
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
First Option
Store data in application context
Declare a class that should extend Application
public class HashTableBundle extends Application {
private Hashtable<String,String> mHashTable = null;
public Hashtable<String, String> getmHashTable() {
return mHashTable;
}
public void setmHashTable(Hashtable<String, String> mHashTable) {
this.mHashTable = mHashTable;
}
}
You can set data into application context by
HashTableBundle mStat = (HashTableBundle) getApplicationContext();
mStat.setmHashTable(mMainHashTable);
You can get it from any activity by using
HashTableBundle mStat = (HashTableBundle) getApplicationContext();
Hashtable<String,String> mHashTable = mStat. getmHashTable();
You need to add HashTableBundle in AndroidManifest otherwise application Throws class cast exception
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:name=".HashTableBundle"> . . . </application>
Second option
MainActivity.java
public class MainActivity extends AppCompatActivity {
Hashtable<String,String> mMainHashTable = new Hashtable<>();
MHashBundle mm = new MHashBundle();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMainHashTable.put("hai","I am From MainActivity");
mm.setmHashTable(mMainHashTable);
Intent mIntent = new Intent(MainActivity.this,ClassB.class);
mIntent.putExtra("myhashtable", mm);
System.out.println("data Main Activity :"+mMainHashTable.get("hai"));
startActivity(mIntent);
this.finish();
}
}
Hashtable container MHashBundle.java
public class MHashBundle implements Serializable {
private Hashtable<String,String> mHashTable = null;
public Hashtable<String, String> getmHashTable() {
return mHashTable;
}
public void setmHashTable(Hashtable<String, String> mHashTable) {
this.mHashTable = mHashTable;
}
}
note MHashBundle.java must implement Serializable
Second Activity ClassB.java
public class ClassB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent mIntent = new Intent(ClassB.this,ClassC.class);
MHashBundle mBundle = (MHashBundle) getIntent().getSerializableExtra("myhashtable");
mIntent.putExtra("myhashtable",mBundle);
System.out.println("data class B :"+mBundle.getmHashTable().get("hai"));
startActivity(mIntent);
this.finish();
}
Thrird Activity
public class ClassC extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MHashBundle mBundle = (MHashBundle) getIntent().getSerializableExtra("myhashtable");
System.out.println("data class C :"+mBundle.getmHashTable().get("hai"));
}
}
I like to pass object from one activity from another activity. I implemented Serializable.
But somehow, the object is not passed and at the receiver side I get NULL.
Can pls check where is wrong?
public class TrackerInfo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
String Idnumber;
String Simcardnumber;
String Description;
String Model;
String time;
public String getSimcardnumber() {
return Simcardnumber;
}
public String getDescription() {
return Description;
}
public String getModel() {
return Model;
}
public void setModel(String model) {
this.Model = model;
}
public String getTime() {
return time;
}
public void setInforFromCursor(Cursor cursor){
this.Idnumber = cursor.getString(1);
this.Simcardnumber = cursor.getString(2);
this.Description = cursor.getString(3);
this.Model = cursor.getString(4);
this.time = cursor.getString(5);
}}
At sender side,
#Override
public void itemSelected(String id) {
//get Tracker info
dbHelper = new TrackerDBAdapter(this);
dbHelper.open();
Cursor cursor = dbHelper.fetchListByIDNum(id);
TrackerInfo tracker = new TrackerInfo();
tracker.setInforFromCursor(cursor);
dbHelper.close();
LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();
obj.put("TRAKCER", tracker);
Bundle b = new Bundle();
b.putSerializable("bundleobj", obj);
Intent intent = new Intent(this, DetailMapView.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("bundleobj", b);
startActivity(intent);
}
At receiver side,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_detail_map_view);
try { setContentView(R.layout.activity_detail_map_view);
Bundle bn = new Bundle();
bn = getIntent().getExtras();
HashMap<String, Object> getobj = new HashMap<String, Object>();
getobj = (HashMap<String, Object>) bn.getSerializable("bundleobj");
trackerinfo = (TrackerInfo) getobj.get("TRACKER");
} catch (Exception e) {
Log.e("Err", e.getMessage());
}}
I think that your problem is here:
obj.put("TRAKCER", tracker);
You are adding tracker to HashMap with key TRAKCER
But here:
getobj.get("TRACKER");
You are trying to get object with key TRACKER but keys are not equal and this is reason of NPE. You need to fix
obj.put("TRACKER", tracker);
Now keys are equal so it should works.
Update:
As #Sam pointed out you wrapped your HashMap into Bundle and Bundle into Intent. So if your approach had work you need to do following:
LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();
obj.put("TRACKER", tracker);
Bundle b = new Bundle();
b.putSerializable("trackerObj", obj);
Intent intent = new Intent(this, DetailMapView.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("bundleObj", b);
And for retrieving HashMap:
Bundle wrapper = getIntent().getBundleExtra("bundleObj"); // this Bundle contains HashMap
HashMap<String, Object> obj = (HashMap<String, Object>) wrapper.getSerializable("trackerObj");
Recommendation:
How #Sam pointed out again, better and cleaner way is to wrap directly your HashMap as Serializable into Intent with putExtra("trackerObj", obj) method and then easily retrieve it as
HashMap<String, Object> o = (HashMap<String, Object>) getIntent().getSerializableExtra("trackerObj");
You have a few mistakes, please read Sajmon's answer, but you are also putting a Bundle in a Bundle, but only reading from the outer Bundle. Remove code like this:
Bundle b = new Bundle();
b.putSerializable("bundleobj", obj);
And put the data directly into the Intent:
Intent intent = new Intent(this, DetailMapView.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("bundleobj", obj);
// You may need to help the compiler by casting it to a Serializable
//intent.putExtra("bundleobj", (Serializable) obj);
In order to use your double Bundle method you need to fetch both "bundleobj" tags:
bn = getIntent().getExtras().getBundle("bundleobj");
HashMap<String, Object> getobj = (HashMap<String, Object>) bn.getSerializable("bundleobj");
I have the following in code in my onClick() method as
List<Question> mQuestionsList = QuestionBank.getQuestions();
Now I have the intent after this line, as follows :
Intent resultIntent = new Intent(this, ResultActivity.class);
resultIntent.putParcelableArrayListExtra("QuestionsExtra", (ArrayList<? extends Parcelable>) mQuestionsList);
startActivity(resultIntent);
I don't know how to pass this question lists in the intent from one activity to another activity
My Question class
public class Question {
private int[] operands;
private int[] choices;
private int userAnswerIndex;
public Question(int[] operands, int[] choices) {
this.operands = operands;
this.choices = choices;
this.userAnswerIndex = -1;
}
public int[] getChoices() {
return choices;
}
public void setChoices(int[] choices) {
this.choices = choices;
}
public int[] getOperands() {
return operands;
}
public void setOperands(int[] operands) {
this.operands = operands;
}
public int getUserAnswerIndex() {
return userAnswerIndex;
}
public void setUserAnswerIndex(int userAnswerIndex) {
this.userAnswerIndex = userAnswerIndex;
}
public int getAnswer() {
int answer = 0;
for (int operand : operands) {
answer += operand;
}
return answer;
}
public boolean isCorrect() {
return getAnswer() == choices[this.userAnswerIndex];
}
public boolean hasAnswered() {
return userAnswerIndex != -1;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
// Question
builder.append("Question: ");
for(int operand : operands) {
builder.append(String.format("%d ", operand));
}
builder.append(System.getProperty("line.separator"));
// Choices
int answer = getAnswer();
for (int choice : choices) {
if (choice == answer) {
builder.append(String.format("%d (A) ", choice));
} else {
builder.append(String.format("%d ", choice));
}
}
return builder.toString();
}
}
Between Activity: Worked for me
ArrayList<Object> object = new ArrayList<Object>();
Intent intent = new Intent(Current.class, Transfer.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)object);
intent.putExtra("BUNDLE",args);
startActivity(intent);
In the Transfer.class
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
ArrayList<Object> object = (ArrayList<Object>) args.getSerializable("ARRAYLIST");
Hope this help's someone.
Using Parcelable to pass data between Activity
This usually works when you have created DataModel
e.g. Suppose we have a json of type
{
"bird": [{
"id": 1,
"name": "Chicken"
}, {
"id": 2,
"name": "Eagle"
}]
}
Here bird is a List and it contains two elements so
we will create the models using jsonschema2pojo
Now we have the model class Name BirdModel and Bird
BirdModel consist of List of Bird
and Bird contains name and id
Go to the bird class and add interface "implements Parcelable"
add implemets method in android studio by Alt+Enter
Note: A dialog box will appear saying Add implements method
press Enter
The add Parcelable implementation by pressing the Alt + Enter
Note: A dialog box will appear saying Add Parcelable implementation
and Enter again
Now to pass it to the intent.
List<Bird> birds = birdModel.getBird();
Intent intent = new Intent(Current.this, Transfer.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("Birds", birds);
intent.putExtras(bundle);
startActivity(intent);
And on Transfer Activity onCreate
List<Bird> challenge = this.getIntent().getExtras().getParcelableArrayList("Birds");
Thanks
If there is any problem please let me know.
Steps:
Implements your object class to serializable
public class Question implements Serializable`
Put this in your Source Activity
ArrayList<Question> mQuestionList = new ArrayList<Question>;
mQuestionsList = QuestionBank.getQuestions();
mQuestionList.add(new Question(ops1, choices1));
Intent intent = new Intent(SourceActivity.this, TargetActivity.class);
intent.putExtra("QuestionListExtra", mQuestionList);
Put this in your Target Activity
ArrayList<Question> questions = new ArrayList<Question>();
questions = (ArrayList<Questions>) getIntent().getSerializableExtra("QuestionListExtra");
It works well,
public class Question implements Serializable {
private int[] operands;
private int[] choices;
private int userAnswerIndex;
public Question(int[] operands, int[] choices) {
this.operands = operands;
this.choices = choices;
this.userAnswerIndex = -1;
}
public int[] getChoices() {
return choices;
}
public void setChoices(int[] choices) {
this.choices = choices;
}
public int[] getOperands() {
return operands;
}
public void setOperands(int[] operands) {
this.operands = operands;
}
public int getUserAnswerIndex() {
return userAnswerIndex;
}
public void setUserAnswerIndex(int userAnswerIndex) {
this.userAnswerIndex = userAnswerIndex;
}
public int getAnswer() {
int answer = 0;
for (int operand : operands) {
answer += operand;
}
return answer;
}
public boolean isCorrect() {
return getAnswer() == choices[this.userAnswerIndex];
}
public boolean hasAnswered() {
return userAnswerIndex != -1;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
// Question
builder.append("Question: ");
for(int operand : operands) {
builder.append(String.format("%d ", operand));
}
builder.append(System.getProperty("line.separator"));
// Choices
int answer = getAnswer();
for (int choice : choices) {
if (choice == answer) {
builder.append(String.format("%d (A) ", choice));
} else {
builder.append(String.format("%d ", choice));
}
}
return builder.toString();
}
}
In your Source Activity, use this :
List<Question> mQuestionList = new ArrayList<Question>;
mQuestionsList = QuestionBank.getQuestions();
mQuestionList.add(new Question(ops1, choices1));
Intent intent = new Intent(SourceActivity.this, TargetActivity.class);
intent.putExtra("QuestionListExtra", ArrayList<Question>mQuestionList);
In your Target Activity, use this :
List<Question> questions = new ArrayList<Question>();
questions = (ArrayList<Question>)getIntent().getSerializableExtra("QuestionListExtra");
Your bean or pojo class should implements parcelable interface.
For example:
public class BeanClass implements Parcelable{
String name;
int age;
String sex;
public BeanClass(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public static final Creator<BeanClass> CREATOR = new Creator<BeanClass>() {
#Override
public BeanClass createFromParcel(Parcel in) {
return new BeanClass(in);
}
#Override
public BeanClass[] newArray(int size) {
return new BeanClass[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
dest.writeString(sex);
}
}
Consider a scenario that you want to send the arraylist of beanclass type from Activity1 to Activity2.
Use the following code
Activity1:
ArrayList<BeanClass> list=new ArrayList<BeanClass>();
private ArrayList<BeanClass> getList() {
for(int i=0;i<5;i++) {
list.add(new BeanClass("xyz", 25, "M"));
}
return list;
}
private void gotoNextActivity() {
Intent intent=new Intent(this,Activity2.class);
/* Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)list);
intent.putExtra("BUNDLE",args);*/
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("StudentDetails", list);
intent.putExtras(bundle);
startActivity(intent);
}
Activity2:
ArrayList<BeanClass> listFromActivity1=new ArrayList<>();
listFromActivity1=this.getIntent().getExtras().getParcelableArrayList("StudentDetails");
if (listFromActivity1 != null) {
Log.d("listis",""+listFromActivity1.toString());
}
I think this basic to understand the concept.
Pass your object via Parcelable.
And here is a good tutorial to get you started.
First Question should implements Parcelable like this and add the those lines:
public class Question implements Parcelable{
public Question(Parcel in) {
// put your data using = in.readString();
this.operands = in.readString();;
this.choices = in.readString();;
this.userAnswerIndex = in.readString();;
}
public Question() {
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(operands);
dest.writeString(choices);
dest.writeString(userAnswerIndex);
}
public static final Parcelable.Creator<Question> CREATOR = new Parcelable.Creator<Question>() {
#Override
public Question[] newArray(int size) {
return new Question[size];
}
#Override
public Question createFromParcel(Parcel source) {
return new Question(source);
}
};
}
Then pass your data like this:
Question question = new Question();
// put your data
Intent resultIntent = new Intent(this, ResultActivity.class);
resultIntent.putExtra("QuestionsExtra", question);
startActivity(resultIntent);
And get your data like this:
Question question = new Question();
Bundle extras = getIntent().getExtras();
if(extras != null){
question = extras.getParcelable("QuestionsExtra");
}
This will do!
The easiest way to pass ArrayList using intent
Add this line in dependencies block build.gradle.
implementation 'com.google.code.gson:gson:2.2.4'
pass arraylist
ArrayList<String> listPrivate = new ArrayList<>();
Intent intent = new Intent(MainActivity.this, ListActivity.class);
intent.putExtra("private_list", new Gson().toJson(listPrivate));
startActivity(intent);
retrieve list in another activity
ArrayList<String> listPrivate = new ArrayList<>();
Type type = new TypeToken<List<String>>() {
}.getType();
listPrivate = new Gson().fromJson(getIntent().getStringExtra("private_list"), type);
You can use object also instead of String in type
Works for me..
Simple as that !! worked for me
From activity
Intent intent = new Intent(Viewhirings.this, Informaall.class);
intent.putStringArrayListExtra("list",nselectedfromadapter);
startActivity(intent);
TO activity
Bundle bundle = getIntent().getExtras();
nselectedfromadapter= bundle.getStringArrayList("list");
If your class Question contains only primitives, Serializeble or String fields you can implement him Serializable. ArrayList is implement Serializable, that's why you can put it like Bundle.putSerializable(key, value) and send it to another Activity.
IMHO, Parcelable - it's very long way.
I do one of two things in this scenario
Implement a serialize/deserialize system for my objects and pass them as Strings (in JSON format usually, but you can serialize them any way you'd like)
Implement a container that lives outside of the activities so that all my activities can read and write to this container. You can make this container static or use some kind of dependency injection to retrieve the same instance in each activity.
Parcelable works just fine, but I always found it to be an ugly looking pattern and doesn't really add any value that isn't there if you write your own serialization code outside of the model.
You must need to also implement Parcelable interface and must add writeToParcel method to your Questions class with Parcel argument in Constructor in addition to Serializable. otherwise app will crash.
Your arrayList:
ArrayList<String> yourArray = new ArrayList<>();
Write this code from where you want intent:
Intent newIntent = new Intent(this, NextActivity.class);
newIntent.putExtra("name",yourArray);
startActivity(newIntent);
In Next Activity:
ArrayList<String> myArray = new ArrayList<>();
Write this code in onCreate:
myArray =(ArrayList<String>)getIntent().getSerializableExtra("name");
To set the data in kotlin
val offerIds = ArrayList<Offer>()
offerIds.add(Offer(1))
retrunIntent.putExtra(C.OFFER_IDS, offerIds)
To get the data
val offerIds = data.getSerializableExtra(C.OFFER_IDS) as ArrayList<Offer>?
Now access the arraylist
Implements Parcelable and send arraylist as putParcelableArrayListExtra and get it from next activity getParcelableArrayListExtra
example:
Implement parcelable on your custom class -(Alt +enter) Implement its methods
public class Model implements Parcelable {
private String Id;
public Model() {
}
protected Model(Parcel in) {
Id= in.readString();
}
public static final Creator<Model> CREATOR = new Creator<Model>() {
#Override
public ModelcreateFromParcel(Parcel in) {
return new Model(in);
}
#Override
public Model[] newArray(int size) {
return new Model[size];
}
};
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Id);
}
}
Pass class object from activity 1
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putParcelableArrayListExtra("model", modelArrayList);
startActivity(intent);
Get extra from Activity2
if (getIntent().hasExtra("model")) {
Intent intent = getIntent();
cartArrayList = intent.getParcelableArrayListExtra("model");
}
Your intent creation seems correct if your Question implements Parcelable.
In the next activity you can retrieve your list of questions like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getIntent() != null && getIntent().hasExtra("QuestionsExtra")) {
List<Question> mQuestionsList = getIntent().getParcelableArrayListExtra("QuestionsExtra");
}
}
You can pass the arraylist from one activity to another by using bundle with intent.
Use the code below
This is the shortest and most suitable way to pass arraylist
bundle.putStringArrayList("keyword",arraylist);
I found that most of the answers work but with a warning. So I have a tricky way to achieve this without any warning.
ArrayList<Question> questionList = new ArrayList<>();
...
Intent intent = new Intent(CurrentActivity.this, ToOpenActivity.class);
for (int i = 0; i < questionList.size(); i++) {
Question question = questionList.get(i);
intent.putExtra("question" + i, question);
}
startActivity(intent);
And now in Second Activity
ArrayList<Question> questionList = new ArrayList<>();
Intent intent = getIntent();
int i = 0;
while (intent.hasExtra("question" + i)){
Question model = (Question) intent.getSerializableExtra("question" + i);
questionList.add(model);
i++;
}
Note:
implements Serializable in your Question class.
You can use parcelable for object passing which is more efficient than Serializable .
Kindly refer the link which i am share contains complete parcelable sample.
Click download ParcelableSample.zip
You can Pass Arraylist/Pojo using bundle like this ,
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle args = new Bundle();
args.putSerializable("imageSliders",(Serializable)allStoriesPojo.getImageSliderPojos());
intent.putExtra("BUNDLE",args);
startActivity(intent);
Get those values in SecondActivity like this
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
String filter = bundle.getString("imageSliders");
You can try this. I think it will help you.
Don't fotget to Initialize value into ArrayList
ArrayList<String> imageList = new ArrayList<>();
Send data using intent.putStringArrayListExtra()....
Intent intent = new Intent(this, NextActivity.class);
intent.putStringArrayListExtra("IMAGE_LIST", imageList);
startActivity(intent);
Receive data using intent.getStringArrayListExtra()...
ArrayList<String> imageList = new ArrayList<>();
Intent intent = getIntent();
imageList = intent.getStringArrayListExtra("IMAGE_LIST");
As we know getSerializable() is deprecated so we can use other easy way to transfer array between activities or between fragment to activities:
First initialize Array of Cars:
private var carsList = ArrayList<Cars>()
On sending Activity/Fragment side:
val intent = Intent(mContext, SearchActivity::class.java)
intent.putExtra("cars_list", Gson().toJson(carsList))
startActivity(intent)
On Receiving Activity:
val type: Type = object : TypeToken<List<CarsModel?>?>() {}.type
categoryList = Gson().fromJson(intent.getStringExtra("cars_list"), type)
I had the exact same question and while still hassling with the Parcelable, I found out that the static variables are not such a bad idea for the task.
You can simply create a
public static ArrayList<Parliament> myObjects = ..
and use it from elsewhere via MyRefActivity.myObjects
I was not sure about what public static variables imply in the context of an application with activities. If you also have doubts about either this or on performance aspects of this approach, refer to:
What's the best way to share data between activities?
Using static variables in Android
Cheers.
I was trying to pass a String from an AsyncTask to a new Activity in AsyncTask.onPostExecute:
protected void onPostExecute(String response) {
Intent displayResponse = new Intent(context, DisplayResponse.class);
displayResponse.putExtra("package_name.DisplayResponse.response", response);
displayResponse.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(displayResponse);
}
where context = (Context) this in the MainActivity which starts the AsyncTask and passes context in the constructor.
In DisplayResponse getIntent().getStringExtra("package_name.DisplayResponse.response") is always null
If I use a simple Parcelable with just one String and pass that from
protected void onPostExecute(String response) {
Intent displayResponse = new Intent(context, DisplayResponse.class);
StringParcel sp = new StringParcel(response);
displayResponse.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle bundle = new Bundle();
bundle.putParcelable("response", sp);
displayResponse.putExtra("package_name.DisplayResponse.response", bundle);
context.startActivity(displayResponse);
}
I can then use the String in DisplayResponse:
Intent intent = getIntent();
Bundle extras = intent.getBundleExtra("package_name.DisplayResponse.response");
StringParcel sp = extras.getParcelable("response");
textView.setText(sp.parcelString);
So the question is why does the first method using putExtra, getStringExtra fail, whereas the second method using a Parcelable work?
I want to pass two values to another activity can I do this with putExtra or do I have to do it a more complicated way, which it seems from my reading. E.g.. can something like this work?
public final static String ID_EXTRA="com.fnesse.beachguide._ID";
Intent i = new Intent(this, CoastList.class);
i.putExtra(ID_EXTRA, "1", "111");
startActivity(i);
The above gives an error.
Edit
The first thing I tried was similar to:
i.putExtra(ID_EXTRA1, "1");
i.putExtra(ID_EXTRA2, "111");
but ID_EXTRA2 seems to write over ID_EXTRA1
So,
i.putExtra(ID_EXTRA, new String[] { "1", "111"});
Looks like the go but how do I extract the values from the array in the second activity, I have been using this for a single value.
passedVar = getIntent().getStringExtra(CoastList.ID_EXTRA);
I guess I have to turn ID_EXTRA into an array somehow???
You could pass a 'bundle' of extras rather than individual extras if you like, for example:
Intent intent = new Intent(this, MyActivity.class);
Bundle extras = new Bundle();
extras.putString("EXTRA_USERNAME","my_username");
extras.putString("EXTRA_PASSWORD","my_password");
intent.putExtras(extras);
startActivity(intent);
Then in your Activity that your triggering, you can reference these like so:
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String username_string = extras.getString("EXTRA_USERNAME");
String password_string = extras.getString("EXTRA_PASSWORD");
Or (if you prefer):
Bundle extras = getIntent().getExtras();
String username_string = extras.getString("EXTRA_USERNAME");
String password_string = extras.getString("EXTRA_PASSWORD");
You can pass multiple values by using multiple keys. Instead of
i.putExtra(ID_EXTRA, "1", "111");
do
i.putExtra(ID_EXTRA1, "1");
i.putExtra(ID_EXTRA2, "111");
Of course you have to define 2 constants for the keys and have to read both seperately in the new activity.
Or you can pass a string array via
i.putExtra(ID_EXTRA, new String[] { "1", "111"});
Putting extra values in class
public class MainActivity extends Activity {
public final static String USERNAME = "com.example.myfirstapp.MESSAGE";
public final static String EMAIL = "com.example.myfirstapp.EMAIL";
public void registerUser(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText userNameTxt = (EditText) findViewById(R.id.editText1);
EditText emailTxt = (EditText) findViewById(R.id.editText2);
String userName = userNameTxt.getText().toString();
String email = emailTxt.getText().toString();
intent.putExtra(USERNAME, userName);
intent.putExtra(EMAIL,email);
startActivity(intent);
}
Reading extra values from another class
public class DisplayMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String user = intent.getStringExtra(MainActivity.USERNAME);
String email = intent.getStringExtra(MainActivity.EMAIL);
Passing bundle of extra for kotlin coders
val intent = Intent(this, MyActivity::class.java)
val extras = Bundle().apply {
putString("EXTRA_USERNAME", "my_username")
putString("EXTRA_PASSWORD", "my_password")
}
intent.putExtras(extras)
startActivity(intent)
Then retrieve your values in the other activity like below:
val extras = getIntent().extras
val username_string = extras?.getString("EXTRA_USERNAME")
val password_string = extras?.getString("EXTRA_PASSWORD")
No you can't but you can pass an array using:
public Intent putExtra (String name, String[] value)
like this for example:
i.putExtra(ID_EXTRA, new String[]{"1", "111"});
Your example won't work, since the Extras are made out of a Key and a Value. You cant put multiple Keys and Values in one Extra
Also, your keys need to be Strings as far as I know (and noticed) but I might be wrong on that one.
Try this:
public final static String ID_EXTRA="com.fnesse.beachguide._ID";
Intent i = new Intent(this, CoastList.class);
i.putExtra("ID_Extra", ID_EXTRA);
i.putExtra("1", 111);
startActivity(i);
For a single small amount of value putExtra is perfect but when you pass multiple values and need to pass custom ArrayList or List then I think it's a bad idea. Solution is you can use Parcelable. You and also use Singleton or Serializable also.
Parcelable:
Parcelable class which you need to share.
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
Form your activity where you want to send
MyParcelable example = new MyParcelable();
.....
.....
Bundle bundle = new Bundle();
bundle.putParcelable("example", Parcels.wrap(example));
From another activity where you want to receive
MyParcelable example = Parcels.unwrap(getIntent().getParcelableExtra("example"));