简体   繁体   中英

How can I share array lists between activities in android studio?

I am trying to build an android app and I have a problem. First of all, I wrote a method which access your phone memory and imports an excel file which contains two columns with values that represents time and heart rate. I read the data from excel and stored it into an array list and this array list it is DataFitbit type ( DataFitbit is a class I made which contains two parameters, like excel file, time and heart rate). Now I want to create a chart with this data in other activity, but I think the code wrote in order to share my arraylist between those two activities doesn't work. I don't have any error, but when I push the button that create another activity where I want to create the chart, the app crashes.

This is the code wrote in order to share the array list between activities:

Bundle bundle = getIntent().getExtras();
ArrayList<DateFitbit> dateFitbit = (ArrayList<DateFitbit>) bundle.get("arraylist");
ListView listView = findViewById(R.id.listView);
ArrayAdapter<DateFitbit> items = new ArrayAdapter<DateFitbit>(this,android.R.layout.simple_list_item_1);
listView.setAdapter(items);

The code that opens a new activity which will contain charts is:

public void openChartActivity(){
    Intent intent = new Intent(this, ChartActivity.class);
    intent.putExtra("arraylist",dateFitbit);
    startActivity(intent);
}

In the very first time I tried to see my data into a list view, to be sure that the share has been done, but as I said, something doesn't work well.

Do you have any suggestions for me?

You're not passing a basic String ArrayList , instead you're using a custom data type object for ArrayList .

For that to work, you need to do something as mentioned here:

1. Now, pass it in intent as:

Bundle bundle = new Bundle();
bundle.putSerializable("arraylist",(Serializable) dateFitbit);
intent.putExtra("Bundle",bundle);
startActivity(intent);


2. In the receiving activity, get it as:

Intent intent = getIntent();
Bundle bundle = intent.getBundleExtra("Bundle");
ArrayList<DataFitBit> dateFitbit= (ArrayList<DataFitBit>) bundle.getSerializable("arraylist");

This will preserve your custom ArrayList model and you can then utilize it as you prefer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM