如何使用if语句putextra arraylist <object>并在其他活动中显示它

时间:2018-01-22 07:36:13

标签: java android arraylist

Activiy 1

List<Goods> goodsList = new ArrayList<>();
goodsList = getAllData();
Goods goods = new goods();
intent.putExtra("listbarang", (Serializable) goodsList);

function getAllData()是我在我的数据库中显示所有数据的函数,顺便说一下,我用RecyclerView显示它。

活动2

goodsList = (List<Goods>) getIntent().getSerializableExtra("listbarang");

我是如何获得ArrayList

我想要的只是在if语句中添加具有特定条件的ArrayList。例如,我想只显示库存超过0的商品。

我已经成功存储了ArrayList。但是我希望获得该条件的具体数据,可能使用循环或其他东西。

3 个答案:

答案 0 :(得分:1)

我对你的问题不太了解,我认为你可能需要通过列表中的标准。像这样:

intent.putExtra("listbarang", goodsList);
// Criteria for at least one item in the list
intent.putExtra("criteria", 1);

然后处理额外的:

int criteria;

Intent intent = getIntent();
goodsList = (List<Goods>) intent.getSerializableExtra("listbarang");
criteria = intent.getIntExtra("criteria", 0);

// do something based on criteria
for(Goods good: goodsList) {
  if(good.getStock >= criteria) {
    // process the good.
  }
}

答案 1 :(得分:0)

您可以从Parcelable实现Goods类,并使用Bundle.putParcelableArrayList存储列表数据。

答案 2 :(得分:0)

在活动之间传递arrayList,将它们分段并存储在sharedPreferences中的解决方案。

Passing arrayList of Object type from One Activity to another activity.

This solution will also used for passing from one fragment to another fragment

or fragment to activity or activity to fragment.

And this also helps to store arrayList of object type in sharedPreferences.

First added this dependency in build.gradle(app) file


compile 'com.google.code.gson:gson:2.4'


for e.g.:

//first Activity
ArrayList<Goods> list=new ArrayList<>();
Gson gson=new Gson();
String goodList=gson.toJson(list);
Intent intent=new Intent(this,SecondActivity.class);
intent.putString("goods",goodList);
startActivity();


//Second Activity
Gson gson=new Gson();
String goodList=getIntent().getString("goods");
Type type=new TypeToken<ArrayList<Goods>>(){}.getType();
List<Goods> list = new gson.fromJson(goodList,type);

我希望这个解决方案可以帮到你。 感谢