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();
}
Related
I need to populate the data from the query and populate it on ListView with custom Item.
on OnCreateView, I'm calling my adapter like this:
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(getContext(), android.R.layout.simple_list_item_1, stops)
This is my whole code of LoadData
public void LoadData() {
String query = "SELECT ticket_placeto, COUNT(CASE WHEN passenger_type <> 'Baggage' THEN 1 END) AS Pass,\n" +
"COUNT(CASE WHEN passenger_type = 'Baggage' THEN 1 END) AS Baggage FROM tickets GROUP BY ticket_placeto";
c = sqldb.rawQuery(query, null);
if (c != null) {
if (c.moveToFirst()) {
do {
String placeto = c.getString(0);
String passengers = c.getString(1);
String baggages = c.getString(2);
stops.add(placeto + " " + passengers + " " + baggages);
} while (c.moveToNext());
}
}
}
This is the output of it
I've just hard coded the spacing on stops.add for temporary display of data. I already have a custom ListItem Layout but didn't use it for the mean time.
this is the result of the query on chrome://inspect
enter image description here
for your reference, i just re-code LoadData. thanks to pskink who help me here and to other that respond on this thread.
public void LoadData() {
String query = "SELECT _id, ticket_placeto, " +
"COUNT(CASE WHEN passenger_type <> 'Baggage' THEN 1 END) AS Pass," +
"COUNT(CASE WHEN passenger_type = 'Baggage' THEN 1 END) AS Baggage " +
"FROM tickets GROUP BY ticket_placeto";
final String[] columns = new String[]{
DBHelper.TICKET_ID,
DBHelper.TICKET_PLACETO,
"Pass",
"Baggage",
};
final int[] to = new int[]{
R.id.stops_id,
R.id.stops_location,
R.id.stops_passengers,
R.id.stops_baggages
};
c = sqldb.rawQuery(query,null);
if (c != null) {
adapter = new SimpleCursorAdapter(getContext(), R.layout.item_for_stops, c, columns, to, 0);
lv_stops.setAdapter(adapter);
}
}
1.First initialize your List in onCreate() method of activty,
ArrayList<String> stops = new ArrayList<>();
then pass it to ArrayAdapter.
2.After successfully executing query add data to your "stops" list,then
add following line to your code.
arrayAdapter.notifyDataSetChanged();//to notify that your data of list has been change
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);
I am pretty sure my sqlite syntax is right but I don't know why when database result is loaded in my listview it show all of my data. I think the problem is about my cursor snippet.
How can I fix this problem that load only rows where table_one.id = table_two.day_id
#Override
public List<Model> getAllEx() {
SQLiteDatabase db = helper.getWritableDatabase();
List<Model> list = new ArrayList<>();
String query = "SELECT * FROM " + Constants.TABLE_ONE + " INNER JOIN " + Constants.TABLE_TWO +" ON "+
Constants.ID_ONE + " = " + Constants.ID_DAY;
Cursor c = db.rawQuery(query, null);
while (c.moveToNext()) {
Model model = new Model();
model.setSecond_id(c.getInt(c.getColumnIndex(Constants.ID_TWO)));
model.setExercise(c.getString(c.getColumnIndex(Constants.EXERSICE)));
model.setNumber(c.getString(c.getColumnIndex(Constants.NUMBER)));
model.setReps(c.getString(c.getColumnIndex(Constants.REPS)));
model.setId_day(c.getInt(c.getColumnIndex(Constants.ID_DAY)));
list.add(model);
}
return list;
}
I am not sure what values you have in your constants but is your query like this
select * from table_one as one inner join table_two as two
on one.id = two.day_id
where one.category="cat_one"
and two.category="cat_two"
You can remove the category of second/first table if not required.
I am new to android development and have come across a problem with deleting a row in a SQLite table that I have not been able to find a solution to. When I try to delete a row nothing is happening.
In my activity, called 'MainActivity,' I am using a context menu to call a method to delete an item from the list. This portion of code is as follows:
case R.id.delete_program:
DBAdapter adap = new DBAdapter(this);
adap.open();
long pass = (long) (position + 1);
adap.removeFromCurrent(pass);
adap.close();
Runnable run = new Runnable() {
public void run(){
refreshCurrent(getApplicationContext());
}
};
runOnUiThread(run);
proAdapt.notifyDataSetChanged();
return true;
In 'DBAdapter' the method removeFromCurrent():
public boolean removeFromCurrent(long cp_id) {
return this.dB.delete(PROGRAMS_TABLE, CP_ID + '=' + cp_id, null) > 0;
}
In 'MainActivity' the method refreshCurrent():
public static void refreshCurrent(Context context) {
CURRENT.clear();
DBAdapter adap = new DBAdapter(context);
adap.open();
ArrayList<Program> temp = adap.getCurrentPrograms();
for(Program item : temp) {
Toast.makeText(context, "Item added: " + item.getName(), Toast.LENGTH_SHORT).show();
CURRENT.add(item);
}
adap.close();
}
I'm using the toast to check if the table has changed but the display has not.
From 'DBAdapter' the method getCurrentPrograms():
public ArrayList<Program> getCurrentPrograms() {
ArrayList<Program> list = new ArrayList<Program>();
Cursor cursor =
this.dB.query(PROGRAMS_TABLE, new String[] {
CP_ID, CP_NAME, ACTUAL_DAY, D_ID, CP_CYCLE, CP_DAY_ONE },
null, null, null, null, null);
int rows = cursor.getCount();
if(cursor != null)
cursor.moveToFirst();
for(int i = 1; i <= rows; i++) {
list.add(new Program(cursor.getString(cursor.getColumnIndex(CP_NAME)),
cursor.getInt(cursor.getColumnIndex(ACTUAL_DAY)),
cursor.getInt(cursor.getColumnIndex(CP_DAY_ONE)),
cursor.getInt(cursor.getColumnIndex(CP_CYCLE))));
cursor.moveToNext();
}
return list;
}
The ArrayList 'CURRENT' is the list used to populate the ListView. My thinking was that I would be able to delete a row from the table and then repopulate this list as well as the ListView. I was also curious as to what happened to a SQLite table once a row is removed; do the other rows move up a position, or do they stay in the same place?
I am still very new to this so any help about my problem or tips for the rest of my code would be much appreciated. Let me know what else I'm doing wrong with my programming.
If you are using the SQLiteOpenHelper you should be getting a SQLiteDatabase object and then using a transaction, if you don't set it as successful then nothing will happen
SQLiteDatabase db = mDbHelper.getWritableDatabase();
db.beginTransaction();
//Do stuff
db.setTrasactionSuccessfull();
db.endTransaction();
Also I think when you pass null into the where clause the where doesn't matter.
You should have something like db.delete("tbl", "id=?", new String[]{String.valueOf(id)});
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();
}