How to get data value of ArrayList to another activity - android

Hey I have an arraylist in activity1.class I want to get data from that array to show the data episodeList.size() in activity2.class here my list code
public class EpisodeAdapter extends RecyclerView.Adapter<EpisodeAdapter.EpisodeHolder>{
private List<Episode> episodeList;
public EpisodeAdapter(List<Episode> episodeList) {
this.episodeList = episodeList;
}
#Override
public EpisodeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_episode , null);
EpisodeAdapter.EpisodeHolder mh = new EpisodeAdapter.EpisodeHolder(v);
return mh;
}
public int getItemCount() {
return episodeList.size();
}

Intent intent = new Intent(this, className);
intent.putParcelableArrayListExtra("episodeList", episodeList);
startActivity(intent);
and you can get it by
ArrayList<Episodes> list=getIntent.getparcelableArrayList("episodeList")
and don't forget to make the model class to parcelable

You can use intents to pass values from one activity to another activity like this:
In your current activity from where you want to pass ArrayList:
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putStringArrayListExtra("key", your_array_list);
startActivity();
And in your Activity where you want to receive the values:
Intent intent = getIntent();
ArrayList arrayList= intent.getStringArrayListExtra("key");

I also had the same problem on my project. I just used SharedPreferences. It's like a local file in your project, but you cannot see it. You simply put the values inside and retrieve them in your 2nd Activity.
For more information: https://developer.android.com/training/data-storage/shared-preferences

Implement Parcelable in your ArrayList model.
Intent intent = new Intent(context, ServiceDetailActivity.class);
intent.putParcelableArrayListExtra("key", (ArrayList<? extends Parcelable>) arrayList);
startActivity(intent);
And get list in another activity
arrayList = getIntent().getParcelableArrayListExtra("key");

Related

Send ArrayList inside ArrayList

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
{}

send Arraylist by Intent

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

Android Java - Passing data between intents but need to save it on main activity

I have an app that for right now, consists of 2 buttons (will later consists of 20+). When I click on a button, it takes me to a new activity that has a list of items I can select. After selecting something and clicking the Back button, it starts a new activity that passes on the item's information (in this case, "orange") and then it assigns the word "orange" to the button that was clicked.
Now when I click on the other button to assign it's information, I lose all of my first button information. What are my options for saving the previous information? Would I have to create an intent for it and keep passing it back and forth between actvities?
At the end, I need to collect all the information that was assigned to both buttons and pass that onto another activity, as this is just the customizing page. Is there a way I can just have the Strings set such that leaving the activity won't delete the String information?
Here's my MainActivity
Bundle extras = getIntent().getExtras();
if (extras != null) {
btnValue = extras.getString("btnValue");
itemValue = extras.getString("itemValue");
}
if (btnValue.equals("btn1")){
btn1.setText(itemValue);
} else if (btnValue.equals("btn2")) {
btn2.setText(itemValue);
}
}
public void onClickBtn1(View v) {
Intent myIntent = new Intent(this, Main2Activity.class);
myIntent.putExtra("btn", "btn1");
startActivity(myIntent);
}
public void onClickBtn2(View v) {
Intent myIntent = new Intent(this, Main2Activity.class);
myIntent.putExtra("btn", "btn2");
startActivity(myIntent);
}
and my 2nd activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
btnValue = extras.getString("btn");
}
listView = (ListView) findViewById(R.id.list);
String[] values = new String[] { "apple", "banana", "orange", "cherry"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
itemPosition = position;
itemPositionString = String.valueOf(itemPosition);
}
});
}
public void onClickBack (View v) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("btnValue", btnValue);
intent.putExtra("itemValue", itemValue);
startActivity(intent);
}
You can use the Android lifecycle to manage the activity's state.
To save the activity state you need to do your work on the method onSaveInstanceState.
onSaveInstanceState(Bundle bundle)
On restoration you either check the bundle the following methods
onRestoreInstanceState(Bundle bundle)
onCreate(Bundle bundle)
You can find more details here:
https://developer.android.com/training/basics/activity-lifecycle/recreating.html
When you use startActivity it creates new activity. So you lose old information. You need to use startActivityForResult from MainActivity while starting second activity and from the second activity you should use setResult
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK, returnIntent);
finish();
And you handle the result in MainActivity with
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
..
..
}
Here, there is an example How to manage `startActivityForResult` on Android?
You basically have 3 choices:
Pass all data in the Intent and return any new/changed data in another Intent using startActivityForResult().
Save the data in a static variable somewhere (globals). All activities can then reference the current data and make changes to it that are then seen by all other activities. This is the quick-and-dirty solution which is suitable for small, trivial or "homework" solutions.
Save the data in a persistent storage (a file or an SQLite database). All activities can read all the current data, display it and make changes. After the BACK button is pressed, the underlying Activity should read the current data from the persistent storage to refresh the views.

Start Activity from RecyclerView.Adapter with bundled Object

I'm using RecyclerView to populate CardViews with my object "Income". Now I need one of the buttons in CardView to start new Activity and send that object to it.
Here's part of my button's onClickListener in Adapter:
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editAt(income);
}
});
public void editAt(Income income){
Intent i = new Intent(context,IncomeAddActivity.class);
Bundle bundle = new Bundle();
// here I want to send that "income" object
i.putExtras(bundle);
startActivity(i);
}
Is there any easy method to do this, or my approach is totally wrong?
You need to make your class Income implements the interface Serializable. Then you can do this:
Bundle bundle = new Bundle();
bundle.putSerializable("object", income);
intent.putExtras(bundle);
startActivity(i);
You can also use Shared Preferences to store and get some data
SharedPreferences.Editor ed = mPrefs.edit();
ed.putInt("view_mode", mCurViewMode);
ed.commit();

Android: Passing an ArrayList between classes

How do I pass an ArrayList between classes? I want to pass an ArrayList from this class/method that extends Activity...
public class OpportunityActivity extends Activity {
public void updateOpportunities(ArrayList<Opportunity> opportunities) {
Intent intent = new Intent(this, OppListActivity.class);
startActivity(intent);
}
...over to OppListActivity class that extends ListActivity where I use this opportunities ArrayList to populate my custom ListView using the elements in the arraylist opportunities:
public class OppListActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
I'd like to pass opportunities arraylist between the two intact. Should I...
- use a bundle (I've tried but can't work out the right syntax, and this seems like overkill/maybe there's a better way?)
- make opportunities public / somehow exposed to both classes
- pass opportunities as a parameter?
Specific syntax (not pseudocode) appreciated.
You can't create an Activity like this:
public void updateOpportunities(ArrayList<Opportunity> opportunities) {
OppListActivity a = new OppListActivity();
}
You should always use an Intent. In the Intent you can add an "extra" with your ArrayList, which you will read later in your ListActivity. Note that you will probably need to make your Opportunity implement Parcelable. There's a lot of info on both of these topics both in StackOverflow and in the official docs.
You need to use intents to start a new activity. And you can actually put serializable objects in your intent's extra data:
public void updateOpportunities(ArrayList<Opportunity> opportunities) {
Intent intent = new Intent(this, OppListActivity.class);
intent.putExtra("opportunities", opportunities);
startActivity(intent);
}
And in your OppListActivity activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
ArrayList<Opportunity> opportunities = intent.getSerializableExtra("opportunities");
}
But you probably need to make sure that Opportunity class extends Serializable.
On way is to use putExtra if you are using an Intent to trigger the next activity. It would look something like this:
ArrayList<String> test_array = new ArrayList<String>();
// do something with test_array
Intent launchNextActivity = new Intent(getApplicationContext(), nextActivity.class);
launchNextActivity.putExtra("array", test_array);
startActivity(launchNextActivity);
And then in the activity you launch, you could use the following to get it:
Intent sender = getIntent();
ArrayList<String> passedInArray = new ArrayList<String>();
passedInArray = sender.getStringArrayExtra("array");
usually you add an extra bundle when starting a new intent when switching to some other activity. e.g
ArrayList<String> theArrayList = new ArrayList<String>();
Intent i = new Intent(this,TheNewActivity.class);
i.putStringArrayListExtra("list",theArrayList);
startActivity(i);
finish();
hiiii..... You can use Bean,with the one ArrayList
e.g
ArrayList<RowItem> aryListbean=new ArrayList<rowItem>(); //your arraylist
RowItem rowItem=new RowItem(); // that is your bean class
now You have to create a class RowItem,that is your Bean,which have getter/setter method
for(....)
{
rowItem.setUserId(); // set method's example
rowItem.setPassword() // set method's exampl
aryListbean.add(rowItem);
}
Now you can use your data in every Activities using getmethod
e.g
getUserId();
getUserPassword();

Categories

Resources