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

问题描述 投票:0回答:1

当我试图从列表视图中点击某个名字时,我想让它从名字中返回ID(在Toast Text中),但无论我在列表视图中点击哪个名字,我总是得到 "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");
}
java android string int return-value
1个回答
1
投票

试试这个。

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

编辑: 等等... ...现在我注意到了你返回的内容... ... getColumnIndex() 返回某列的索引,其中你的 id 你创建的表有两列。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
    }
© www.soinside.com 2019 - 2024. All rights reserved.