I am having trouble getting a null value from SQLite database using Android.
My database has 10 columns. From column 1 to 8 all are filled with values. But there are several rows where the values in column 9 and column 10 are either null or some number.
I want to check:
String selectQuery = "SELECT * FROM products WHERE barcodeId='" + id + "'";
Cursor myCursor = db.rawQuery(selectQuery, null);
if (myCursor.moveToFirst()) {
//checking to see if there is something in column 9
if(myCursor.getString(8) != null){
// do soemthing
}else {
// if there is nothing do something
}
//checking to see if there is something in column 10
if(myCursor.getString(9) != null){
// do soemthing
}else {
// if there is nothing do something
}
}
Can some one provide a working code according to my example with column 9 and 10 in my table.
A brief explanation will also be welcomed.
Thanks
I don't know if Cursor.getString() will return a null or not. The docs don't say, it may just return an empty string. You should use Cursor.isNull() instead to check for a null value in your column.
Thanks DavidCAdams that fixed my problem.
Here is my code if someone is interested in it.
if(myCursor.isNull(8)){
Log.w("No value", "Cell is empty");
}else{
Log.w("Value is present", "There is a value");
}
if(myCursor.isNull(9)){
Log.w("No value", "Cell is empty");
}else{
Log.w("Value is present", "There is a value");
}
Related
I want to check the data in SQLite if already exist can update or else insert.I am checking code like this what i mentioned below.
Code:
public long addmenus(String navigationdrawer,String optionname)
{
SQLiteDatabase menus=this.getWritableDatabase();
try {
ContentValues values=new ContentValues();
values.put(HEADER_NAME,navigationdrawer);
values.put(CHILD_NAME,optionname);
// menus.insert(TABLE_NAME,null,values);
// String owner=optionname;
Cursor cursor = menus.rawQuery("select * from TABLE_NAME where CHILD_NAME ='"+ optionname +"'", null);
if(cursor.getCount()<1)
{
//execute insert query here
long rows = menus.insert(TABLE_NAME, null, values);
return rows;
// return rows inserted.
}
else
{
//Perform the update query
String strFilter = "CHILD_NAME" + optionname;
long updaterow=menus.update(TABLE_NAME,values,strFilter,null);
return updaterow;
// return rows updated.
}
// menus.close();
} catch (Exception e) {
return -1;
}
finally {
if (menus != null)
menus.close();
}
}
My activity:
I converted whole json data into string object then insert into SQLite.
String productpage=jsonObject.toString();
db.addmenus(productpage,"Navigationmenus");
But It doesn't work.It couldn't insert into sqlite.
Anyone solve this problem Glad to appreciate.
Thanks in advance
You can user insertWithOnConflict() like this
db.insertWithOnConflict(TABLE, null, yourContentValues, SQLiteDatabase.CONFLICT_REPLACE);
You can use refer this Link. That link explains how to find the email address available in a table or not, you can change the column name, table and pass the values according. In your scenario you want to check the whether the name exists already or not, so you must pass which name you want to find. If the name is there then this method will return true or false. You can validate whether you had to insert or update according the response.i.e., false means you had to insert, otherwise if it is true means then you had to update.
you should use replace into
REPLACE INTO table(...) VALUES(...);
Question is not much clear but, i think you want to check either data/record is inserted in SQLite or not. you will need to define some extra variable long rowInserted insert() method returns the row ID of the newly inserted row, or -1 when an error occurred.
menus.insert(TABLE_NAME, null, values);
long rowInserted = db.insert(AddNewPhysicalPerson, null, newValues);
if(rowInserted != -1)
Toast.makeText(myContext, "New row added :" + rowInserted, Toast.LENGTH_SHORT).show();
else
Toast.makeText(myContext, "Something wrong", Toast.LENGTH_SHORT).show();
Updated
check either data is in table or column? for this you use this code
public boolean Exists(String id){
Cursor res = getAllData();
int count=0;
while (res.moveToNext()){
String email =res.getString(3);
if(email.equals(id)){
count++;
}
}
if(count==0){
return false;
} else{
return true;
}
}
Second you asking about json first store all data in any List run time and get string from it then you are able to store in SQlite
try {
items = jsonObject.getJSONArray("myjsonattribute");
List<MyAnySetterGetter> mList = new ArrayList<MyAnySetterGetter>();
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String mfilename = c.getString("myjsonattribute2");
mList.add(mfilename);
}
} catch (JSONException e) {
//e.printStackTrace();
}
then use above list to insert data from list to SQLite
like
String str1 = mList.get(position).getMYITEM1();
String str2 = mList.get(position).getMYITEM2();
insert str1 and str2 in SQLite hope you will get idea.
you should
set key for the table, then
insert(if the key existed it will not insert anymore), then
update all row.
I am working in an android application and I am using sqllite in my application. I want to update my sql with a query that contains case statement. Please suggest me a correct solution to execute this query and return me an int value to confirm if the table is updated successfully.
My query ::
UPDATE TblAgencies SET Selected= CASE WHEN ID=6 THEN 1 ELSE 0 END
update TblAgencies set Selected = (ID == 6); will do this.
As to "did the update work correctly" -- that's standard API work, nothing to do with the query itself.
I wont do the programming for you but here how you do it.
int res = db.update(table, values, whereClause, whereArgs);
if(res>0) etc...
try
{
database=openOrCreateDatabase("solutiondb", MODE_PRIVATE, null);
database.execSQL("update patientdetails set name='"+naMe+"',dob='"+DOB+"',gender='"+genDer+"',height="+heiGht+",weight="+weiGht+",bmi="+BMI+",bloodgroup='"+bloodGroup+"',profession='"+proFession+"',address='"+addRess+"',contact="+contactNumber+",smoking='"+smoKing+"',drinking='"+drinKing+"',maritalstatus='"+maritalStatus+"',physician='"+phySican+"' where id="+patientId+"");
Toast.makeText(PersonalInformationActivity.this, "Your Personal Details Are Saved Successfully", Toast.LENGTH_LONG).show();
dialog.dismiss();
intent=new Intent(PersonalInformationActivity.this, PersoxcsdActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
database.close();
}
catch(SQLException exception)
{
}
Good day, Hope the tilte is not misleading. please take a look at the code snippet below and notice the commented parts:
//if(cursor.moveToFirst()){
if(cursor.moveToNext() == true){
// do {
Log.d(TAG, "Column Name in bindview is " + columnName);
String name = cursor.getString(cursor.getColumnIndexOrThrow(columnName));
Log.d(TAG, " name is " + name);
// } while(cursor.moveToNext());
//}
}
now only when i use cursor.moveToNext() do i get a value for the string "name".if i use the do/while statement as commented out in the above code or cursor.moveTofirst(), i get null value for the string. any idea why this is happening.
*Background:* am calling/initalizing this CursorAdapter from onLoadFinished() of a CursorLoader.
Perhaps you are trying to do this:
// Get the column's index
int index = cursor.getColumnIndex(columnName);
String name;
// You might want to check if the column exist with:
// if(index == -1)
// return;
// If you have move the Cursor's index, reset it:
// cursor.moveToFirst();
while(cursor.moveToNext()) { // == true is implied
name = cursor.getString(index);
Log.d(TAG, " name is " + name);
}
First find the column index outside the loop, the column index will not change unless you change the cursor. Then loop through all the valid results.
I have an application that runs fine on android 2.1, but when trying to transition it to 3.0 I get a cursor error that I'm not familar with.
Java.lang.IllegalStateException: Couldn't read row0, column -1 from
cursor window. Make sure cursor is initialized correctly before
accessing data from it.
All the data is storred in a SQLite database and this code works fine in android 2.1. Does a cursor have to be initialized differently in android 3.0?
Listed below is my code.
private void OpenGroupData(){
SQLiteDatabase db = openOrCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE,null);
Cursor cur = db.rawQuery("SELECT groupid FROM properties GROUP BY GroupID" + ";" , null);
LinearLayout glayout = (LinearLayout) findViewById(R.id.Grouplayout);
LinearLayout gwindow = (LinearLayout) findViewById(R.id.groupwindow);
TextView data = new TextView(this);
glayout.addView(data);
data.setText("");
int ID = cur.getColumnIndex("groupid");
int idvalue;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
try{
// Check if our result was valid.
cur.moveToFirst();
if (cur != null) {
// Loop through all Results
do {data = new TextView(this);
data.setTextSize(20);
data.setClickable(true);
data.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
GroupClick(v);
}
});
glayout.addView(data);
idvalue = cur.getInt(ID);
data.setId(idvalue);
data.setText("Group: " + idvalue);
}while(cur.moveToNext());
}
cur.close();
db.close();
} catch(Exception e) {
Toast.makeText(getApplicationContext(), "Open Group Exception: " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
I ran into the same error message earlier this day. All it turned out to was that I made a typo in the column name. So, if it still applies, you could go and check the column name for typo's. Note that its case sensitive aswell. Error for me was along the lines of:
//Trew error
c.getColumnIndex("ArticleNumber");
//Was correct
c.getColumnIndex("Articlenumber");
Alright I figured it out. For some reason when trying to transistion my application to 3.0 when my cursor goes and gets the column index for a field, in this case ("groupid") it is returning a value of -1. When the Cursor tries to start at -1 it crashes because it can't find a record at row(0), column(-1). So my fix was to just add one to the column index when getting the id. see below.
int ID = cur.getColumnIndex("groupid") + 1;
int idvalue;
By adding 1 to the Column index it seems to have solved the problem.
If getColumnIndex returns -1, then the column doesn't exist.
Otherwize it returnes zero-based column index.
-1 is the _id column which every sqlite table should have as is required by the android framework. If you have to add +1 to the index you are going wrong somewhere.
The -1 value returns form getColumnIndex(columnName) if 'columnName' can't be found. Check the column names
I wrote the below code for compare the record with the database record.its comparing but inserting all the records
public void onClick(View v) {
if(v.equals(add))
{
if(ifExisting())
{
insert();
Log.e("Data Inserting","true");
Intent i=new Intent(AddCategory.this,ShareFolioActivity.class);
startActivity(i);
//Toast.makeText(AddCategory.this, "Already exists",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(AddCategory.this, "Already exists",Toast.LENGTH_LONG).show();
Log.e("Data Inserting","false");
}
}
}
boolean ifExisting() {
Log.e("wquery","SELECT * FROM sharelist WHERE category='"+category.getText().toString()+"'");
Cursor c = db.rawQuery( "SELECT category FROM sharelist WHERE category='"+category.getText().toString()+";'",null);
if(c.getCount()==-1)
{
Log.e("Condition true","true");
return false;
}
else
{
Log.e("Condition true","false");
return true;
}
}
You have if(ifExisting())
{
insert();
shouldn't it instead be if(!ifExisting())
{
insert();
Otherwise you are inserting if it exists.
You seem to be expecting that c.getCount() will be -1 if the query returns 0 rows. Why wouldn't it return 0? (I don't remember seeing a case where it returns -1, but perhaps my memory is faulty.)
In any case, checking for c.getCount() <= 0 would seem to be safer.
Also, this query
Cursor c = db.rawQuery( "SELECT category FROM sharelist WHERE category='"+category.getText().toString()+";'",null);
is malformed -- look at the end where you have ";'". You want to have "'" there. (Query strings that are passed to rawQuery must not end in a semicolon; otherwise, "';" would be the correct choice.)
As others have said to you on other threads, you really don't want to be making queries by concatenation; using the selectionArgs argument is a much safer way to pass query values.