我一直在使用Android Studio自学Java / XML,并希望得到一些帮助。我正在尝试创建一个购物清单应用程序,我遇到了在数组中命名字符串数组的问题。我设置了一个ArrayList,但我想用字符串数组填充ArrayList。当我尝试添加字符串输入(来自用户)时,我收到一条错误消息:
列表中的add(java.lang.String [])无法应用
to(java.lang.String)
这是我的代码:
public class ShoppingLists extends AppCompatActivity {
/* Create ArrayList (from List) and Adapter for the ListView */
List<String[]> shoppingLists = null;
ArrayAdapter<String> adapter = null;
ListView lv = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_lists);
/* Create main array */
shoppingLists = new ArrayList<>();
/* Set view style with adapter */
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, shoppingLists);
lv = (ListView) findViewById(R.id.shoppingListView);
lv.setAdapter(adapter);
}
/* Create a menu. */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.shopping_menu, menu);
return true;
}
/* Create actions for menu button presses */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
/* Determine which menu button is pressed */
switch (item.getItemId()) {
case R.id.action_add:
/* Create an alert dialog for user input */
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.add_list));
final EditText input= new EditText(this);
builder.setView(input);
/* If 'OK' is pressed, enter user input as new object into shoppingLists array */
builder.setPositiveButton(getString(R.string.ok_button), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/* Convert user input to string and add it to list */
shoppingLists.add(input.getText().toString());
/* Update adapter with new object to make visible */
lv.setAdapter(adapter);
}
});
builder.setNegativeButton(getString(R.string.cancel_button), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/* Exit dialog box without adding new object */
dialog.cancel();
}
});
builder.show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
此处的错误标有:
shoppingLists.add(input.getText().toString());
我有一种感觉,我错过了一些简单的东西,但我无法理解。
预先感谢您的协助!
答案 0 :(得分:1)
List<String[]> shoppingLists = null;
它应该是
List<String> shoppingLists = null;
答案 1 :(得分:1)
有两种解决方案
1 - 将List<String[]> shoppingLists = null;
更改为List<String> shoppingLists = null;
2 - 首先将输入文本添加到字符串数组中,然后将该字符串数组添加到列表中,如下所示:String[] strArray = {input.getText().toString()};
shoppingLists.add(strArray);