[英]How can I share array lists between activities in android studio?
I am trying to build an android app and I have a problem.我正在尝试构建一个 android 应用程序,但我遇到了问题。 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.
首先,我编写了一个方法来访问您的手机 memory 并导入一个 excel 文件,该文件包含两列,其值代表时间和心率。 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).我从 excel 读取数据并将其存储到数组列表中,该数组列表是
DataFitbit
类型( DataFitbit
是我制作的 class 包含两个参数,如 ZBF57C906FA7D2BB66D07372E41585D9 文件,时间和时间) 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.现在我想在其他活动中使用这些数据创建一个图表,但我认为为了在这两个活动之间共享我的 arraylist 而编写的代码不起作用。 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
.您没有传递基本的
String
ArrayList
,而是为 ArrayList 使用自定义数据类型ArrayList
。
For that to work, you need to do something as mentioned here:为此,您需要执行此处提到的操作:
1. Now, pass it in intent as: 1. 现在,将其传递为:
Bundle bundle = new Bundle();
bundle.putSerializable("arraylist",(Serializable) dateFitbit);
intent.putExtra("Bundle",bundle);
startActivity(intent);
2. In the receiving activity, get it as: 2.在接收活动中,获取为:
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.这将保留您的自定义 ArrayList model,然后您可以根据需要使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.