Instead of using direct query to db im using contentResolver but it returns null. And i dont know do i need to add some code or there is a mistake in mine.
private void displayDatabaseInfo() {
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
PetEntry._ID,
PetEntry.COLUMN_PET_NAME,
PetEntry.COLUMN_PET_BREED,
PetEntry.COLUMN_PET_GENDER,
PetEntry.COLUMN_PET_WEIGHT };
// Perform a query on the provider using the ContentResolver.
// Use the {#link PetEntry#CONTENT_URI} to access the pet data.
Cursor cursor = getContentResolver().query(
PetEntry.CONTENT_URI, // The content URI of the words table
projection, // The columns to return for each row
null, // Selection criteria
null, // Selection criteria
null); // The sort order for the returned rows
Log.v(LOG_TAG, "Проверка курсора " + cursor);
TextView displayView = (TextView) findViewById(R.id.text_view_pet);
if (cursor != null){
try {
// Create a header in the Text View that looks like this:
//
// The pets table contains <number of rows in Cursor> pets.
// _id - name - breed - gender - weight
//
// In the while loop below, iterate through the rows of the cursor and display
// the information from each column in this order.
displayView.setText("The pets table contains " + cursor.getCount() + " pets.\n\n");
displayView.append(PetEntry._ID + " - " +
PetEntry.COLUMN_PET_NAME + " - " +
PetEntry.COLUMN_PET_BREED + " - " +
PetEntry.COLUMN_PET_GENDER + " - " +
PetEntry.COLUMN_PET_WEIGHT + "\n");
// Figure out the index of each column
int idColumnIndex = cursor.getColumnIndex(PetEntry._ID);
int nameColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_NAME);
int breedColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_BREED);
int genderColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_GENDER);
int weightColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_WEIGHT);
// Iterate through all the returned rows in the cursor
while (cursor.moveToNext()) {
// Use that index to extract the String or Int value of the word
// at the current row the cursor is on.
int currentID = cursor.getInt(idColumnIndex);
String currentName = cursor.getString(nameColumnIndex);
String currentBreed = cursor.getString(breedColumnIndex);
int currentGender = cursor.getInt(genderColumnIndex);
int currentWeight = cursor.getInt(weightColumnIndex);
// Display the values from each column of the current row in the cursor in the TextView
displayView.append(("\n" + currentID + " - " +
currentName + " - " +
currentBreed + " - " +
currentGender + " - " +
currentWeight));
}
} finally {
// Always close the cursor when you're done reading from it. This releases all its
// resources and makes it invalid.
cursor.close();
}
}
}
Before that i got an error null exception. After added if/else statement exceptions dissapeared but anyway it doesnt work and returns null
Problem was in ContentProvider. I have changed code and now it works.
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// Get readable database
SQLiteDatabase database = mDbHelper.getReadableDatabase();
// This cursor will hold the result of the query
Cursor cursor;
// Figure out if the URI matcher can match the URI to a specific code
int match = sUriMatcher.match(uri);
switch (match) {
case PETS:
// For the PETS code, query the pets table directly with the given
// projection, selection, selection arguments, and sort order. The cursor
// could contain multiple rows of the pets table.
cursor = database.query(PetEntry.TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
break;
case PET_ID:
// For the PET_ID code, extract out the ID from the URI.
// For an example URI such as "content://com.example.android.pets/pets/3",
// the selection will be "_id=?" and the selection argument will be a
// String array containing the actual ID of 3 in this case.
//
// For every "?" in the selection, we need to have an element in the selection
// arguments that will fill in the "?". Since we have 1 question mark in the
// selection, we have 1 String in the selection arguments' String array.
selection = PetEntry._ID + "=?";
selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };
// This will perform a query on the pets table where the _id equals 3 to return a
// Cursor containing that row of the table.
cursor = database.query(PetEntry.TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Cannot query unknown URI " + uri);
}
return cursor;
}
Related
so i recently learn to write a code in android using sqlite and i try to select data from sqlite but this error occur
ive tried some suggestion from the internet and read my book but i didnt solve my problem
public Penyakit getPenyakit1(String namaGejal){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT idPen FROM " + TABLE_CONTACTS + " WHERE " +
namapen + " =\"" + namaGejal + "\"";
Cursor cursor = db.rawQuery(query,null);
Penyakit penyakit = new Penyakit();
if(cursor.moveToFirst()){
cursor.moveToFirst();
penyakit.set_nomber(Integer.parseInt(cursor.getColumnName(0)));
penyakit.set_namaPen(cursor.getColumnName(1));
penyakit.set_idPenyakit(Integer.parseInt(cursor.getColumnName(2)));
penyakit.set_namGej(cursor.getColumnName(3));
penyakit.set_idGejala(Integer.parseInt(cursor.getColumnName(4)));
cursor.close();
} else {
penyakit=null;
}
return penyakit;
}
this is logcat
Process: com.example.lordbramasta.pakar, PID: 18914
java.lang.NumberFormatException: For input string: "idPen"
at java.lang.Integer.parseInt(Integer.java:615)
at java.lang.Integer.parseInt(Integer.java:650)
at com.example.lordbramasta.pakar.DBAdapter.getPenyakit1(DBAdapter.java:79)
i expected the value of idPen get selected , thank you
Your problem is this line:
penyakit.set_nomber(Integer.parseInt(cursor.getColumnName(0)));
cursor.getColumnName(0) returns idPen as this is the name of the only column returned by your query:
SELECT idPen FROM ....
and your code is trying to cast the string "idPen" to an integer.
So getColumnName() returns the name of the column at a specified index and not the value of the column.
You should do
penyakit.set_nomber(Integer.parseInt(cursor.getString(0)));
or if the data type of the column idPen is INTEGER then:
penyakit.set_nomber(cursor.getInt(0));
Also don't try to get any other columns because your query returns only 1.
Note: remove that cursor.moveToFirst(); inside the if block because it is already executed.
Probably you need to use a ' instead of ". So, change the query to the following:
String query = "SELECT idPen FROM " + TABLE_CONTACTS + " WHERE " +
namapen + " =\'" + namaGejal + "\'";
I'm suggesting you to use SQLiteDatabase.query() instead rawQuery like this:
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
"idPen"
};
// Filter results WHERE "namapen" = 'namaGejal'
String selection = "namapen" + " = ?";
String[] selectionArgs = { namaGejal };
// How you want the results sorted in the resulting Cursor
String sortOrder = null; // null for default order
Cursor cursor = db.query(
TABLE_CONTACTS, // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
// do something with the cursor
Please take a look Read information from a database
If you want to get all columns data from your TABLE_CONTACTS use SELECT * FROM
I have an SQLite Database in my android application with the following structure:
public void onCreate(SQLiteDatabase db) {
String CREATE_LISTS_TABLE = "CREATE TABLE " + TABLE_LISTS +
"("+
_ID + " INTEGER PRIMARY KEY , " +
NOTE + " TEXT" +
")";
db.execSQL(CREATE_LISTS_TABLE);
}
And this works, in that I can insert data into it without a problem. However I need to store the notes inside an array. I currently have the following query:
public List<String> getAllNotes() {
List<String> notes = new ArrayList<>();
String GET_ALL_NOTES = "SELECT * FROM " + TABLE_LISTS;
SQLiteDatabase db = getReadableDatabase();
if(db!=null)
{
Cursor cursor = db.rawQuery(GET_ALL_NOTES, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
notes.add(String.valueOf(cursor.getInt(cursor.getColumnIndex("notes"))));
cursor.moveToNext();
}
cursor.close();
}
db.close();
return notes;
}
However, this gives the following error:
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
I was wondering how to fix this, I have read the android developer stuff but I can't seem to get anything to work.
Thanks in advance
Check the value of "NOTE", and use it in:
notes.add(String.valueOf(cursor.getInt(cursor.getColumnIndex(NOTE))));
I think a best way to make the call should be something like this:
// Check the cursor
if(cursor != null) {
if (cursor.moveToFirst()) {
// Variables to be used
String note;
// Col position
int colNote = cursor.getColumnIndex(NOTE);
do {
// Get the information
note = cursor.getString(colNote);
// Add the note
notes.add(note);
} while (cursor.moveToNext());
}
// Close the cursor
cursor.close();
}
Because you are fetching only integer and string from database, instead of using ArrayList , you can try using HashMap. So you can get the value by just giving the key. Below simple code will work for ArrayList too with minor changes..
Try this
HashMap<Integer,String> notes = new HashMap<Integer,String>() ;
Cursor cursor = db.rawQuery(GET_ALL_NOTES, null);
while (cursor.moveToNext())
{
int i = cursor.getInt(0);
String s = cursor.getString(1);
notes.put (i,s) ;
}
cursor.close();
I have created a SpinnerActivity, which looks like following:
http://img4.fotos-hochladen.net/uploads/bildschirmfotovse8j4po1t.png
Now for example if I select 'Landschaft' (in English: landscape) I want to search in the DatabaseHandler.java for a location which is in the category 'Landschaft' (landscape)
Therefore I have written the following method in DatabaseHandler.java:
In this method, I have just written Kategorie = Landscape.
However I want, that the selected SpinnerArray (Landschaft, Brücken...etc.) in my Spinner would be inserted in my DatabaseHandler instead of "Landschaft", how can I do that?
public List<Position> getAllPositionsWithCategory() {
List<Position> positionList = new ArrayList<Position>();
String selectQuery = "SELECT * FROM " + TABLE_POSITIONS
+ " WHERE Kategorie = 'Landschaft'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Position position = new Position();
position.setID(Integer.parseInt(cursor.getString(0)));
position.setName(cursor.getString(1));
position.setKategorie(cursor.getString(2));
position.setLaenge(cursor.getFloat(3));
position.setBreite(cursor.getFloat(4));
// Adding position to list
positionList.add(position);
} while (cursor.moveToNext());
}
}
Simply replace the the fixed String with ? in your query, and pass the value to be inserted in the second argument of db.rawQuery().
The following might work for your case:
String selectQuery = "SELECT * FROM " + TABLE_POSITIONS
+ " WHERE Kategorie = ?";
// ...
Cursor cursor = db.rawQuery(selectQuery, new String[] { "Landschaft" });
You can now replace your String "Landschaft" with a variable of your choice.
See also: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#rawQuery(java.lang.String,%20java.lang.String[])
I have a DB helper that does this function:
public Cursor getCourseNames() throws SQLException {
mDb = mDbHelper.getReadableDatabase();
return mDb.query("Course",null, COURSE_ROWID, null, null, null, null, null);
}
The table it is pulling from looks like this:
private static final String COURSE_ID = "CourseID";
private static final String COURSE_NAME = "Name";
private static final String COURSE_CODE = "CourseCode";
private static final String COURSE_ROWID = "_id";
private static final String COURSE_CREATE =
"create table " +
"Course" + " ( " +
COURSE_ROWID + " integer primary key autoincrement, " +
COURSE_ID + "integer not null," +
COURSE_NAME + "text not null, " +
COURSE_CODE + "text not null" + ");";
In my main activity I try this and get a null pointer...
public void buildCoursetoChapterList(){
Cursor cursor = dbHelper.getCourseNames();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(MainActivity.this, android.R.layout.simple_list_item_1, cursor, null, null);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
Anyone have an idea what my problem is?
I put data into the db earlier on:
if(dbHelper.checkCourseForData() !=null)
{
setContentView(R.layout.classlist);
}
else
{
dbHelper.addFirstClassToDb(course_code, name, course_id);
Log.d+i("Course added to DB", course_code + " " + name + " " + course_id);
}
tried this and still nothing, I want to select all the Name values within Course.
No clue... losing hope.
public Cursor checkCourseForData() throws SQLException {
String[] values = {COURSE_NAME};
Cursor mCursor = mDb.query("Course",values,COURSE_ROWID + "=" + "Name", null, null, null, null, null);
if (mCursor != null) { mCursor.moveToFirst(); }
return mCursor;
}
It should be this
public Cursor getCourseNames() throws SQLException {
String[] values = {COURSE_NAME};
mDb = mDbHelper.getReadableDatabase();
return mDb.query("Course",values,COURSE_ROWID, null, null, null, null, null);
}
Explanation :
the medthod in the api has been defined as
public Cursor query (String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having, String orderBy)
So you need to pass the strings accordingly.
User my example as a reference it works for me
private String name;
private String Events_Table = "events";
private String[] Columns = {"_id", "Name", "Date", "Time_Slot", "Venue", "Details", "EHName", "EHNumber"} ;
private String WhereClause = Columns[1]+"=?" ;
Cursor cursor = db.query(Events_Table, Columns, WhereClause, new String[] {name}, null, null, null);
Consider Reading this
Parameters
table The table name to compile the query against.
columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
This is a simple one! yet, I am missing something. Please help me out.
Here, I am trying to fetch values by id, but not able to do so. It is returning same values even after changing id's value.
db = openOrCreateDatabase("DBSOURCE", 0, null);
Cursor cursorc = db.rawQuery("SELECT * FROM LIST WHERE ID="+id+"", null);
cursorc.moveToFirst();
int NameID = cursorc.getColumnIndex("Name");
int mobilenumberID = cursorc.getColumnIndex("MoblieNumber");
edName.setText(cursorc.getString(NameID));
edMobNum.setText(cursorc.getString(mobilenumberID));
cursorc.close();
db.close();
1-
or better to use parametrized statement
String query = "SELECT COUNT(*) FROM " + tableName + " WHERE columnName = ?";
cursor = db.rawQuery(query, new String[] {comment});
2 - use if with conditon c.moveToFirst() or c.getCount() >0 or (!c.isAfterLast())
if (c.moveToFirst()){
do{
//if you not need the loop you can remove that
id = c.getInt(c.getColumnIndex("_id"));
}
while(cursor.moveToNext());
}c.close();
Is the id column title actually "ID"? Or is that a variable that is set to "_id" (the usual column name for the primary key in an Android database)?
If the latter, your query is not right, because you are using "ID" as the literal column name. Try changing it to this:
Cursor cursorc = db.rawQuery("SELECT * FROM LIST WHERE " + ID + " = " + id, null);
or even this:
Cursor cursorc = db.rawQuery("SELECT * FROM LIST WHERE _id = " + id, null);
try using
Cursor cursorc = db.rawQuery("select * from list where ID = ?", new String[] {id+""});
try with this way
Suppose long id=5;
String[] col=new String[]{KEY_ROWID,KEY_NAME,KEY_ADDRESS}; // your column which data u want to retrive if id is same
Cursor c=db.query(DATABASE_TABLE, col, KEY_ROWID+"="+id,null, null, null, null);
if(c!=null){
c.moveToFirst();
// get data here which u want accroding to ur requirement
}
try this
Cursor cursorc = db.rawQuery("SELECT * FROM LIST WHERE ID='"+id+"'", null);