나는 하나의 테이블 question_table
과 하나 ImageButton
( 뒤로 )가 있습니다. 뒤로를 클릭 한 후 데이터베이스에서 마지막으로 삽입 된 레코드를 가져와야 합니다.
내 행이 다음과 같은 열이 포함되어 : question
, optionA
, optionB
, optionC
, optionD
, 나는 내에서 사용하기위한 데이터가 필요 Activity
. 데이터베이스에 한 가지 방법을 만들었지 만 작동하지 않습니다.
다음은 참조 용 코드입니다.
MySQLiteHelper.java 추출 :
public List<ObjectiveWiseQuestion> getLastInsertQuestion()
{
// long index = 0;
List<ObjectiveWiseQuestion>LocwiseProfileList=new ArrayList<ObjectiveWiseQuestion>();
db = getReadableDatabase();
Cursor cursor = db.query(
"sqlite_sequence",
new String[]{"seq"},
"name = ?",
new String[]{TABLE_QUESTION},
null,
null,
null,
null );
if (cursor.moveToFirst())
{
do {
ObjectiveWiseQuestion owq= new ObjectiveWiseQuestion();
owq.setQuestion(cursor.getString(2));
owq.setOptionA(cursor.getString(3));
owq.setOptionB(cursor.getString(4));
owq.setOptionC(cursor.getString(5));
owq.setOptionD(cursor.getString(6));
owq.setCorrectOption(cursor.getString(7));
LocwiseProfileList.add(owq);
} while(cursor.moveToNext());
db.close();
}
return LocwiseProfileList;
}
OnClickListner
에서 AddQuestionActivity.java
imgBack.setOnClickListener( new View.OnClickListener()
{
@Override
public void onClick(View v)
{
msg();
emptyFormField();
try {
final List<ObjectiveWiseQuestion> LocWiseProfile = db.getLastInsertQuestion();
for (final ObjectiveWiseQuestion cn : LocWiseProfile)
{
db=new MySQLiteHelper(getBaseContext());
db.getWritableDatabase();
txtQuestion.setText(cn.getQuestion());
txtOptionA.setText(cn.getOptionA());
txtOptionB.setText(cn.getOptionB());
txtOptionC.setText(cn.getOptionC());
txtOptionD.setText(cn.getOptionD());
txtCorrectOption.setText(cn.getCorrectOption());
db.close();
}
} catch(Exception e) {
e.printStackTrace();
}
}
});
힌트를주세요.
답변
이 시도:
SELECT *
FROM TABLE
WHERE ID = (SELECT MAX(ID) FROM TABLE);
또는
다음 솔루션을 사용할 수도 있습니다.
SELECT * FROM tablename ORDER BY column DESC LIMIT 1;
답변
정답이 약간 장황하다고 생각합니다.
SELECT * FROM table ORDER BY column DESC LIMIT 1;
답변
테이블에서 마지막 기록을 얻으려면 ..
String selectQuery = "SELECT * FROM " + "sqlite_sequence";
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
답변
다음은 열에서 아무것도 정렬 할 필요없이 단순히 마지막 줄을 반환하는 간단한 예입니다.
"SELECT * FROM TableName ORDER BY rowid DESC LIMIT 1;"
답변
전체 SQL 문자열 대신 SQLiteDatabase 클래스의 메서드 쿼리를 사용하는 것이 더 좋을 것이라고 생각합니다.
Cursor cursor = sqLiteDatabase.query(TABLE, allColluns, null, null, null, null, ID +" DESC", "1");
마지막 두 매개 변수는 ORDER BY 및 LIMIT입니다.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html 에서 자세한 내용을 볼 수 있습니다.
답변
이미 커서가있는 경우 다음과 같이 커서에서 마지막 레코드를 가져올 수 있습니다.
cursor.moveToPosition(cursor.getCount() - 1);
//then use cursor to read values
답변
간단하게 Cursor
moveToLast (); 방법은 마지막 기록으로 이동하는 것을 제공합니다
cursor.moveToLast();
