Sqlite android update query not working - android

Here My update database table methods
public void insertionchallanval(ArrayList<String> itemcode,ArrayList<String> item,ArrayList<String> quantity,
ArrayList<String> date,ArrayList<String> status,ArrayList<String> id)
{
ContentValues insertValues = new ContentValues();
for(int i=0;i<status.size();i++)
{
if(!retriveidstatus(id.get(i)))
{
insertValues.put("id", id.get(i));
insertValues.put("itemcode", itemcode.get(i));
insertValues.put("item", item.get(i));
insertValues.put("status", status.get(i));
insertValues.put("date", date.get(i));
insertValues.put("quantity", quantity.get(i));
//insertValues.put("category", category.get(i));
myDataBase.insert("create_challan", null, insertValues);
}
else
{
insertValues.put("id", id.get(i));
insertValues.put("itemcode", itemcode.get(i));
insertValues.put("item", item.get(i));
insertValues.put("quantity", quantity.get(i));
insertValues.put("status", status.get(i));
insertValues.put("date", date.get(i));
//insertValues.put("category", category.get(i));
myDataBase.update("create_challan", insertValues, "id="+"'"+id.get(i)+"'",null );
}
}
}
Here my check Id Methods
public boolean retriveidstatus(String id)
{
Cursor curCalllog = myDataBase.rawQuery("SELECT id FROM create_challan", null);
if(curCalllog.moveToNext() && curCalllog != null) {
while(!curCalllog.isAfterLast())
{
if(id.contains(curCalllog.getString(0)))
{
return true;
}
curCalllog.moveToNext();
}
}
return false;
}
Table Structure
id String
status String
date String
challanno String
itemcode String
item String
quantity String
When i call methods for insertion new value then its working fine but when i call again with new updated value then update methods return 0 means no row effected
Please Help me how i can fix this problem
Thanks IN Advance

Instead of checking wether the _IDs exist or not you can use replace() method of the class SQLiteDatabase like this :
myDataBase.replace("create_challan", null, insertValues);
hope it helps Cheers :)

Related

Recycle view Adapter not updating value Getting BY Sqlite

I have one application in which initially I am inserting parameter for font color and font size manually and by getting thoes data into adpater by reading database i was able to make change in fontsize and fontcolor of list items.
Important code:
insert method of helper:
public boolean insertData(ContactModel contactModel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
// contentValues.put(col_0,contactModel.getId());
contentValues.put(col_1,contactModel.getName());
contentValues.put(col_2,contactModel.getNumber());
contentValues.put(col_3,contactModel.getColor());
contentValues.put(col_4,contactModel.getFSize());
contentValues.put(col_5,contactModel.getDataIndex());
// long result =db.insert(Table_name,null,contentValues);
long result = db.insertWithOnConflict(Table_name, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);
if(result == -1){
return false;
}else{
return true;
}
}
method for insert data :
public void tempinsert(String name,String num,String color,int size,int index){
boolean inSamedata=tempSqliteDatabaseHelper.IsItemExist(name,num);
if(inSamedata==false){
boolean indata = tempSqliteDatabaseHelper.insertData(new ContactModel(name,num,color,size,index));
if (indata == true) {
Log.e("DataSave","DataSave");
}
else{
Log.e("In_Data_not_True","In Data not True");
}
}else if(inSamedata==true){
Log.e("Record_Exist","Record Exist");
}
}
Calling above method:
tempinsert(getDisplayName(),getPhNumber(),"#2d2d2d",35,1);
As you can see I am inserting font color and size statically.
Code inside onBind method adapter for make change in list item:
#Override
public void onBindViewHolder(#NonNull MyContactHolder myContactHolder, int i) {
myContactHolder.Name.setText(customDataListModels.get(i).getName());
myContactHolder.Number.setText(customDataListModels.get(i).getNumber());
Log.e("poistionAdapter:", String.valueOf(myContactHolder.getPosition()));
Cursor cursor = tempSqliteDatabaseHelper.getAllData();
if (cursor.getCount() == 0) {
Toast.makeText(mcontext.getApplicationContext(), "No Contact Selected", Toast.LENGTH_SHORT).show();
return;
}
while (cursor.moveToNext()) {
Integer SFontsize=cursor.getInt(4);
String SColor=cursor.getString(3);
myContactHolder.Name.setTextColor(Color.parseColor(cursor.getString(3)));
myContactHolder.Name.setTextSize(SFontsize);
Log.d("Font_Size", String.valueOf(SFontsize));
Log.d("Font_color", String.valueOf(SColor));
}
}
Here inside log I am getting same value as inserted, Everything is fine uptil this point, Problem occurs After i am updating fontsize and fontcolor in database.After update I am able get updated fontsize/color in log but whenever I am give thoes value to
myContactHolder.Name.setTextColor(Color.parseColor(cursor.getString(3)));
myContactHolder.Name.setTextSize(SFontsize);
Textview not updating it's font size and color according to update , Funny thing is for cursor.getString(3) and SFontsize ,, I am getting updating value.If u reqiued any other code for understand my problem post in comment.

How to know when SQLite query is finished

