如何从 sqlite 数据库中获取 ID 值 (android studio java)

how to get ID Value from sqlite database (android studio java)

当我尝试从列表视图中单击某个名称时,我希望它 return 来自其名称的 ID(在 Toast 文本中),但无论我在列表视图中单击什么名称,我总是得到结果“0” ,你能帮我修复我的代码吗?,谢谢

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

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");
}

试试这个:

Cursor getNoteId = myDB.rawQuery("select id from notepadData where notepad like + "'" + currentNote + "'", null);

编辑:
等等...现在我注意到你 return...
getColumnIndex() return 你是某列的索引,你的 id 列总是 0 并且不会改变。 您使用两列创建 table:id(索引 0)和 notepad(索引 1)
您应该使用 cursor.getInt(0) 并在调用之前使用 cursor.moveToFirst()
这样做:

    if (getNoteId != null && getNoteId.moveToFirst() {
       return getNoteId.getInt(0)
    } else {
       return null;  // because you have to return something
    }