问题描述
我的ListView是从我的数据库中提取的配方列表.我正在尝试在ListView中获取单击项的文本.通过数据库调用和游标适配器填充ListView.我想使用所选项目的文本在另一个活动中进行另一个数据库调用.这是代码块
My ListView is a list of recipes pulled from my database. I am trying to get the text of a clicked item in my ListView. The ListView is populated through a database call and a cursoradapter. I want to use the text of the selected item to make another database call in another activity. Here is the code chunk
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中单击一个项目时.
when I click on an item in the ListView.
以下是该活动的一个块:
Here is the Activity in one chunk:
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);
}
});
}
}
推荐答案
您将_id与R.id.name_entry关联,因此您的列表由_id的值组成.
You associate _id with R.id.name_entry, so your list consists of whatever the values of _id are.
String[] from = new String[] {"_id"};
int[] to = new int[] {R.id.name_entry};
如果是这样,您可以通过
If that is so you can get the name which is _id by
Cursor c = cursorAdapter.getCursor();
String text = c.getString(c.getColumnIndex("_id"));
这篇关于从单击的列表视图项中获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!