Android: Order Headers Alphabetically in an Expandable List - android

I can't order alphabetically the headers of my Expandable List. I'm getting the headers of my list from my Database. I get the headers alphabetically order from Database but then when I add them to my Expandable List something happens, because when I test it(on my phone), they appear with no order. Can you please help?
HashMap<String, List<String>> expandableListDetail = new HashMap<String, List<String>>();
(...)
List<String> categoria_header = new ArrayList<String>();
Database db = new Database(context);
List<Categorias> categorias;
categorias = db.getAllCategorias();
for (int i=0; i<categorias.size(); i++){
//Log.d("Expandabe","-->"+categorias.get(i).toString());
expandableListDetail.put(categorias.get(i).toString(), categoria_header);
}
Then my getAllCategories method is:
public List<Categorias> getAllCategorias(){
String selectQuery;
Cursor cursor;
int i=0;
List<Categorias> categorias = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
selectQuery = "SELECT * FROM " + TABLE_CATEGORIA + " ORDER BY " + col_NOME_CATEGORIA + " ASC;";
//Log.d("Database-->",""+selectQuery);
cursor = db.rawQuery(selectQuery, null);
if (cursor !=null) {
while (cursor.moveToNext()) {
Categorias categoria = new Categorias();
categoria.setNomeCategoria(cursor.getString(cursor.getColumnIndex(col_NOME_CATEGORIA)));
categorias.add(categoria);
}
}
db.close();
return categorias;
}
Thanks.

That is because your expandable list is HashMap<String, List<String>> expandableListDetail.
HashMaps are unordered i.e. the order in which you put the K,V pairs is not guaranteed to be the same when you are iterating over it.
In your scenario, you need a LinkedHashMap which will preserve the order of K,V pairs.
LinkedHashMap

Related

Not able to show all data fetch from sqlite db into Expandable list view

