I have a ListView, by clicking which opens the details.

int selectedId; listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { startActivity(new Intent(getContext(), BookDetails.class)); selectedId = bookingHistoryObjects.get(position).getId(); } }); 

Base:

 public List<BookDetailsObjects> getAllBookingDetailsObjects(int id) { SQLiteDatabase db = this.getReadableDatabase(); BookDetailsObjects bookDetailsObjects = new BookDetailsObjects(); List<BookDetailsObjects> bookList = new ArrayList<>(); JSONObject jsonObject = null; Cursor cursor = db.query(BOOKING.TABLE_BOOKING, new String[]{ BOOKING.KEY_ID, BOOKING.KEY_DETAILS}, BOOKING.KEY_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null); if (cursor != null) { cursor.moveToFirst(); try { jsonObject = new JSONObject(cursor.getString(1)); bookDetailsObjects.setPNR(jsonObject.getString("PNR")); bookDetailsObjects.setDate(jsonObject.getString("DATE")); bookDetailsObjects.setDepartDate(jsonObject.getString("DEPART_DATE")); bookDetailsObjects.setFromTo(jsonObject.getString("FROM_TO_CODE")); bookDetailsObjects.setValidUntil(jsonObject.getString("VALID_UNTIL")); bookDetailsObjects.setTotalPrice(jsonObject.getString("TOTAL_PRICE")); bookDetailsObjects.setRoute(jsonObject.getString("ROUTE")); bookDetailsObjects.setFlightClass(jsonObject.getString("CLASS")); bookList.add(bookDetailsObjects); } catch (JSONException e) { e.printStackTrace(); } } return bookList; } 

Details:

  DBHelper dbHelper = new DBHelper(BookDetails.this); allBookItems = dbHelper.getAllBookingDetailsObjects(BookingHistoryFragment.selectedId); 

But I still need to go to the details from another page after pressing the button, and assign the last ID to selectedId, which I don’t have ...

So, how do I get the latest ID?

    2 answers 2

    Decided, finally. Can someone help!

     public long getLastInsertId() { long index = 0; SQLiteDatabase sdb = getReadableDatabase(); Cursor cursor = sdb.query( "sqlite_sequence", new String[]{"seq"}, "name = ?", new String[]{BOOKING.TABLE_BOOKING}, null, null, null, null ); if (cursor.moveToFirst()) { index = cursor.getLong(cursor.getColumnIndex("seq")); } cursor.close(); return index; } 
    • Something is not very clear how the last ID is obtained here - pavlofff

    If the ID field is auto-increment then you can run a query like this: "SELECT last_insert_rowid () ...."