Cursor always returns null - SQLite - android

I tried this query and the cursor alway return to NULL, in the table "members" exist 1 record, Thank you.
sql = "SELECT nick, pass FROM miembros LIMIT 1";
cursor = write.rawQuery(sql, null);
if (cursor != null){
if(cursor.moveToFirst()) {
nickDB = cursor.getString(0);
passDB = cursor.getString(1);
resp[0] = nickDB;
resp[1] = passDB;
}
// Cierra el cursor
if(!cursor.isClosed()) cursor.close();
}else{
Log.e("CURSOR","CURSOR NULL");
}
return resp;
}

this is working code. compare and try. Change stuff as needed
public void getItem() {
String selectQuery;
SQLiteDatabase db;
String myPath = DATABASE_PATH + DATABASE_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
selectQuery = "SELECT * FROM TABLE";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
cursor.getInt(cursor.getColumnIndex("id"));
while (cursor.moveToNext()) {
cursor.getInt(cursor.getColumnIndex("id"));
}
}
}

Related

Sql query page refresh

Experts,
As-Is
I am having application in which textview is displaying the database table count.Which keep change upon inserting the data in to the database table
And issue is changed data is appearing whenever i closed and reopen again only.
To-Be
Textview should show the count the moment data is inserted in to the table. Like auto refresh something like that. Could you assist.
my code is
String strData1 = "";
Cursor c = dbhndlr.getAllEntries();
if (c!= null) {
if (c.moveToFirst()) {
do {
strData1 += c.getString(0);
} while (c.moveToNext());
}
}
tex.setText(strData1);
String strData2 = "";
Cursor c1 = dbhndlr.getAllEntries1();
if (c1!= null) {
if (c1.moveToFirst()) {
do {
strData2 += c1.getString(0);
} while (c1.moveToNext());
}
}
tex1.setText(strData2);
DB
public Cursor getAllEntries(){
String selectQuery = "SELECT count (*) FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery(selectQuery, null);
return cur;
}
public Cursor getAllEntries1(){
String selectQuery = "SELECT count (*) FROM " + TABLE_LABELS2;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur1 = db.rawQuery(selectQuery, null);
return cur1;
}
public List<String> getAllLabels1(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT count (*) FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor1 = db.rawQuery(selectQuery, null);
final ArrayList<String> row1 = new ArrayList<String>();
// looping through all rows and adding to list
if (cursor1.moveToFirst()) {
do {
labels.add(cursor1.getString(1));
} while (cursor1.moveToNext());
}
// closing connection
cursor1.close();
db.close();
// returning lables
return labels;
}

How to prevent app crashed after delete empty database

i had been trying to prevent accidentally click on delete button when the data base is empty. It will crash after click.
Database handler
public void deleteLastMessage(Class a) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_MSG + " = ?",
new String[] { String.valueOf(a.get_message()) });
db.close();
}
public String getLastString() {
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
LastString = cursor.getString(0);
cursor.close();
db.close();
return LastString;
}
Activity
public void deleteMessage(View v) {
LastMessage = new SubliminalClass(db.getLastString());
db.deleteLastMessage(LastMessage);
It work fine when there are data to delete, it crashed when there is no data.
My data is a column of string.
Referred to this Application crashes while reading an empty table in android but to no avail.
I have tried this below but still crashed when there is no data.
public boolean checkdb(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor mCursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
Boolean rowExists;
String nullString="";
if (nullString.equals(getLastString())) //todo change this
// DO SOMETHING WITH CURSOR
rowExists = false;
else
{
// I AM EMPTY
rowExists = true;
}
return rowExists;
}
Anyone can help me solve this?
Try this
Check the table row count is greater than zero then do the delete operation.
//Add in your activity
int rowCount = db.getRowCount();
db.close();
if(rowCount>0)
{
db.deleteLastMessage(LastMessage);
}else{
}
//Add in DBhelperClass
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
public void deleteLastMessage(Class a) {
try{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_MSG + " = ?",
new String[] { String.valueOf(a.get_message()) });
db.close();
} catch (Exception e){
e.printStackTrace();
}
}
You could add try/catch around your delete code.
Also the checkdb function could be like this
public boolean checkdb(){
SQLiteDatabase db = this.getReadableDatabase();
Log.d(TAG,"Got Readable DB")
Cursor mCursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
Boolean rowExists = false;
String nullString="";
if(mCursor != null){
Log.d(TAG,"Cursor is not null")
try{
rowExists = mCursor.getCount() > 0;
Log.d(TAG,"rowExists is " + rowExists);
mCursor.close();
} catch (Exception e){
e.printStackTrace();
}
}
return rowExists;
}

How to get the Max value SQLite Android

