I am trying to write a query for retrieving data from SQLite database. I wanted to print the result of a query in a text box. So I used a getint() method for the cursor. Below is my code. It does not start in my Android emulator. Is it the correct way to write the query? It is showing no errors.
import android.app.Activity;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.*;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class SQLDemo1Activity extends Activity {
private SQLiteDatabase db;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
db= SQLiteDatabase.openDatabase(
"/data/data/cis493.sqldatabases/databases/multilinguialdatabase.sqlite",
null,
SQLiteDatabase.CREATE_IF_NECESSARY);
db.beginTransaction();
Cursor cursor = db.query(
"colors" /* table */,
new String[] { "ID" } /* columns */,
"English = ?" /* where or selection */,
new String[] { "green" } /* selectionArgs i.e. value to replace ? */,
null /* groupBy */,
null /* having */,
null /* orderBy */
);
int id = cursor.getInt(0);
TextView met = (TextView) findViewById(R.id.t1);
met.setText(id);
db.endTransaction();
db.close();
}
catch(SQLiteException e) {
Toast.makeText(this, e.getMessage(), 1).show();
}
}
}
You need to put cursor.moveToNext() or cursor.moveToFirst() before trying to get the int with getInt(). Put it in an if statement as there may be no results in the cursor.