Ok, I've got this Retrofit Call that receives a list of objects and insert the into a local SQLite database. I want to display a message saying that the operation was successful with a Ok button that when pressed opens a new activity.
How do I check if my Query has finished so I can show the message?
final ContactApi contactApi = retrofit.create(ContactApi.class);
Call<List<Contact>> callContact = contactApi.getContact(token);
callContact.enqueue(new Callback<List<Contact>>() {
#Override
public void onResponse(Response<List<Contact>> response, Retrofit retrofit) {
List<Contact> contactList = response.body();
if (contactList != null) {
try {
DBHelper dbHelper = new DBHelper(TokenActivity.this, token);
SQLiteDatabase conn = dbHelper.getWritableDatabase();
RepoContact repocontact = new RepoContact(conn);
// Inserts each contact into the database
for (Contatc c : contactList) {
repositorioCadastro.inserirCadastro(c);
Log.i("ACTTOKEN", "Contact insert ID: " + c.getId());
}
} catch (SQLiteException e) {
Log.i("ACTTOKEN", "Faillure on insert: " + e.getMessage());
}
}
wrap your code in try{...}finally{...} blocks with a listener ( beginTransactionWithListener(SQLiteTransactionListener transactionListener)), and use the transactionListner to check whether everything went well within the transaction, in addition to everything within the try/finally.
what you have is good, just try adding finally block..
something like this..
db.beginTransaction();
try {
...
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
You can try a different loop, something like this:
for(int i = 0; i < contactList.size(); i++) {
Contact c = contactList.get(i);
repositorioCadastro.inserirCadastro(c);
Log.i("ACTTOKEN", "Contact insert ID: " + c.getId());
if(i == (contactList.size() - 1)) {
// DO SOMETHING HERE
}
}
You may check insert statement return a long when query successfully executed then long value.
db.insert()
returns the row ID of the newly inserted row, or -1 if an error occurred

To get count of duplicate column values

I have created a table with id and tag as column.
id is set as primary key. And in tag column, I have entered more than one value.
So now i want to get the count of how many times the tag value is repeated.
So my table is like this.
Id Tag
---------------------
1 Friend, Family
2 Family, Enemy
and my output should be like this:
friend (1)
family(2)
Enemy(1)
I have written a code but not getting the result I want.
This is MyDatabase.java code:
public Details calculateCount()
{
Details detail = null;
try
{
SQLiteDatabase db=this.getWritableDatabase();
String selectQuery=("select count(*),Tags from photodetails group by Tags" );
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToLast())
{
do
{
detail=new Details(Integer.parseInt(cursor.getString(0)),(cursor.getString(1)));
}while( cursor.moveToNext());
}
}
catch(Exception e)
{
e.printStackTrace();
}
return detail;
}
And this is MAinActivity.java code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
getActionBar().setDisplayHomeAsUpEnabled(true);
MyDataBase MyDB = new MyDataBase(this);
Log.d(LOGCAT,"Entered MAinActivity2");
Details c= MyDB.calculateCount();
if(c == null)
{
Log.d(LOGCAT,"C is null");
}
else
{
Log.d(LOGCAT,c.getTag()); // Here iam only retrieving tag dont know how to get that count.
}
}
Pls help me out on this
If you want to get a count, you're going to want to create a method such as a int getCount() method that will return the int value of the count. Currently, you have Details calculateCount() which will return a Details object.

problems with cursor and getting data?

I have created a table and trying to fetch data from it using a cursor as follow:
public Cursor getcontent() {
Cursor d = database.query(DatabaseHandler.Table_Name2,allColumns,selection, null, null,null,null);
return d;
}
Cursor r = X.getcontent();
if (r.getCount() > 0) {
r.moveToFirst();
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext()==true);
r.close();
} else {
Log.i("TAG"," No value found");
}
}
I am showing the result in the TextView to see what data it is fetched. My problem is when I run this code sometimes it shows the data in the TextView, whatever it has fetched and sometimes it doesn't. Its a 50:50 ratio, according to me it should show fetched values every time as data is fetched every time I don't know what is wrong here, can someone tell me what's the issue here?
Check Whether Cursor you are getting is Null or not . and if yes then What is the Count of Cursor. you can Do it by Below Way.
Cursor r = X.getcontent();
if ((r != null) && (r.getCount() > 0)) {
r.moveToFirst();
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext());
r.close();
} else {
Log.i("TAG"," No value found inside Cursor");
}
try like this
Cursor r = X.getcontent();
try {
if (r.moveToFirst()) {
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext());
}
} finally {
if(r!=null) {
r.close();
}
}

ContentValues Object comparing with Database wont work

I'm trying to compare a ContentValues Object with values from a Database, but I can't figure out why the following wont work:
ContentValues werte = new ContentValues();
try{
JSONObject ClickedItem = new JSONObject();
ClickedItem = resultArray.getJSONObject(position);
werte.put("name", ClickedItem.getString("name"));
werte.put("hersteller", ClickedItem.getString("hersteller"));
}
catch (Exception e) {
System.out.println("Whoops - something went wrong!3");
e.printStackTrace();
}
Boolean allreadyAdded = false;
Cursor devicesCursor = mDatenbank.query("addedDevices", new String[] {"name", "hersteller"}, null, null, null, null, null);
startManagingCursor(devicesCursor);
devicesCursor.moveToFirst();
for (int i=0;i<devicesCursor.getCount();i++){
if(devicesCursor.getString(0) == werte.getAsString("name")){
allreadyAdded = true;
}
devicesCursor.moveToNext();
}
if(allreadyAdded==false){
mDatenbank.insert("addedDevices", null, werte);
}
The if(devicesCursor.getString(0) == werte.getAsString("name")) just wont work and I can't figure out why. System.out.println shows me that devicesCursor and were both have the same value but already Added won't be set to true...
Because you can not compare two string using == operator, Your if condition never be gone true.
To compare two strings just use .equals() or .equalsIgnoreCases() from Java String Class..
if(devicesCursor.getString(0).equals(werte.getAsString("name")))

Categories

Resources