Trying to get the maximum id in my TABLE_GOALS
public String getLatestGoal(){
SQLiteDatabase db=dbhandler.getWritableDatabase();
//columns
Cursor cursor=db.query(MyDBHandler.TABLE_GOALS, null, "SELECT MAX("+MyDBHandler.COLUMN_ID+"))", null, null, null, null);
StringBuffer buffer = new StringBuffer();
while(cursor.moveToNext()){
int index1=cursor.getColumnIndex(MyDBHandler.COLUMN_ID);
String max_id=cursor.getString(index1);
buffer.append(max_id);
}
return buffer.toString();
}
I can't get the maximum value and i don't know why. Sorry, newbie here in Android.
public int getMaxid(){
String selectQuery = "SELECT max(id) as id FROM customerentries";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
cursor.moveToFirst();
int maxid = cursor.getInt(cursor.getColumnIndex("id"));
return maxid;
}
public String getLatestGoal(){
SQLiteDatabase db=dbhandler.getWritableDatabase();
Cursor c = db.query(MyDBHandler.TABLE_GOALS, new String[]{"MAX("+MyDBHandler.COLUMN_ID+")"}, null, null, null, null, null);
if(c.getCount()>0){
c.moveToFirst();
String max_id=c.getString(0);
buffer.append(max_id);
}
c.close();
db.close();
return buffer.toString();
}

How to retrieve data from database table by Username?

I'm not too sure whether it's appropriate that using 'username' as my selection to retrieve other data instead of using an id. FYI, my username is unique as there will not be any other user having the same username. I'm doing this way because I'm not sure how to use or call the id from the table.
I'm getting this error:
CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
I have a DatabaseAdapter.java with this code:
public Cursor getData(String username){
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cur = db.query(TABLE_PROFILE, COLUMNS_PROFILE, " username=?", new String[]{username}, null, null, null, null );
if (cur != null){
cur.moveToFirst();
}
return cur;
}
With a EditProfileFragment.java:
dbAdapter = new DatabaseAdapter(getActivity());
dbAdapter = dbAdapter.open();
un = getArguments().getString("username");
Cursor cur = dbAdapter.getData(un);
String password = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_PASSWORD));
String age = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_AGE));
String weight = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_WEIGHT));
String height = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_HEIGHT));
String gender= cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_GENDER));
I'm getting the String un in my log, means my username is successfully passed. I'm blur with the data retrieving data from the cursor, please help and thank you in advance for the help.
Try this Answer
public Cursor getData(String username){
SQLiteDatabase db = dbHelper.getReadableDatabase();
String sql="select * from " + tableName + " where username =?";
Cursor cursor=database.rawQuery(sql,new String{username});
if (cursor != null)
{ cursor.moveToFirst();}
return cursor;
}
Hope this will help you
Here is small piece of code.Here i am verifying if user exist or not based on username/email and password.I know it is not complete solution but can guide you in right direction (somehow).
public boolean verifyLogin(String email,String password)
{
Cursor mCursor = ourDatabase.rawQuery("SELECT * FROM " + DATABASE_TABLE_USERS + " WHERE Email=? AND Password=?", new String[]{email,password});
if (mCursor != null)
{
if(mCursor.getCount() > 0)
{
return true;
}
}
return false;
}
EditText username;
String S;
S = username.getText().toString();
now run this query
String selectQuery = "SELECT* FROM **TABLE NAME** WHERE username=S ";
Cursor c = db.rawQuery(selectQuery, new String[] { username });
if (c.moveToFirst()) {
temp_address = c.getString(0);
}
c.close();
String name;
name = username.getText().toString();
"select * from yourTable where username= '"+name+"'"
Run this query. I hope it will help you ..!

Sqlite query for multiple result

i want to query for data in sqlite, but in the case where 2item have the same name.. still it return only result... what should i add in this code?
public String getItemNameRbPrice(long lprice) throws SQLException{
String[] column = new String[]{Pro_ID, Pro_Name, Pro_Price, Pro_Description, Pro_Date};
Cursor c = ourDatabase.query(TABLE_NAME, column, Pro_Price + "=" + lprice, null, null, null, null);
if(c != null){
c.moveToFirst();
String name = c.getString(1);
Log.v(name,name + ("zz"));
return name;
}
return null;
}
Try sending List<String>
public List<String> getItemNameRbPrice(long lprice) throws SQLException{
String[] column = new String[]{Pro_ID, Pro_Name, Pro_Price, Pro_Description, Pro_Date};
Cursor c = ourDatabase.query(TABLE_NAME, column, Pro_Price + "=" + lprice, null, null, null, null);
List<String> lst = new ArrayList<String>();
if (cursor.moveToFirst()) {
do {
String name = c.getString(1);
lst.add(name);
Log.v(name,name + ("zz"));
} while (cursor.moveToNext());
}
return lst;
}

Categories

Resources