【发布时间】:2020-01-08 16:37:26
【问题描述】:
问题总结:
简而言之,用户选择一个名称,然后他们尝试连接到服务器。该服务器检查名称是否被占用。如果该名称被使用,它们将被发送到“名称选择”屏幕,并且列表应通过删除当前使用的所有其他名称来更新。我从服务器得到一个String,名称在那个字符串中。我正在尝试使用该字符串从 ArrayList 中删除名称。例如,我的列表有名称 01、名称 02、名称 03、名称 04。它们是我列表中的单个项目。当我从服务器收到一条字符串消息时,例如在一个 String 中,如下所示:“名称 01,名称 02,名称 03”,我希望能够从 ArrayList 中删除这些名称。
我尝试过的:
我创建了一个迭代器来浏览用户可以从中选择的名称列表。例如,我尝试使用单个名称“Name 01”将其从列表中删除,并且有效。我也尝试过使用“Name 01”+“Name 02”,但它不会从列表中删除任何内容。我也尝试过“名称 01,名称 02,名称 03”,但这也没有删除任何内容。我还尝试了 if (s.contains(value)) 和 if (s.startsWith(value)) 在一个字符串中使用长字符串,但它仍然没有删除任何内容。我也看过:Remove multiple elements with multiple indexes from arraylist in java - Java Arraylist remove multiple element by index - Remove multiple items from ArrayList - Remove items from ArrayList with certain value - Remove all elements from an ArrayList that contains string
姓名选择活动:onCreate
// Create the list to populate the spinner
List<String> deviceNameList = new ArrayList<>();
nameList.add("Name 01");
nameList.add("Name 02");
nameList.add("Name 03");
nameList.add("Name 04");
// Array Adapter for creating list
adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, nameList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
nameSpinner.setAdapter(adapter);
nameSpinner.setOnItemSelectedListener(this);
// An Iterator to go through the list and remove any names already taken
// that we get back as one String from server
// This is the Extra Intent from the Main Activity if user has chosen a name already taken
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("namesTaken");
Iterator<String> it = nameList.iterator();
while (it.hasNext() ) {
String s = it.next();
if (s.startsWith(value)) {
it.remove();
}
}
主要活动:在onCreate
// Create test extraIntent with names to see if the list will be updated
// Test button simulates if name is already taken, server will send message to phone
// and send user back to the device name selection screen and only show the devices that are free to select
bTest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String namesTaken = "Horizon 01, Horizon 02, Horizon 03";
myIntent.putExtra("namesTaken", namesTaken);
startActivity(myIntent);
//Clear shared preferences
SharedPreferences settings = context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
//Removes Device Name to be empty ""
settings.edit().remove(NAME).commit();
finish();
}
});
我的期望和实际结果:我希望用户从 ArrayList 中选择一个名称,然后将其发送到 MainActivity。当他们连接到服务器时,我希望能够从服务器获取名称的String,并将用户发送回名称选择屏幕,同时使用String 删除获取的名称并更新列表仅显示 ArrayList 中的可用名称。现在,我只能删除字符串“Name 01”中的一个名称,但不能删除像“Name 01, Name 02, Name 03”这样的长字符串
【问题讨论】:
标签: java android string arraylist