I am inserting data from .csv file into sqlite database. But when I am fetching data from sqlite & showing it into Expandable list view,it skips some row data and showing in Expandable list view i.e. Some data is missing while showing from sqlite to Expandable list view
Main Activity
` databaseHelper = new DatabaseHelper(this);
listDataHeader = new ArrayList<String>();
childDataHashMap = new HashMap<String, List<ChildInfo>>();
// get the listview
expListView = (ExpandableListView)findViewById(R.id.expandableListView);
//Group data//
Cursor cursor = databaseHelper.getExpandableData();
cursor.moveToFirst();
Log.i(TAG, "cursor.getCount()" + cursor.getCount());
do {
Log.d(TAG,"Category "+ cursor.getString(cursor .getColumnIndex("categorydesc")));
String categoryDescription = cursor.getString(cursor .getColumnIndex("categorydesc"));
int categoryId = cursor.getInt(cursor.getColumnIndex("CategoryId"));
Log.i(TAG, "categoryDescription:" + categoryDescription);
listDataHeader.add(categoryDescription);
//Child data//
Cursor cursorChild = databaseHelper.fetchChildren(categoryId);
List<ChildInfo> childList = new ArrayList<ChildInfo>();
cursorChild.moveToFirst();
while (cursorChild.moveToNext()) {
String businessName = cursorChild.getString(cursorChild .getColumnIndex("BusinessName"));
phoneNumber = cursorChild.getString(cursorChild.getColumnIndex("ph_Phone"));
String landMark = cursorChild.getString(cursorChild.getColumnIndex("LandMark"));
Log.w("", "Category Child " + businessName);
ChildInfo childInfo = new ChildInfo(businessName, phoneNumber,landMark);
childList.add(childInfo);
}
childDataHashMap.put(categoryDescription, childList);
} while (cursor.moveToNext());
cursor.close();
listAdapter = new ExpandableListAdapterNew(this, listDataHeader,childDataHashMap);
// setting list adapter
expListView.setAdapter(listAdapter);
Database Helper
public Cursor fetchGroup() {
String query = "SELECT DISTINCT CategoryId, categorydesc FROM Category ";
Cursor res = db.rawQuery(query, null);
return res;
}
public Cursor getExpandableData() {
String query = "SELECT * FROM Category GROUP BY categorydesc";
return db.rawQuery(query, null);
}
Logcat output
Number of Records(10600): :: 11
MainAcitivity(10600): cursor.getCount()6
Category Hotels
categoryDescription:Hotels
Category Child GoodLuck
Category Restaurants
categoryDescription:Restaurants
Category Child ByThe Way
Category School
categoryDescription:School
Category Child Ornellas
Category Stationary
categoryDescription:Stationary
Category Child Venus
Category super shopee
Actual categories are 6 but it's showing only 5 of them.
Problem in:
cursor.moveToFirst();
Log.i(TAG, "cursor.getCount()"+cursor.getCount());
while (cursor.moveToNext()) // ...
You are move cursor to first item, no gets data for this, move to next.
For child items - same problem.

Key value pairs from sqlite to spinner

Could someone show me the correct way to achieve this.
I have setup a hashmap from a sqlite query as follows
public HashMap<String, String> getData(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_DEVICES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("device_name", cursor.getString(1));
user.put("id", cursor.getString(3));
}
cursor.close();
db.close();
// return user
return user;
}
I then want a spinner where the device names are displayed but when selected its the id that is then used for the next action
I was thinking something like this , but I am not sure exactly how.
private void loadLockScreenSpinner() {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String,String> hm = db.getData();
String device_name = hm.get("device_name");
String id = hm.get("id");
ArrayAdapter<HashMap<String, String>> adapter = new ArrayAdapter<HashMap<String,String>>(this, android.R.layout.simple_spinner_item);
adapter.add(hm);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
devicesSpinner.setAdapter(adapter);
devicesSpinner.setWillNotDraw(false);
}
Not sure what to put in the onItemSelected

Android - SQLite delete and update data not working well

I created database with few tables, got 1 table called friend. A friend has few expenses, some expenses might share with another friend. Now i am trying to delete a friend, what i am trying to do is when the friend share expenses with another friend, the expense of the friend that shared with another friend will then added to another friend and the expense will not deleted. Then, the expenses that are not shared with another friend is directly deleted and will not added to any friend since the friend has many expenses. Now the problem is when i trying to add the expense to another friend, its not working. And i am not getting any error.
Here is my code : i think the problem occur inside if(sharerList.size()>1)...., since the rest of the code works well.
public void deleteFriend(String id) {
Log.d(LOGCAT, "delete");
SQLiteDatabase database = this.getWritableDatabase();
ArrayList<HashMap<String, String>> wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM FriendsExpenses WHERE friendId='" + id + "'";
SQLiteDatabase databaseread = this.getReadableDatabase();
Cursor cursor = databaseread.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("expenseId", cursor.getString(0));
wordList.add(map);
} while (cursor.moveToNext());
}
for (int a=0; a<wordList.size();a++){
HashMap<String, String> ValexpenseId = wordList.get(a);
for (Entry<String, String> entry : ValexpenseId.entrySet()) {
String value = entry.getValue();
String selectQuery2 = "SELECT * FROM FriendsExpenses WHERE expenseId='" + value + "'";
SQLiteDatabase databaseread2 = this.getReadableDatabase();
Cursor cursor2 = databaseread2.rawQuery(selectQuery2, null);
ArrayList<HashMap<String, String>> sharerList = new ArrayList<HashMap<String, String>>();
if (cursor2.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("friendId", cursor2.getString(0));
wordList.add(map);
} while (cursor2.moveToNext());
}
else{};
if (sharerList.size() > 1){
String selectQuery3 = "SELECT expenseTotal FROM expenses WHERE expenseId='" + value + "'";
SQLiteDatabase databaseread3 = this.getReadableDatabase();
Cursor cursor3 = databaseread3.rawQuery(selectQuery3, null);
String expenseTotal = null;
if (cursor3.moveToFirst()) {
do {
expenseTotal = cursor3.getString(cursor3.getColumnIndex("expenseTotal"));
} while (cursor3.moveToNext());
}
for (int b=0; b<sharerList.size();b++){
HashMap<String, String> ValfriendId = sharerList.get(b);
for (Entry<String, String> entry2 : ValfriendId.entrySet()) {
String value2 = entry2.getValue();
String currentSpend = currentSpending(value2);
double currentSpending = (Double.parseDouble(currentSpend));
double expTotal = (Double.parseDouble(expenseTotal));
double newSpending = currentSpending + ((expTotal/sharerList.size()) /sharerList.size()-1);
updateSpending(value2, newSpending);
}
}
}
else
{
String deleteQuery = "DELETE FROM expenses where expenseId='" + value + "'";
Log.d("query", deleteQuery);
database.execSQL(deleteQuery);
}
}
}
String deleteQuery = "DELETE FROM friends where friendId='" + id + "'";
String deleteQuery2 = "DELETE FROM FriendsExpenses where friendId='" + id + "'";
Log.d("query", deleteQuery2);
Log.d("query", deleteQuery);
database.execSQL(deleteQuery2);
database.execSQL(deleteQuery);
}
sharerList is empty because you never add any entries.
There are likely to be other copy/paste errors, such as getString(0) with SELECT *.

Getting the value of the ArrayList<HashMap<String,String>> for display

Hi I just want to know better on how to use this. Since I'm using this kind of method in doing my custom listView now I wanted to apply it since I love the approach on this but I don't know how I should do it. Anyway What I have is a database query where I get all the result from a search query in SQLite Database. Now I'm sure about the content of my query since I already tested it but when I display it the result always return the same output which is the last row of the query. For better understanding here's my code:
public ArrayList<HashMap<String,String>> getList(String search_param){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> hashmap = new HashMap<String,String>();
String query_select = "SELECT column1, column2 FROM tablename WHERE column2 LIKE '%"+ search_param +"%';";
Cursor cursor = db.rawQuery(query_select,null);
if (cursor.moveToFirst()) {
do {
item_list.put("column1", cursor.getString(0));
item_list.put("column2",cursor.getString(1));
list.add(hashmap);
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
now to retrieve the list here's what I tried so far:
ArrayList<HashMap<String,String>> new_list;
DatabaseClass db = new DatabaseClass(getActivity());
new_list = db.getList("");
for(int i=0;i<new_list.size();i++){
HashMap<String,String> content = new HashMap<String, String>();
content = new_list.get(i);
Log.v("The hashmap",content.get("column1").toString());
Log.v("The hashmap",content.get("column2").toString());
}
now the content of my Database should be 1,2,3 for column1 and test1,test2,test3 for column2. but what I get from the result are 3,3,3 and test3,test3,test3
I also tried the method of doing
newlist.get(i).get("column1").toString; but it doesn't even solve the problem.
Any idea on what I should do about this?
Within do while you need to create instance for hashmap,
public ArrayList<HashMap<String,String>> getList(String search_param){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> hashmap;
String query_select = "SELECT column1, column2 FROM tablename WHERE column2 LIKE '%"+ search_param +"%';";
Cursor cursor = db.rawQuery(query_select,null);
if (cursor.moveToFirst()) {
do {
hashMap = new HashMap<String,String>();
hashMap.put("column1", cursor.getString(0));
hashMap.put("column2",cursor.getString(1));
list.add(hashmap);
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
This works like charm with me
public ArrayList<HashMap<String, String>> getList(String search_param){
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
String query_select = "SELECT column1, column2 FROM tablename WHERE column2 LIKE '%"+ search_param +"%';";
Cursor cursor = db.rawQuery(query_select,null);
int colCount = cursor.getColumnCount();
int rowCount = cursor.getCount();
if (cursor.moveToFirst()) {
do {
HashMap<String, String> col = new HashMap<String, String>();
int size =cursor.getColumnCount();
for (int i = 0; i < size; i++) {
col.put(cursor.getColumnName(i), cursor.getString(i));
}
list.add(col);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}

Querying Multiple Fields in a Database

For example, I have this table:
I am using the following method to query from that table:
public ArrayList<ArrayList<String>> getAllViandCategory() {
ArrayList<ArrayList<String>> data2 = new ArrayList<ArrayList<String>>();
ArrayList<String> data = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + "tbl_viand_category";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
data.add(cursor.getString(0));
data.add(cursor.getString(1));
data2.add(data);
} while (cursor.moveToNext());
}
return data2;
}
I am not getting the desired output. I am getting this: [1,Fish,2,Vegetables,3,Meat,4,Rice,5,Etc] instead of [[1,Fish],[2,Vegetables],[3,Meat],[4,Rice],[5,Etc]]
What you have is a List of Lists. The outer list has objects which has lists.
// Code to add a list object into outer list.
data2.add(data);
You will notice that you have created the data object just once. So basically the same object is inserted into data2 again and again.
You need to create a new data object for each iteration.
// New Code
if (cursor.moveToFirst()) {
do {
data = new ArrayList<String>();
data.add(cursor.getString(0));
data.add(cursor.getString(1));
data2.add(data);
} while (cursor.moveToNext());
}
Hope that helps :D

Categories

Resources