我的 ListView 是从我的数据库中提取的食谱列表。我正在尝试在我的 ListView 中获取单击项目的文本。ListView 通过数据库调用和 cursoradapter 填充。我想使用所选项目的文本在另一个活动中进行另一个数据库调用。这是代码块
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
final String text = ((TextView)v).getText().toString();
recipeid = myDBAdapter.getRecipeID(text);
Intent intent = new Intent(ListAllRecipes.this, DisplayRecipe.class);
intent.putExtra("recipeid", recipeid);
startActivity(intent);
}
});
当我运行我的代码时,我得到
04-22 14:08:37.022: E/AndroidRuntime(25206): FATAL EXCEPTION: main
04-22 14:08:37.022: E/AndroidRuntime(25206): java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.TextView
04-22 14:08:37.022: E/AndroidRuntime(25206): at com.example.ketorecipes.ListAllRecipes$1.onItemClick(ListAllRecipes.java:47)
当我单击 ListView 中的项目时。
这是一大块的活动:
public class ListAllRecipes extends Activity{
private DBAdapter myDBAdapter;
private ListView listView;
private int recipeid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_all);
myDBAdapter = new DBAdapter(this);
myDBAdapter.openToRead();
Cursor c = myDBAdapter.getValues();
listView = (ListView)findViewById(R.id.listView1);
String[] from = new String[] {"_id"};
int[] to = new int[] {R.id.name_entry};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.list_entry, c, from, to);
listView.setAdapter(cursorAdapter);
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
final String text = ((TextView)v).getText().toString();
recipeid = myDBAdapter.getRecipeID(text);
Intent intent = new Intent(ListAllRecipes.this, DisplayRecipe.class);
intent.putExtra("recipeid", recipeid);
startActivity(intent);
}
});
}
}