Reputation: 383
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();
}
}
}
Upvotes: 1
Views: 567
Reputation: 943
To write a query in Android Sqllite requires certain parameters like:
// Queries the user dictionary and returns results mCursor = getContentResolver().query(
URI // The content URI of the words table
mProjection, // The columns to return for each row
mSelectionClause // Selection criteria
mSelectionArgs, // Selection criteria
mSortOrder); // The sort order for the returned rows
For more details read Android Developer's Website: http://developer.android.com/guide/topics/providers/content-provider-basics.html
Upvotes: 0
Reputation: 4147
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.
Upvotes: 1