我有一个ArrayList
,其中的代码由此代码生成并存储:
btSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
members.add(new member (name, id, mail, ccard, address));
Toast.makeText(MemReg_activity.this, "Member Added", Toast.LENGTH_LONG).show();
etname.setText("");
}
});
现在我想通过name
从其他活动中搜索此列表
有没有办法做到这一点 ?
如果没有,除了使用ArrayList
之外还有其他方法可以帮助我做到这一点吗?
会员班
package com.fawzyx.movie_rental_store;
public class Member extends Customer {
String id;
String mail;
String ccard;
String address;
public Member (String name, String id, String mail, String ccard, String address) {
this.name = name;
this.id = id;
this.mail = mail;
this.ccard = ccard;
this.address = address;
}
public String getName()
{
return name;
}
}
答案 0 :(得分:1)
如果member
是唯一的,name
name
的查找方法:
public Member findMemberByName(String name) {
// go through list of members and compare name with given name
for(Member member : members) {
if (member.getname().equals(name)) {
return member; // return member when name found
}
}
return null; // return null when no member with given name could be found
}
如果name
不唯一,则该方法会返回包含所有匹配项的ArrayList
public ArrayList<Member> findMemberByName(String name) {
ArrayList<Member> matches = new ArrayList<Member>();
// go through list of members and compare name with given name
for(Member member : members) {
if (member.getname().equals(name)) {
matches.add(member); // adds matching member to the return list
}
}
return matches; // return the matches, which is empty when no member with the given name was found
}
要在另一个Activity
中执行此操作,您必须将members
传递给此其他活动。见Starting another Activity
答案 1 :(得分:0)
如果您正在搜索一次,请循环播放。如果您将列表一次并多次搜索,则可能需要创建一个单独的哈希映射,其中名称为键,对象列表为值。然后你可以简单地查找键来获得匹配的每个对象。