Update listview after update database sqlite - android

How to update items in listview after update the row on database sqlite. I have put notifyDataSetChanged() but not success, there is not error, but not refresh data in row. The data will change if I click menu back and open list again. So I want update the data in row after I update data. Below structur my code, Thanks.
CustomBaseAdapter adapter;
ListView cListView;
in onCreate:
cListView = (ListView) findViewById(R.id.list_category);
List<ItemsArtikel> rowItems = (List<ItemsArtikel>) db.getAllCategory(katname);
adapter = new CustomBaseAdapter(this, rowItems);
cListView.setAdapter(adapter);
Query listcategory:
public List<ItemsArtikel> getAllCategory(String cat) {
SQLiteDatabase db = this.getWritableDatabase();
List<ItemsArtikel> cList = new ArrayList<ItemsArtikel>();
String selectQuery = "SELECT * FROM " + TABLE_CAT + " WHERE "
+ COLOM_KAT + "=\"" + cat + "\"";
Cursor c = db.rawQuery(selectQuery, null);
c.moveToFirst();
if (c.getCount() > 0) {
do {
ItemsArtikel kat = new ItemsArtikel();
kat.setID(c.getLong(c.getColumnIndex(COLOM_ID)));
kat.setName(c.getString(c.getColumnIndex(COLOM_NAME)));
kat.setLink(c.getString(c.getColumnIndex(COLOM_LINK)));
kat.setImage(c.getString(c.getColumnIndex(COLOM_IMAGE)));
kategoriList.add(kat);
} while (c.moveToNext());
}
return cList;
}
After i use for listview is presented for to download images and update each row the database using AsyncTask when download image. Image success downloaded and row also success updated, Just not refresh in listview.
This is code onPostExecute when download image:
#Override
protected void onPostExecute(HashMap<String, Object> result) {
String id = (String) result.get("id");
String path = (String) result.get("image");
// update row in database
db.updateRowCategory(id, path);
cListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}

On calling notifyDataSetChanged() it will just notify the register view to update the content to reflect the changes.
In your case you are updating data in Database not in Adapter Data model. To reflect the changes in ListView you need to updated the Adapter's datamodel and then call notifyDataSetChanged();
OR
If your are rendering data directly from Database use CursorAdapter and implement onContentChanged () for updating ListView

Use following line before add adapter.
#Override
protected void onPostExecute(HashMap<String, Object> result) {
String id = (String) result.get("id");
String path = (String) result.get("image");
// update row in database
db.updateRowCategory(id, path);
cListView.Invalidate();
cListView.setAdapter(adapter);
cListView.Invalidate();
adapter.notifyDataSetChanged();
}

Related

Populating Gridview and Listview from List created from databaseHelper

I find some tutorials, to create databaseHelper class, which help me to fetch data from database, the data was fetch using List, but somehow i dont know how to populate that list into ArrayList for my gridview and list view, when i try, it says List cannot converted into ArrayList. How can i do that? here my code snippet
databaseHelper.java
public List<Seat> getAllSeats() {
List<Seat> seats = new ArrayList<Seat>();
String selectQuery = "SELECT * FROM " + TABLE_SEATS + "WHERE status=0";
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Seat seat = new Seat();
seat.set_id(c.getInt((c.getColumnIndex("id"))));
seat.set_table_no(c.getString(c.getColumnIndex("table_no")));
// adding to list
seats.add(seat);
} while (c.moveToNext());
}
return seats;
}
index.java
/* LIST SEAT */
final ArrayList<Seat> list_seat = db.getAllSeats();
final GridView gridview_seat = (GridView) findViewById(R.id.gridviewSeat);
gridview_seat.setAdapter(new SeatListAdapter(this, list_seat));
Just convert your list data into array list with following code...
List<Seat> list = db.getAllSeats();
ArrayList<Seat> list_seat = new ArrayList<Seat>(list.size());
list_seat .addAll(list);

Delete item from database

I'm trying to delete an item onLongClick of listview,
but the selected item is not being deleted. Here's my database delete method:
public int deleteReminderEntry(Model id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(REMINDER_TABLE_NAME, REMINDER_COLUMN_ID + " = ?", new String[] {Integer.toString(id.getId())});
}
and my delete action:
model.getId();
database.deleteReminderEntry(model);
reminderListAdapter.notifyDataSetChanged();
You changed the data in the database, not data in the adapter.
After deleting from the database, either fetch the data again and recreate the adapter or delete the item from the ArrayList passed to the adapter.

SwipeRefresh layout not working in sqlite

