每次我使用编辑文本中的字符串按下搜索按钮时,我想刷新 ListView ,但列表不刷新。
这是我的主要 Activity :
public class MainActivity extends ListActivity implements OnClickListener {
private DataSource datasource;
Button search;
EditText searchEt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (Button) findViewById(R.id.bSearch);
searchEt = (EditText) findViewById(R.id.etTextSearch);
search.setOnClickListener(this);
datasource = new DataSource(this);
datasource.open();
List<Recipe> values = datasource.getAllRecipe(Recipe.l);
// List<Recipe> values = datasource.getAllRecipe();
// use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Recipe> adapter = new ArrayAdapter<Recipe>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayAdapter<Recipe> adapter = (ArrayAdapter<Recipe>) getListAdapter();
Recipe title = null;
switch (v.getId()) {
case R.id.bSearch:
try {
String s = searchEt.getText().toString();
Recipe.l = s;
Log.i("1", Recipe.l + "");
} catch (Exception e) {
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Row Empty or ID not found");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
break;
}
adapter.notifyDataSetChanged();
}
@Override
protected void onResume() {
datasource.open();
super.onResume();
}
@Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
这是我的 DAO 中的方法:
public List<Recipe> getAllRecipe(String l) throws SQLException {
List<Recipe> titles = new ArrayList<Recipe>();
Cursor cursor = database.query(Helper.TABLE_RECIPES, allColumns,
Helper.COLUMN_TAG + "='" + Recipe.l + "'", null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Recipe title = cursorToRecipe(cursor);
titles.add(title);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return titles;
}
private Recipe cursorToRecipe(Cursor cursor) {
Recipe title = new Recipe();
title.setId(cursor.getLong(0));
title.setTitle(cursor.getString(1));
return title;
}
这是我的模型类:
public static String l = "chicken";
我的 onclicklisteners 正在工作,按钮正在工作。我检查了 DDMS 中的日志,变量 l 正在更改。唯一的问题是 ListView 不刷新。
最佳答案
您收到类转换异常,因为您正在将 getAllRecipe() (返回 Recipe 对象的列表)类型转换为 Recipe 对象(不是 Recipe 对象的列表)。尝试将其更改为
title = (List<Recipe>) datasource.getAllRecipe(Recipe.l);
有一个更好的方法可以实现您想要实现的目标,但这应该会让您继续前进。希望这会有所帮助。
关于java - 通知数据集更改();不清爽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21073514/