[英]how to get ID Value from sqlite database (android studio java)
when i try to click some name from listview, i want it to return the ID from its name(in Toast Text), but i always getting result "0" wherever i click a name in listview, can you help me fix my code?, thanks当我尝试从列表视图中单击某个名称时,我希望它从其名称中返回 ID(在 Toast 文本中),但是无论我在列表视图中单击名称时,我总是得到结果“0”,你能帮我修复我的代码吗? , 谢谢
MainActivity.java MainActivity.java
public void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
public void toastMessageInt(int message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
public void refreshPage() {
listView = findViewById(R.id.listView);
ArrayList<String> arrayList = new ArrayList<>();
Cursor getView = myDB.showListView();
while (getView.moveToNext()) {
arrayList.add(getView.getString(1));
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(listAdapter);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = parent.getItemAtPosition(position).toString();
int data = myDB.GetId(name);
String dataToString = String.valueOf(data);
toastMessage(dataToString); //here always return "0"
}
});
}
DatabaseHelper.java数据库助手.java
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table notepadData(id integer primary key autoincrement, notepad text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists notepadData");
onCreate(db);
}
public int GetId(String currentNote) {
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor getNoteId = myDB.rawQuery("select id from notepadData where notepad = '"+currentNote+"'",null);
return getNoteId.getColumnIndex("id");
}
Try this:尝试这个:
Cursor getNoteId = myDB.rawQuery("select id from notepadData where notepad like + "'" + currentNote + "'", null);
Edit:编辑:
Wait...now I've noticed what you return...等等……现在我注意到了你返回的东西……
getColumnIndex()
returns you index of certain column, where your id
column is always 0 and it won't change. getColumnIndex()
返回某个列的索引,其中您的id
列始终为 0,并且不会更改。 You create table with two columns: id
(index 0) and notepad
(index 1)您创建包含两列的表: id
(索引 0)和notepad
(索引 1)
You should use cursor.getInt(0)
and before that call cursor.moveToFirst()
您应该使用cursor.getInt(0)
并在此之前调用cursor.moveToFirst()
Do it like this:像这样做:
if (getNoteId != null && getNoteId.moveToFirst() {
return getNoteId.getInt(0)
} else {
return null; // because you have to return something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.