我已经尝试了很多方法和建议,但是我的代码却没有正确执行。这是我所做的。需要添加什么代码,以便在添加新项目之后,该项目显示在列表中?
这里是上下文:
在操作栏中,有一个“添加项目”按钮。对话框打开,在对话框的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????
}
}
}
最佳答案
更新数据后,直接使用adapter.notifyDataSetChanged();
。那应该足够了。您也可以在更新模型数据后将notifyDataSetChanged();
放在适配器本身中。
顺便说一句。我在您的代码中看不到列表更新。当然,您必须在调用notifyDataSetChanged();
之前更新列表的模型数据。
关于android - 在将新项插入MySQL后刷新ListView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11178749/