Handling Invalid SQLite Queries in Android - android

I have a simple code that manages to successfully query an SQLite Database and convert that result from cursor to string in order to display it on screen.
My problem now would be invalid queries that make the App Crash. Would there be a way to successfully handle invalid queries? Preferably something that would keep my app from crashing and would just redirect the user to the home page and display a toast of warning.
So far my method for searching looks like this:
public String search(DataBaseHelper myDB){
SQLiteDatabase db = myDB.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
cursor.moveToFirst();
String data = cursor.getString(cursor.getColumnIndexOrThrow("BuildingColor")) + " " +
cursor.getString(cursor.getColumnIndex("Room"));
//Toast msg = Toast.makeText(getBaseContext(),data, Toast.LENGTH_SHORT);
//msg.show();
cursor.close();
return data;
}

Cursor cursor = NULL ;
try
{
cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
if(cursor != NULL)
{
try {
if (cursor.moveToNext()) {
String data = cursor.getString(cursor.getColumnIndexOrThrow("BuildingColor")) +
" " + cursor.getString(cursor.getColumnIndex("Room"));
} else {
// Query result was empty, deal with it here.
}
} finally {
// Cursors should be closed
cursor.close();
}
}
}
catch (SQLiteException e) // (Exception e) catch-all:s are bad mmkay.
{
//print exception
}

Cursor cursor = null;
String data = "";
try
{
cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
}catch (Exception e) {
// TODO: handle exception
}

Related

How do I make my Android app insert record only if it doesn't exist else display a Toast or Message?

I need to enter username & password in edittext & store them into a database on clicking a button. They shoud be stored only if the any other record doesn't have same username. This one causes app to crash
public void updateDB(){
username = editTextUser.getText().toString();
password = editTextPassword.getText().toString();
cursor = db.rawQuery("select * from " +UserDatabase.TABLE1+" where"+UserDatabase.USERNAME+" ='" +username+ "'",null);
if (cursor.getCount()==0) {
values.put(UserDatabase.USERNAME,username);
values.put(UserDatabase.PASSWORD,password);
try {
db.insert(UserDatabase.TABLE1, null, values);
Toast.makeText(this,"Registered", Toast.LENGTH_SHORT).show();
Log.d("SignUpActivity", username + " " + password);
} catch (SQLiteException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this,"Username NA", Toast.LENGTH_SHORT).show();
}
}
you can use insertOrThrow() method instead,just put an UNIQUE keyword before username in table and introduce an new
catch with(SQLException e){}
in this you can toast you messsage
Use this Method for Checking User Already Exist's or Not.
// For UserName[Person] Already Exist
public String ExistsValidation(String PersonName) {
String PName = "";
SQLiteDatabase db = this.getReadableDatabase();
try {
Cursor cursor = db.query(TABLE_NAME, null, PERSON_NAME + "=?", new String[]{String.valueOf(PersonName).trim()}, null, null, null);
if (cursor == null) {
return PName;
} else {
cursor.moveToFirst();
PName = cursor.getString(cursor.getColumnIndex("PersonName"));
}
cursor.close();
} catch (Exception ex) {
ex.printStackTrace();
}
db.close();
return PName;
}
Use above Method Like :
String PersonName = etPersonName.getText().toString().trim();
String storedPersonName = db.ExistsValidation(PersonName);
// if PersonName Exists
if (PersonName.equals(storedPersonName)) {
ShowAlertDialog("Error..!", "PersonName Already Exists,Enter Another Name");
return false;
}

Android Trying to query data but its not returning anything

