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
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");
}
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.
You create table with two columns: id
(index 0) and notepad
(index 1)
You should use cursor.getInt(0)
and before that call cursor.moveToFirst()
Do it like this:
if (getNoteId != null && getNoteId.moveToFirst() {
return getNoteId.getInt(0)
} else {
return null; // because you have to return something
}