I am using swipe refresh layout to load datas from local sqlite i have set the limit 2 and offset as 0 when the list is refreshed the datas are not getting refreshed i don't know why it is not working can anyone help me reagrding this.
Database:
public ArrayList<TransactionSum> getAllTransactionList(int offset) {
ArrayList<TransactionSum> transactionsum = new ArrayList<TransactionSum>();
String selectquery = "SELECT tid,SUM(totalamount) as 'total',strftime('%m-%Y', tdate) as 'month' FROM " + TRANSACTION_LABELS + " WHERE tdate BETWEEN (select min(tdate) from transactionlabel) AND (select max(tdate) from transactionlabel) GROUP BY strftime('%m-%Y', tdate) ORDER BY strftime('%m-%Y', tdate) DESC LIMIT "+2+" OFFSET "+offset+" ";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectquery, null);
if (cursor.moveToFirst()) {
do {
TransactionSum transactiontotal = new TransactionSum();
transactiontotal.setId(cursor.getString(0));
transactiontotal.setTotalamount(cursor.getString(1));
transactiontotal.setMonth(cursor.getString(2));
transactionsum.add(transactiontotal);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return transactionsum;
}
Activity:
#Override
public void onRefresh() {
fetchList();
}
private void fetchList() {
swipeRefreshLayout.setRefreshing(true);
databaseHandlerOtherChgs=new DatabaseHandlerOtherChgs(getApplicationContext());
transactionitems=new ArrayList<TransactionSum>();
transactionitems=databaseHandlerOtherChgs.getAllTransactionList(offSet);
adapter = new TransactionListNewAdapter(this, transactionitems);
for(int i=offSet;i<transactionitems.size();i++){
offSet=offSet+i;
}
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
You are creating a whole new adapter every time you fetch the refresh the list, but you never do anything with this adapter. You have to set it on the view (ListView, `RecyclerView', whichever you are using).
Or, you could add a method to TransactionListAdapter that allows you to change the data in it, and use this method instead of creating new adapters all the time.
public void setTransactionList(ArrayList<TransactionSum> newList) {
mList = newList;
notifyDataSetChanged();
}

Android populate Listview from SQLite List

I'm able to populate my SQLite DB and to do all CRUD operations.
Now I would populate a listview starting from:
List<Starred> data = DBAdapter.getAllUserData();
By log I can read my list:
for (Starred st : data)
Log.d("Title: ", "Title: " + st.getName());
I'm pretty sure I'm missing the Adapter but don't well know how start.
This is my getAllUserData() function:
public static List<Starred> getAllUserData() {
List<Starred> starredList = new ArrayList<Starred>();
// Select All Query
String selectQuery = "SELECT * FROM " + USER_TABLE;
final SQLiteDatabase db = open();
Cursor cursor = db.rawQuery ( selectQuery, null );
if (cursor.moveToFirst()) {
do {
Starred data = new Starred();
data.setID(Integer.parseInt(cursor.getString(0)));
data.setName(cursor.getString(1));
data.setLabel(cursor.getString(2));
// Adding contact to list
starredList.add(data);
} while (cursor.moveToNext());
}
return starredList;
I tried with
ListView lv = (ListView) findViewById(R.id.list);
ArrayAdapter<Starred> arrayAdapter = new ArrayAdapter<Starred>(
this, android.R.layout.simple_list_item_1, data);
lv.setAdapter(arrayAdapter);
but I get nullpointer exception.
Could anyone give me suggestion? Any help would be much appreciated.
try to use the cursor adapter pal
https://github.com/codepath/android_guides/wiki/Populating-a-ListView-with-a-CursorAdapter

Update ListView after delete operation

I am displaying data pulled from the Android OS sqlite database. I am successfully getting the items to delete when I click on them. However I am having an issue refreshing, or updating the listview after the operation.
Below is the code where I delete the contact.
deleteBtn = (Button)v.findViewById(R.id.deleteBtn);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Deleted: " + c.getId() + " " + c.getName(), Toast.LENGTH_SHORT).show();
adapter.deleteContact(c.getId());
updateList();
}
});
Below is the updateList() method:
public void updateList(){
myList.refreshDrawableState();
myList.invalidateViews();
this.notifyDataSetChanged();
}
I included in this method all three ways I tried to refresh but none worked for me. Any idea how I might achieve this?
EDIT: I changed my code thinking this would be the solution but it did not work either:
DbAdapter class delete method():
public boolean deleteContact(int rowId){
getAllContactsList();
return db.delete(DB_TABLE, COLUMN_ID + "=" + rowId, null) > 0;
}
getAllContactsList():
public List<Contact> getAllContactsList(){
List<Contact> contactList = new ArrayList();
Cursor c = db.query(DB_TABLE, new String [] {COLUMN_ID, COLUMN_FNAME, COLUMN_LNAME}, null, null, null, null, null);
//loop through cursor rows and add to list
if(c.moveToFirst()){
do{
Contact contact = new Contact();
contact.setId(Integer.parseInt(c.getString(0)));
contact.setfName(c.getString(1));
contact.setlName(c.getString(2));
contactList.add(contact);
}while(c.moveToNext());
}
return contactList;
}public List<Contact> getAllContactsList(){
List<Contact> contactList = new ArrayList();
Cursor c = db.query(DB_TABLE, new String [] {COLUMN_ID, COLUMN_FNAME, COLUMN_LNAME}, null, null, null, null, null);
//loop through cursor rows and add to list
if(c.moveToFirst()){
do{
Contact contact = new Contact();
contact.setId(Integer.parseInt(c.getString(0)));
contact.setfName(c.getString(1));
contact.setlName(c.getString(2));
contactList.add(contact);
}while(c.moveToNext());
}
return contactList;
}
I thought by getting a new cursor before deleting the contact It would update the list accordingly. Unfortunately It made no difference. Any ideas ?
You have to notify the list's adapter that you have modified the underlying data.
Try using adapter.notifyDataSetChanged();
It seems that you have the Database Adapter class, but you're missing the ArrayAdapter class, which is intended to manage the list of items, displayed in your ListView. Take a look at this example, specifically at the WeatherAdapter.java class.
If I am wrong in my assumptions and the adapter object in your code is not a database adapter, but an ArrayAdapter class, try putting adapter.notifyDataSetChanged() instead of this.notifyDataSetChanged().
Let me know if this helped.
You must requery and and generate new list:
public void updateList(){
clear();
addAll(contactsDbHelper.getAllContactsList()); //addAll works since 11 API version.
notifyDataSetChanged(); //need this is you dissabled auto notify
}
P.S. You should done this job with using Content providers and CursorAdapter, but you need manually notify content provider about changes, because Cursor.requery() is deprecated since 11 version.

Categories

Resources