I am trying to query data. I confirmed that data is being inserted into the database. I tried dumping the query to the log but it doesn't show anything. It never goes into the while loop only the finally. There should be a total of 4 rows in the table being returned.
private void queryCol(String t)
{
Log.d(TAG, "IN queryCol");
final String TABLE_NAME = "CInfo";
String[] projection = {"col1"};
Cursor cursor = db.query(
true,
TABLE_NAME, // The table to query
projection, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null, // The sort order
null,
null
);
try {
while (cursor.moveToNext()) {
Log.d(TAG, "in while");
String s = DatabaseUtils.dumpCursorToString(cursor);
cinfo.add(cursor.getString(cursor.getColumnIndex(term))); //cinfo is an arrayList
Log.d(TAG, s);
}
}
catch (Exception e)
{
Log.d(TAG, "Exception " + e);
}
finally {
Log.d(TAG, "in finally");
cursor.close();
db.close();
}

Exception Invalid Limit Clauses - Android

I am trying to put json object in sqlite database
private void addList(String info){
try {
JSONObject reader=new JSONObject(info);
String COMMAND = reader.getString("COMMAND");
String PARAMS = reader.getString("PARAMS");
int id = vpictures.InsertList(COMMAND,info);
} catch (Exception e){
if (DEBUG_FLAG)Log.d("Log1 ", "adding Exception :"+ e.getMessage());
}
return;
}
The json object info looks like this
{
"COMMAND":"ADD_NEW",
"PARAMS":{
"deviceID":"1234",
"custID":"41701",
"description":"Ddd",
"colTranType":"ABS",
}
}
This is my sqlite table
private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER, DEVICEID TEXT, LTIME INTEGER, LATITUDE REAL,"+
"LONGITUDE REAL, THEPICTURE BLOB, SENT INTEGER, NOTES TEXT, COMMAND TEXT, PARAMS TEXT);";
I am trying to insert COMMAND and PARAMS.
And my sqlite code looks like this
public int InsertList(String COMMAND, String info){
try {
JSONObject reader = new JSONObject(info);
String param_str = reader.getString("info");
if (_Db == null)
_Db = getWritableDatabase();
if (_LastId == -1)
{
Cursor c = _Db.query(TABLE_NAME, new String[] {"max(ID)"}, null, null, null, null, COMMAND, param_str);
if (c != null && c.moveToFirst()) {
_LastId = c.getInt(0);
c.close();
}
else
_LastId = 0;
c.close();
}
try {
ContentValues cv = new ContentValues();
cv.put("ID",++_LastId);
cv.put("COMMAND",String.valueOf(COMMAND));
cv.put("PARAMS",PARAMS);
_Db.insert(TABLE_NAME, "", cv);
} catch (Exception e){
Log.d("Log2","Error:"+e.getMessage());
}
} catch (JSONException e1) {
Log.d("Log2","Error:"+e1.getMessage());
}
return _LastId;
}
Basically the exception i am getting from the addList function
adding Exception : Exception invalid LIMIT clauses
How to consider inserting json object into sqlite
These are the parameters of the query() method:
Cursor c = _Db.query(
TABLE_NAME, // table
new String[] {"max(ID)"}, // columns
null, // selection
null, // selectionArgs
null, // groupBy
null, // having
COMMAND, // orderBy
param_str); // limit
The orderBy and limit parameters do not make sense. To find the largest ID in the entire table, these parameters must be null.
Anyway, there is a helper function that makes it reasier to read a single number from the database without having to muck around with a cursor:
long lastID = DatabaseUtils.longForQuery(_Db, "SELECT max(ID) FROM "+TABLE_NAME, null);
And if you had declared the ID column as INTEGER PRIMARY KEY, it would be autoincremented, and you would not have to set it manually.

NullPointer while using Cursor

I couldn't find a suitable title for my question. Here is the problem... After syso'ing the statement in getData(), it should print the values in the cursor, cMainTable, using the statement in displayDataForMainTable(). But, it doesn't. There are no exceptions, and errors. I have also kept the output that i get in the LogCat. Can someone help me with, why there is no output after the first print.
try {
pm = new PortfolioManager(this);
cMainTable = pm.getData("mainTable");
if (cMainTable.equals(null)) {
System.out.println("Null is returned");
}
displayDataForMainTable(cMainTable);
}
catch (Exception e) {
System.out.println("problem at Oncreate Method");
}
getData() method:
public Cursor getData(String string) {
System.out.println("Getting Data for Table " + string);
c = sqlDB.rawQuery("select * from " + string, null);
return c;
}
displayDataForMainTable() method:
private void displayDataForMainTable(Cursor c2) {
try {
if (c2 != null) {
if (c2.getCount() > 0) {
c2.moveToFirst();
do {
String SNo = c2.getString(c2.getColumnIndex("scriptnumber"));
String SName = c2.getString(c2.getColumnIndex("scriptname"));
int quant = Integer.parseInt(c2.getString(c2.getColumnIndex("totalquantity")));
double avg = Double.parseDouble(c2.getString(c2.getColumnIndex("averageprice")));
double cur = Double.parseDouble(c2.getString(c2.getColumnIndex("currentprice")));
double log = Double.parseDouble(c2.getString(c2.getColumnIndex("lossorgain")));
System.out.println("Inserted Values are ::: " + SNo
+ " " + SName + " " + String.valueOf(quant)
+ " " + String.valueOf(avg) + " "
+ String.valueOf(cur) + " "
+ String.valueOf(log));
} while (c2.moveToNext());
}
}
else {
System.out.println("Cursor c2 is Empty");
}
} catch (Exception e) {
System.out.println("Exception in displayDataForMainTable");
}
}
output
01-18 11:02:27.523: D/dalvikvm(468): GC_EXTERNAL_ALLOC freed 47K, 53% free 2567K/5379K, external 2090K/2137K, paused 45ms
01-18 11:02:33.983: I/System.out(468): Getting Data for Table mainTable
01-18 11:02:36.584: W/KeyCharacterMap(468): No keyboard for id 0
01-18 11:02:36.584: W/KeyCharacterMap(468): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
Edit 1 :::
I have modified the getData() as suggested by Nasser, but the output remains the same..
public Cursor getData(String string) {
System.out.println("Getting Data for Table "+string);
String table = string;
sqlDB = getReadableDatabase();
c = sqlDB.query(table, null, null, null, null, null, null);
//c = sqlDB.rawQuery("select * from "+string, null);
return c;
}
As I read, passing null to the columns(2nd argument) will return all the rows. If this is correct, then the result is the same.
i think u should not return cursor from db instead of that create a setterGetter class set data in its object and return array of that object..
here's my code for same.. try..
also put logs there so u'll get idea about what is going on..
public ArrayList<ContactSetterGetter> getAllNumbers() {
ArrayList<ContactSetterGetter> setterList = new ArrayList<ContactSetterGetter>();
db = getWritableDatabase();
Cursor c = db.query(C_TABLE_NAME, new String[] {"contact_number"},null, null, null, null, null);
if (c.getCount() != 0) {
c.moveToFirst();
do {
ContactSetterGetter setter = new ContactSetterGetter();
setter.setContactNumber(c.getString(0));
setterList.add(setter);
} while (c.moveToNext());
}else{
c.close();
db.close();
return setterList;
}
c.close();
db.close();
return setterList;
}
It seems that Eclipse has shown mercy on me and is displaying the output. Fought for over 4 hours changing code, surfing, finally ended up with no changes in code.
No matter how smart you are as a coder, IDEs always make you feel a novice.

want to get a row from cursor

I want to get a row and this row have 2 columns which named username and password my code is here:
String selection = PROFILE_COLUMN_USERNAME + " = '" + userName+ "' AND " +PROFILE_COLUMN_PASSWORD + " = '" + password + "'";
Cursor cursor = database.query(TABLE_NAME, new String[] {PROFILE_COLUMN_USERNAME, PROFILE_COLUMN_PASSWORD }, selection,null, null, null, null);
I got a sample data like username = erdem and password= c on my db but when i write this sample and write to get username like this:
String s =cursor.getString(cursor.getColumnIndex(PROFILE_COLUMN_USERNAME));
it doesn't work. Why?
Try something like below : Here "path_on_server" is the name of the column in the DB table whose value is being extracted. You can change it to your table's column name.
String query = "some query";
Cursor c = newDB.rawQuery(query, null);
if (c != null) {
if (c.moveToFirst()) {
do {
mPathOnServer = c.getString(c
.getColumnIndex("path_on_server"));
} while (c.moveToNext());
}
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not extract information from DB");
}
Use moveToFirst, read the documentation.
Try this way...
Cursor cursor = null;
try {
String queryString = "SELECT * FROM Table_Name";
cursor = myDatabase.rawQuery(queryString, null);
if (cursor != null && cursor.moveToFirst()) {
do {
String nextUser = new String(cursor.getString(cursor
.getColumnIndex("driver_fname")));
} while (cursor.moveToNext());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.deactivate();
cursor.close();
cursor = null;
}
if (myDatabase != null) {
myDatabase.close();
}
}

Categories

Resources