Reputation: 3
I'd like to get a value from a table. If the column does not contain any value, then I am going to insert one.
If there is a value, I want to notify the user that a value was inserted already. When my table does not contain anything it shows an error as Java Null Pointer Exception
. I want to get a null value from my table. Please help.
String qu="select * from userinfos";
c=db.rawQuery(qu,null);
int count = c.getCount();
String[] values = new String[count + 1];
int i = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
values[i] = c.getString(c.getColumnIndex("mail"));
Toast.makeText(FiveActivity.this, values[i],Toast.LENGTH_LONG).show();
i++;
}
i=0;
if(values[i].equals(null))
{
String Query = "insert into userinfos (mail,pass) values ('"+ mailuser+ "','" + password + "')";
db.execSQL(Query);
Toast.makeText(FiveActivity.this,"Values Inserted",Toast.LENGTH_LONG).show();
}
else
{
for(int j=0;j<3;j++)
Toast.makeText(FiveActivity.this,"Already one Email-Id:"+ values[i]+" "+"you given. if you want to insert new mail and password then go to Delete app",Toast.LENGTH_LONG).show();
}
Upvotes: 0
Views: 1429
Reputation: 107
this is a simple fonction to manage Usertable or others:
/**
* Check if data exist in table
*
* @param table
* The table to check data
* @param whereArgs
* The conditions to check the data
* @return boolean Return True while data exist; False while data not exist
*/
public boolean isDataExist(String table, String column, String[] whereArgs) {
boolean result = false;
SQLiteDatabase db = this.getWritableDatabase();
String sql = "select * from " + table + " where " + column + " = ?";
Cursor cursor = db.rawQuery(sql, whereArgs);
if (cursor.getCount() > 0) {
result = true;
}
cursor.close();
db.close();
return result;
}
Upvotes: 0
Reputation: 47817
You just need to check your count
value like below:
c=db.rawQuery(qu,null);
int count = c.getCount();
if(count==0)
{
////// No data found
}
else
{
/////data available
}
getCount ()
Returns the numbers of rows in the cursor
http://developer.android.com/reference/android/database/Cursor.html#getCount
Upvotes: 1