我尝试了很多方法和建议,但我的代码并不正确。这是我所做的。需要添加什么代码,以便在添加新项目后,项目显示在列表中?
这是上下文:
在操作栏中,有一个“添加项目”按钮。对话框打开,在对话框的 onclick 中,它将您在单个字段中输入的单词插入数据库(MySQL),关闭对话框,然后......这就是我的麻烦所在......没有.
编辑:我已经尝试过了——yourAdapter.notifyDataSetChanged(); 我根本不知道把它放在哪里或如何使用它,因为它不会改变任何东西。
public class Items extends ListActivity {
List<String> items = null;
String NewItem;
ArrayAdapter<String> adapter;
ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
items = new ArrayList<String>();
new task().execute();
}
// Class that sets up ListView and populates from database on initial Activity Load
class task extends AsyncTask<String, String, Void> {
@Override
protected Void doInBackground(String... params) {
// HttpPost ... etc
// BufferRedReader .. etc
}
protected void onPostExecute(Void v) {
String item;
try {
// JSON Stuff
}
} catch (JSONException e1) {
// Here is where ListView is set up when Activity/page first starts
listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long id) {
Intent i = new Intent(getApplicationContext(), Rate.class);
i.putExtra("name", items.get(arg2));
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
}
});
adapter = new ArrayAdapter<String>(Items.this, R.layout.list, items);
setListAdapter(adapter);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.Add_Item:
final Dialog dialog = new Dialog(Items.this);
dialog.setContentView(R.layout.insert_dialog);
dialog.setTitle("Insert Item");
dialog.setCancelable(true);
dialog.show();
final EditText etInsert = (EditText) dialog
.findViewById(R.id.etInsertItem);
Button bInsert = (Button) dialog.findViewById(R.id.bInsert);
bInsert.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
NewItem = etInsert.getText().toString();
new insertTask().execute();
dialog.dismiss();
}
});
return true;
case R.id.About:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// This Class is the "inserting item" task inside the dialog
class insertTask extends AsyncTask<String, String, Void> {
@Override
protected Void doInBackground(String... params) {
try {
// HttpPost Stuff ... running insert Script to Database here
}
}
protected void onPostExecute(Void v) {
// Add ListView Refresh Here????
}
}
}