I have an ArrayList (A) that contains another 2 ArrayLists(B) , I am getting A's data from a json file, in the first activity I can see that A and B both are not empty, but when I pass A to another Activity or a fragment, A stays full but B becomes empty, All the objects used implements Parcelable, this is a snippet of the code used to send and retrieve the data :
Intent myIntent = new Intent(LauncherActivity.this, AcceuilActivity.class);
myIntent.putParcelableArrayListExtra("listeOffres",projectsList);
startActivity(myIntent);
finish();
and this is how I retrieve A that contains B offresList=getIntent().getParcelableArrayListExtra("listeOffres");
Check your Parceble model file. Let's take an example of User here and check below code. Also, check the argument used to passing ArrayList in intent. If this may not help you then please provide more details.
protected User(Parcel in) {
name = in.readString();
....
gender = in.readString();
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
....
parcel.writeString(gender);
}
I had the same problem and I solved it like this:
Intent myIntent = new Intent(LauncherActivity.this, AcceuilActivity.class);
myIntent.putExtra("listeOffres",projectsList);
startActivity(myIntent);
finish();
and this for how to retrive data
offresList = (ArrayList<ModelClass>) getIntent().getSerializableExtra("listeOffres");
then implements Serializable Like:
class ModelClass implements Serializable
{}
Related
I am trying to open another activity by intent and putExtra.
It used to run fine previously, but now it crashes.
startActivity(new Intent(ForgotPassword.this, OtpVerification.class)
.putExtra("user", user)
.putExtra("otp", verificationId));
finish();
the user here is a class object and am receiving it in another activity
user = getIntent().getParcelableExtra("user");
the app is not even going to another activty and crashes without any error message in logcat.
It only happens if i add .putExtra code
Try adding the putExtra in the following way
Intent intent = new Intent(ForgotPassword.this, OtpVerification.class);
intent.putExtra("user", user);
intent.putExtra("otp", verificationId);
startActivity(intent);
finish();
and then get the intent extras
Intent intent= getIntent();
Bundle extras = intent.getExtras();
if(extras != null)
String data = extras.getString("keyName");
Your user is an Object that you're trying to pass from one activity to another.
So you can create a custom class that implements the Serializable interface.(you must be able to use Parcelable too but i don't have experience with it )
//To pass:
intent.putExtra("User", user);
// To retrieve object in second Activity
getIntent().getSerializableExtra("User");
Point to note: each nested class in your main custom class must have implemented the Serializable interface
eg:
class MainClass implements Serializable {
public MainClass() {}
public static class ChildClass implements Serializable {
public ChildClass() {}
}
}
Ref:How to pass an object from one activity to another on Android
Thank you for your suggestions, the actual problem I found was that my user object had a variable called image (String type) and had a value of length about 1,000,000 (I was storing string encoded image using base64 in it). Once i decreased the size to thousands , it worked. I don't know why the app cannot send such large data across activities.
I have 2 activities.
In activity A, I have 4 EditTexts that can only contain integer.
there is a button, that should calculate the average of those 4 numbers entered by user.
In activity B, there are 5 Text views (4 for numbers, 1 for result).
when the button in activity A is pressed.
It should pass the numbers from EditText in Activity A to Text View in Activity B, also should show the average of 4 numbers in Results Text view.
I watched so many tutorials, but they are only for one value and when I try to duplicate the code for more than one value the app crashes.
One way would be to send the values as "extras" of the Intent you use to start Activity B.
Here is a possible code for Activity A:
Intent i = new Intent(this, ActivityB.class);
i.putExtra("1", num1);
i.putExtra("2", num2);
i.putExtra("3", num3);
i.putExtra("4", num4);
i.putExtra("average", result);
startActivity(i);
This code assumes you have the integers you want to send in separate variables num1 - num4, and calculated the average in another variable called "result".
To unpack this in Activity B, you would do something like this:
Intent i = getIntent();
textView1.setText(i.getIntExtra("1", 0); //0 is the default value in case the extra does not exist
textView2.setText(i.getIntExtra("2", 0);
textView3.setText(i.getIntExtra("3", 0);
textView4.setText(i.getIntExtra("4", 0);
resultView.setText(i.getIntExtra("average", 0));
You can also put your numbers in an array, and use one call to putExtra and one call to getIntArrayExtra.
This would be more elegant, but I wanted to demonstrate sending multiple separate numbers.
1.Use the Intention Bundle to pass
activityA code sends data
Intent intent=new Intent(MainActivity.this,ActivityB.class);
Bundle bundle=new Bundle();
bundle.putInt("num1",10);
bundle.putInt("num2",20);
intent.putExtra("bun",bundle);
startActivity(intent);
activityB code receives data
Intent intent=getIntent();
Bundle bundle=intent.getBundleExtra("bun");
int num1=bundle.getInt("num1",0);
int num2=bundle.getInt("num2",0);
2.Use serialized object Seriazable
The implementation class
public class DataUtils implements Serializable {
private int name;
private int age;
public String getName() {
return name;
}
public void setName(int name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
activityA code sends data
Intent intent = new Intent(ActivityA.this,ActivityB.class);
DataUtils dataUtils = new DataUtils();
dataUtils.setAge(20);
dataUtils.setName(10);
intent.putExtra("du",dataUtils);
startActivity(intent);
activityB code receives data
Intent intent=getIntent();
Serializable serializable=intent.getSerializableExtra("du");
if (serializable instanceof DataUtils){
DataUtils db=(DataUtils) serializable;
int name=db.getName();
int age=db.getAge();
}
3.use sharedPreferences to pass data
4.Pass data using static variables of the class
The best way to do it is to use Intent.putExtra(), where you can store key-value pairs. Here's a short guide on how to do it: How to use intent.putextra to pass data between activities
How can I receive a custom ArrayList from another Activity via Intent? For example, I have this ArrayList in Activity A:
ArrayList<Song> songs;
How could I get this list inside Activity B?
The first part to understand is that you pass information from Activity A to Activity B using an Intent object, inside which you can put "extras". The complete listing of what you can put inside an Intent is available here: https://developer.android.com/reference/android/content/Intent.html (see the various putExtra() methods, as well as the putFooExtra() methods below).
Since you are trying to pass an ArrayList<Song>, you have two options.
The first, and the best, is to use putParcelableArrayListExtra(). To use this, the Song class must implement the Parcelable interface. If you control the source code of Song, implementing Parcelable is relatively easy. Your code might look like this:
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putParcelableArrayListExtra("songs", songs);
The second is to use the version of putExtra() that accepts a Serializable object. You should only use this option when you do not control the source code of Song, and therefore cannot implement Parcelable. Your code might look like this:
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putSerializableExtra("songs", songs);
So that's how you put the data into the Intent in Activity A. How do you get the data out of the Intent in Activity B?
It depends on which option you selected above. If you chose the first, you will write something that looks like this:
List<Song> mySongs = getIntent().getParcelableArrayListExtra("songs");
If you chose the second, you will write something that looks like this:
List<Song> mySongs = (List<Song>) getIntent().getSerializableExtra("songs");
The advantage of the first technique is that it is faster (in terms of your app's performance for the user) and it takes up less space (in terms of the size of the data you're passing around).
Misam is sending list of Songs so it can not use plain putStringArrayList(). Instead, Song class has to implement Parcelable interface. I already explained how to implement Parcelable painless in post here.
After implementing Parcelable interface just follow Uddhavs answer with small modifications:
// First activity, adding to bundle
bundle.putParcelableArrayListExtra("myArrayListKey", arrayList);
// Second activity, reading from bundle
ArrayList<Song> list = getIntent().getParcelableArrayListExtra("myArrayListKey");
I hope this helps you.
1. Your Song class should be implements Parcelable Class
public class Song implements Parcelable {
//Your setter and getter methods
}
2. Put your arraylist to putParcelableArrayListExtra()
public class ActivityA extends AppCompatActivity {
ArrayList<Song> songs;
#Override
protected void onCreate(Bundle savedInstanceState) {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), ActivityB.class)
.putParcelableArrayListExtra("songs", (ArrayList<? extends Parcelable>) songs));
}
});
}
3. In the ActivityB
public class ActivityB extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
final ArrayList<Song> songs = intent.getParcelableArrayListExtra("songs");
//Check the value in the console
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (Song value : songs) {
System.out.println(value.getTitle());
}
}
});
}
to send a string arrayList in Java you can use,
intent.putStringArrayListExtra("key", skillist <- your arraylist);
and
List<String> listName = getIntent().getStringArrayListExtra("key");
Please note, bundle is one of the key components in Android system that is used for inter-component communications. All you have to think is how you can use put your Array inside that bundle.
Sending side (Activity A)
Intent intent1 = new Intent(MainActivity.this, NextActivity.class);
Bundle bundle = new Bundle();
Parcelable[] arrayList = new Parcelable[10];
/* Note: you have to use writeToParcel() method to write different parameters values of your Song object */
/* you can add more string values in your arrayList */
bundle.putParcelableArray("myParcelableArray", arrayList);
intent1.putExtra("myBundle", bundle);
startActivity(intent1);
Receiving side (Activity B)
Bundle bundle2 = getIntent().getBundleExtra("myBundle"); /* you got the passsed bundle */
Parcelable[] arrayList2 = bundle.getParcelableArray("myParcelableArray");
I am creating an Android app. One of the functions is to collect some data (item name, item ID and the barcode string) from the user .
Activity1 is a form. User enters the item name and item number manually. For the barcode string, user clicks on the "scan" button then Activity2 (Scanner) is started in order to scan and read the barcode. Once the barcode is read, Activity1 (the form) starts again and all data should appear on the form.
When Activity2 starts by Intent, Activity1 is killed. So, I have to get the item name and item number and store them temporarily before staring the Intent. Then when Activity1 starts again, those data will be rendered on the form again.
Now I am thinking to use Intent Extra to keep the item name and number, and pass them to Activity2 and back to Activity1. Given that Activity2 doesn't need those data, I wonder if that is the right way to do in this scenario. Is there any better way? Should I use Shared Preferences instead?
In Your first activity use put extra argument to intent like this:
// Assuming Activity2.class is second activity
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("variable_name", var); // here you are passing var to second activity
startActivity(intent);
Then in second activity retrieve argument like this:
String var2 = getIntent().getStringExtra(variable_name);
You could create a singleton class and expose setter(for saving) and getter (for retrieving) methods for the model objects (here two private string variables).This class will be alive with your application:
public class MyClass{
private static MyClass instance=null;
public static getInstance(){
if(instance==null){
instance=new MyClass();
}
return instance;
}
private String itemName;
private String itemNumber;
//setter and getter methods here
}
why need to kill the Activity 1, try to call
on Activity 1
declare private int SCAN_BARCODE_REQUEST = 101;
and then
//finish(); dont use this to destroy activity 1
startActivityForResult(new intent(this,Activity2.class), SCAN_BARCODE_REQUEST);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SCAN_BARCODE_REQUEST) {
if (resultCode == RESULT_OK) {
String barcode = data.getStringExtra("BARCODE");
//handle your barcode string here
}
}
}
on your Activity 2,
change your start Activity1 with
Intent intent = new Intent();
intent.putExtra("BARCODE", barcodeString);
setResult(RESULT_OK, intent);
finish();
You can use SharedPreferences.
You can learn how to use them here:
https://www.tutorialspoint.com/android/android_shared_preferences.htm
https://developer.android.com/training/basics/data-storage/shared-preferences.html
SharedPreferences is a really good solution for such applications. It is very simple and easy to use and implement.
have total 3 activites. I pass the data from the first activity like this:
Intent intent = new Intent(getActivity(), Movie_rev_fulldis_activity.class);
intent.putExtra("mov_pos", position + "");
startActivity(intent);
this working fine all data visible to my second activity but i want to display
one filed item to third activity when i click second activity image
here my second activity
youtube_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent youtube= new Intent(getApplicationContext(),PlayYouTube1st.class);
youtube.putExtra("youtubeLink",youtubeLink);
startActivity(youtube);
// Toast.makeText(Movie_rev_fulldis_activity.this,
// youtubeLink, Toast.LENGTH_LONG).show();
}
});
youtubeLink=Reviews_update.revData.get(mov_pos).getYoutubeLink();
Toast.makeText(Movie_rev_fulldis_activity.this,
Reviews_update.revData.get(mov_pos).getYoutubeLink(), Toast.LENGTH_LONG).show();
mov_pos=Integer.parseInt((getIntent().getExtras()).getString("mov_pos"));
in second activity i am getting values but when i send one filed to third activity that value passing null any one please help me i stuck in their,
I want to show YoutubeLink field sencnd activity to third activity how to parse that any one please help
In FastActivity:
Intent in = new Intent(FastActivity.this, SecondActivity.class);
in.putExtra("a", yourdata);
startActivity(in);
In SecondActivity:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String a = extras.getString("a");
}
You can also use any static variable and use it in any class
static int a = 5;
And in any other class
int b = classname.a;
classname is the class where static variable is declared.
Make that variable static and then pass
Your variable object reference get change in the THIRD Activity so, it returns null