Refer the image
我想将favourite_city的元素与选项进行匹配,如果找到匹配项,则将favourite_city列表设置为具有其自身内容的选项中的最高位置。
第一个ArrayList:
favourite_city = [“海得拉巴”,“班加罗尔”]
第二个ArrayList:
options = [“ Nashik”,“海得拉巴”,“孟买”,“班加罗尔”,“钦奈”,“浦那”]
结果:
options = [“海得拉巴”,“班加罗尔”,“纳西克”,“海得拉巴”,“孟买”,“班加罗尔”,“钦奈”,“浦那”]
DocumentReference docRef5 = FirebaseFirestore.getInstance().collection("admin").document("users_profile").collection("dynamic_profile").document("city");
docRef5.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null) {
//-----------code for loading array item from firebase to spinner view-----------------
final List<String> group = (List<String>) document.get("favourite_city");
Log.d(TAG, "favourite city list data: " + group);
final List<String> group1 = (List<String>) document.get("options");
Log.d(TAG, "options list data: " + group1);
cityAdapter = new ArrayAdapter<String>(AdminSetting.this, android.R.layout.simple_spinner_item, group1);
cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
citySpinner.setAdapter(cityAdapter);
StringBuilder str = new StringBuilder();
for (int i = 0; i < group.size(); i++) {
if (i >= 0)
str = str.append(group.get(i));
String searchedItem = str.toString();
Log.d(TAG, "result " + searchedItem);
int itemPosition = cityAdapter.getPosition(searchedItem);
for(int j=0;j<=i;j++) {
if (itemPosition == -1) {
String message = searchedItem + " : Item not found.";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
} else {
String message = searchedItem + " : Item found and selected.";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
citySpinner.setSelection(itemPosition);
}
}
Log.d(TAG, "after appending " + str);
}
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
答案 0 :(得分:0)
首先您的问题不清楚
如果要合并两个arraylist,则需要使用以下代码
favourite_city.addAll(options) // or Either way
如果要查找匹配项,则需要执行以下操作
public String getUserId(ArrayList<User> newUsers, ArrayList<User> oldUsers, String email) {
String userId = null;
for (User user1 : newUsers) {
if (user1.email.equals(email)) {
userId = user1.uid;
break;
}
}
if(userId == null){
for (User user2 : oldUsers) {
if (user2.email.equals(email)) {
userId = user2.uid;
break;
}
}
}
return userId;
}
答案 1 :(得分:0)
为了将收藏夹城市放在第一位,您需要知道它们是否包含在城市列表中。
以下面的代码为例:
ArrayList<String> favourites = new ArrayList<>(Arrays.asList("city1", "city2"));
ArrayList<String> cities = new ArrayList<>(Arrays.asList("city3", "city4", "city1", "city2"));
for (String favCity : favourites) {
if (cities.contains(favCity)) {
cities.add(favourites.indexOf(favCity), favCity);
}
}
System.out.println(cities);
这将打印以下内容:
[city1,city2,city3,city4,city1,city2]
如果要删除重复的收藏夹城市以仅将其保留在第一位,则应在添加到列表中之前添加此行。
cities.remove(favCity);
它将返回:
[city1,city2,city3,city4]