I have a listview, which I would like to sort in an alphabetic order. How do I do that?
public class AppDrawer extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
getSupportActionBar().hide();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_drawer);
ListView userInstalledApps = (ListView) findViewById(R.id.installed_app_list);
List<AppList> installedApps = getInstalledApps();
AppAdapter installedAppAdapter = new AppAdapter(this, installedApps);
userInstalledApps.setAdapter(installedAppAdapter);
}
private List<AppList> getInstalledApps() {
List<AppList> res = new ArrayList<AppList>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
if ((isSystemPackage(p) == false)) {
String appName = p.applicationInfo.loadLabel(getPackageManager()).toString();
Drawable icon = p.applicationInfo.loadIcon(getPackageManager());
res.add(new AppList(appName, icon));
}
}
return res;
}
private boolean isSystemPackage(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true : false;
}
You can use comparator for sorting your list. change your getInstalledApps() method as below.
private List<AppList> getInstalledApps() {
List<AppList> res = new ArrayList<AppList>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
if ((isSystemPackage(p) == false)) {
String appName = p.applicationInfo.loadLabel(getPackageManager()).toString();
Drawable icon = p.applicationInfo.loadIcon(getPackageManager());
res.add(new AppList(appName, icon));
}
}
Collections.sort(res, new Comparator<AppList>() {
#Override
public int compare(AppList o1, AppList o2) {
return o1.getAppName().compareTo(o2.getAppName()); // use your getter for getting app name you are setting.
}
});
return res;
}
You can use Comparator for sorting a list.
List<AppList> installedApps = getInstalledApps();
Collections.sort(installedApps , new Comparator<AppList>() {
public int compare(AppList v1, AppList v2) {
return v1.getAppName().compareTo(v2.getAppName());
}
});
Or if you are using Java 8:
list.sort(String::compareToIgnoreCase);
sort method of List interface is mutable operation. Your list will be modified and order property of List will be corrupted better to use Streams of Java 8
List.stream().sorted().collect(Collectors.toList());
pass your Comparator in sorted method and get the list.
Having a object that has 3 properties:
Item
String date;
int value1;
int value2;
I have first ArrayList<Item> listA which contains:
2017-01-18, 0, 0
2017-01-17, 0, 0
2017-01-16, 0, 0
2017-01-15, 0, 0
Second ArrayList<Item> listB which contains:
2017-01-18, 7, 3
2017-01-15, 4, 0
I want to combine both lists, into a final one, having the values summed by same date
2017-01-18, 7, 3
2017-01-17, 0, 0
2017-01-16, 0, 0
2017-01-15, 4, 0
Try this:
public static void sumList(List<Item> list1, List<Item> list2){
List<Item> bigger;
List<Item> smaller;
if(list1.size() > list2.size()){
bigger = list1;
smaller = list2;
} else{
bigger = list2;
smaller = list1;
}
for(int i = 0; i < bigger.size(); i++){
for(int j = 0; j < smaller.size(); j++){
if(bigger.get(i).date.equals(smaller.get(j).date)){
bigger.get(i).value1 = bigger.get(i).value1 + smaller.get(j).value1
bigger.get(i).value2 = bigger.get(i).value2 + smaller.get(j).value2
}
}
}
}
happy coding!
try this
List<Item> firstList = new ArrayList<Item>();
List<Item> secondList = new ArrayList<Item>();
HashMap<String, Item> hashMap = new HashMap<String, Item>();
for(Item item: firstList) {
hashMap.put(item.date, item);
}
for(Item item: secondList) {
Item tempItem = hashMap.get(item.date);
if(tempItem != null) {
tempItem.add(item);
hashMap.put(tempItem.date, tempItem);
} else {
hashMap.put(item.date, item);
}
}
and your item class be like
class Item {
String date;
int value1;
int value2;
public void add(Item item) {
this.value1 = this.value1 + item.value1;
this.value2 = this.value2 + item.value2;
}
}
I Have two String arrays in my application, One containing Country names, and other containing corresponding extension code, But the issue is that the names of countries are not properly ordered in alphabetical order,
public static final String[] m_Countries = {
"---select---", "Andorra", ...., "Zimbabwe"};
public static final String[] m_Codes = {
"0", "376",...., "263"};
These are the arrays,
So my question is, is there any way to sort the first array such that the second array also changes to corresponding position without writing my own code?
If not, what's the best sort method i can use for these arrays?
Any kind of help will be greatly appreciated.
Form TreeMap from your array and all your data get sort. After that fill your respective array with Key and Values.
TreeMap<String, String> map = new TreeMap<>();
int length = m_Countries.length;
for(int i=0;i<length;i++){
map.put(m_Countries[i], m_Codes[i]);
}
String[] countries = map.keySet().toArray(new String[map.keySet().size()]);
System.out.println("Country:"+Arrays.toString(countries));
String[] codes = map.values().toArray(new String[map.values().size()]);
System.out.println("Codes:"+Arrays.toString(codes));
Result:
Country:[---select---, Afghanistan, ..., Zimbabwe]
Codes:[0, 93,.... , 263]
Method 1.
You can create a hashMap to store the original country to code.
private void handle(String[] m_Countries, String[] m_Codes, Map<String, String> map) {
if (m_Codes == null || m_Countries == null || map == null) {
return;
}
//
final int codeCount = m_Codes.length;
final int countryCount = m_Countries.length;
final int count = Math.min(codeCount, countryCount);
for (int i = 0; i < count; i++) {
map.put(m_Countries[i], m_Codes[i]);
}
// TODO sort
// get code by country name by map.get(country)
}
Method 2.
You can make a List of pairs which contains country and code. Then sort the list.
private List<Pair<String, String>> sortCountryWithCode(String[] m_Countries, String[] m_Codes) {
if (m_Codes == null || m_Countries == null) {
return null;
}
//
final int codeCount = m_Codes.length;
final int countryCount = m_Countries.length;
final int count = Math.min(codeCount, countryCount);
if (count == 0) {
return null;
}
// generate a list
List<Pair<String, String>> list = new ArrayList<>();
for (int i = 0; i < count; i++) {
list.add(new Pair<String, String>(m_Countries[i], m_Codes[i]));
}
// sort
Collections.sort(list, new Comparator<Pair<String, String>>() {
#Override
public int compare(Pair<String, String> lhs, Pair<String, String> rhs) {
return lhs.first.compareToIgnoreCase(rhs.first);
}
});
return list;
}
code with love. :)
I have to store and manage a volume list in the format:
"100 ml", "200 ml", "300 ml"...
I'm using the SharedPreferences with JSON to store this everytime the list is changed.
I want the list to be ordered, so 100 < 1000, but it is showing like 1000 and 2000 before 300.
Here is my comparator:
mVolumeComparator = new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
int volume1 = Integer.parseInt(s1.replace(" ml", ""));
int volume2 = Integer.parseInt(s2.replace(" ml", ""));
if (volume1 > volume2) {
return 1;
} else if (volume2 > volume1) {
return -1;
} else {
return 0;
}
}
};
And here is my get method:
public static ArrayList<String> getVolumesFromPreference(Context ctx) {
if (!ctx.getSharedPreferences(KEY_SHARED_PREFERENCES, MODE_PRIVATE).contains(KEY_VOLUMES_BUNDLE)) {
startDefaultVolumes(ctx, KEY_VOLUMES_BUNDLE);
}
try {
JSONArray jsonArray = new JSONArray(ctx.getSharedPreferences(KEY_SHARED_PREFERENCES, MODE_PRIVATE).getString(KEY_VOLUMES_BUNDLE, null));
ArrayList<String> lista = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
lista.add(jsonArray.getString(i));
}
Collections.sort(lista, mVolumeComparator);
return lista;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
private static void startDefaultVolumes(Context ctx, String key_bundle) {
JSONArray jsonArray = new JSONArray();
jsonArray.put("269 ml");
jsonArray.put("350 ml");
jsonArray.put("473 ml");
jsonArray.put("550 ml");
jsonArray.put("600 ml");
SharedPreferences.Editor editor = ctx.getSharedPreferences(KEY_SHARED_PREFERENCES, MODE_PRIVATE).edit();
editor.putString(key_bundle, jsonArray.toString());
editor.commit();
}
use Integer.valueOf() method instead Integer.parceInt()
I will recommend you to store only the value "100", "1000", "300" and UNIT if you have more than unit available.
SO, you can order it just with a normal Integer comparator, and then apply the "ml" suffix at runtime
Try this code for sorting arraylist in ascending order.
ArrayList<int> lista = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
lista.add(Integer.parseInt(jsonArray.getString(i)));
}
Collections.sort(lista , new Comparator<Integer >() {
#Override
public int compare(Integer lhs, Integer rhs) {
return Integer.valueOf(lhs).compareTo(Integer.valueOf(rhs));
}
});
I want to handle onclick on groups of a custom ExpandableListView. With this code I am getting the number of group when clicking on it:
exList.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
Log.i("group position", groupPosition + "");
return false;
}
});
I am adding the simplified code. I hope you can figure out what the problem might be:
public class ProductLists extends Activity {
private static final String G_TEXT = "G_TEXT";
private static final String C_TITLE = "C_TITLE";
private static final String C_TEXT = "C_TEXT";
private static final String C_CB = "C_CB";
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
List<Map<String, Boolean>> groupCheckBox = new ArrayList<Map<String,Boolean>>();
List<List<Map<String, Boolean>>> childCheckBox = new ArrayList<List<Map<String,Boolean>>>();
String loadedexpanded;
String upperString;
int number, k_num, k_num2;
String etext_newitem;
EditText et_newitem;
String CheckedItem;
String CheckedItems;
ExpandBaseAdapter adapter;
ExpandableListView exList;
HotOrNot info;
ArrayList<String> grpsfav = new ArrayList<String>();
ArrayList<String> OftenUsedAll = new ArrayList<String>();
ArrayList<String> OftenUsedID = new ArrayList<String>();
ArrayList<String> OftenUsedName = new ArrayList<String>();
ArrayList<String> OftenUsedNumber = new ArrayList<String>();
Button sqlExp, sqlAdd;
ArrayList<String> PRLists = new ArrayList<String>();
ArrayList<String> PRListsR = new ArrayList<String>();
ArrayList<String> PRListsID = new ArrayList<String>();
ArrayList<String> PRLists2 = new ArrayList<String>();
ArrayList<String> todoItems = new ArrayList<String>();
ArrayList<String> todoItemsID = new ArrayList<String>();
ArrayList<String> todoItemsNAME = new ArrayList<String>();
List<String> usable_chars = Arrays.asList(";", "'", "/", "\"", "%", "'\'", "$", "+", "-", "=", ":", "_");
ArrayList<String> todoItemsTEMP = new ArrayList<String>();
ArrayList<String> todoItemsIDTEMP = new ArrayList<String>();
ArrayList<String> todoItemsNAMETEMP = new ArrayList<String>();
ArrayList<String> inners = new ArrayList<String>();
ArrayList result2;
Button sqlView, sqlValami;
Cursor c, c2;
String newlistname, modifiedlistname;
String loadedCapital, loadedshowhints;
SharedPreferences sharedPreferences;
ExpandableListView expandlist;
DisplayMetrics metrics;
int width;
List<String> selectionList = Arrays.asList("Rename", "Delete");
List<String> selectionListA = Arrays.asList("Add item", "Rename group", "Delete group");
CharSequence[] selectionList2, selectionList2A;
String rowIdtobemodified, rowIDtobedeleted;
int groupPosition;
int childPosition;
AlertDialog.Builder builder;
Dialog dialog_newitem, dialog_newgroup;
Dialog dialog_renamelist, dialog_deletelist;
EditText et_renamelist, et_deletelist;
//String etext_renamelist, etext_deletelist;
String renamelist_name, deletelist_name;
Spinner SPProductLists3, SPProductLists32;
Button btn_rename_save, btn_rename_cancel, btn_delete_save, btn_delete_cancel;
String allerrors_newproductlistdialog;
ArrayList<String> errors_addgroup = new ArrayList<String>();
String selected_item_from_lists_torename, selected_item_from_lists_torename2;
List<String> nonusable_chars = Arrays.asList(";", "'", "/", "\"", "%", "'\'", "$", "+", "-", "=", ":", "_");
int max;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_productlists3);
exList = (ExpandableListView) findViewById(R.id.layoutExListView);
info = new HotOrNot(this);
info.open();
//----------------------------query tables--------------------------------
c = info.showAllTables();
if (c.moveToFirst())
{
do{
PRLists.add(c.getString(0));
}while (c.moveToNext());
}
if (PRLists.size() >= 0)
{
for (int i=0; i<PRLists.size(); i++)
{
Log.d("PRLists(" + i + ")", PRLists.get(i) + "");
}
}
//Declare base adapter
max = 0;
for (int i = 0; i < PRLists.size(); i++)
{
Map<String, String> curGroupMap = new HashMap<String, String>();
groupData.add(curGroupMap);
curGroupMap.put(G_TEXT, PRLists.get(i).replaceAll("_", " ").substring(2, PRLists.get(i).replaceAll("_", " ").length()));
List<Map<String, String>> children = new ArrayList<Map<String, String>>();
if (!PRLists.get(i).equals("PR_Often_Used"))
{
Log.i("tabla", PRLists.get(i) + "");
c2 = info.getAllTitlesPRtables(PRLists.get(i));
if (c2.moveToFirst())
{
do{
Map<String, String> curChildMap = new HashMap<String, String>();
children.add(curChildMap);
curChildMap.put(C_TITLE, c2.getString(1).replaceAll("_", " "));
curChildMap.put(C_TEXT, "Child ");
}while (c2.moveToNext());
}
}
else
{
Log.i("tabla", "PR_OFTEN_USED");
c2 = info.getAllTitlesOftenUsed("PR_Often_Used");
if (c2.moveToFirst())
{
do{
Map<String, String> curChildMap = new HashMap<String, String>();
children.add(curChildMap);
curChildMap.put(C_TITLE, c2.getString(1).replaceAll("_", " "));
curChildMap.put(C_TEXT, "Child ");
}while (c2.moveToNext());
}
}
if (children.size() > max)
{
max = children.size();
}
childData.add(children);
}
info.close();
for ( int i = 0; i < PRLists.size(); i++) {
List<Map<String, Boolean>> childCB = new ArrayList<Map<String,Boolean>>();
for (int j = 0; j < max; j++) { //leghosszabb belso lista merete
Map<String, Boolean> curCB = new HashMap<String, Boolean>();
childCB.add(curCB);
curCB.put(C_CB, false);
}
childCheckBox.add(childCB);
}
adapter = new ExpandBaseAdapter(ProductLists.this,
groupData, childData, groupCheckBox, childCheckBox);
exList = (ExpandableListView) findViewById(R.id.layoutExListView);
exList.setAdapter(adapter);
exList.setGroupIndicator(null);
exList.setDivider(null);
int groupCount = adapter.getGroupCount();
for (int i = 0; i < groupCount; i++) {
exList.collapseGroup(i);
}
exList.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
CheckBox checkBox = (CheckBox) v.findViewById(R.id.multiple_checkbox);
checkBox.toggle();
if (childCheckBox.get(groupPosition).get(childPosition).get(C_CB)) //ha itt hiba akkor azert van m az adapterben akkor allitok cb statuszt ha van children, es mivel ha nincs akkor ez ertelmezhetetlen
{
childCheckBox.get(groupPosition).get(childPosition).put(C_CB, false);
}
else {
childCheckBox.get(groupPosition).get(childPosition).put(C_CB, true);
}
return false;
}
});
exList.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
//Log.i("group position", groupPosition + "");
Toast.makeText(ProductLists.this, "group position" + groupPosition, Toast.LENGTH_SHORT).show();
Log.i("PRLists.get(groupPosition)", PRLists.get(groupPosition));
if (PRLists.get(groupPosition).equals("PR_Often_Used"))
{
}
return false;
}
});
exList.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
groupPosition = ExpandableListView.getPackedPositionGroup(id);
childPosition = ExpandableListView.getPackedPositionChild(id);
selectionList2 = selectionList.toArray(new CharSequence[selectionList.size()]);
builder = new AlertDialog.Builder(ProductLists.this);
builder.setItems(selectionList2, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, final int item)
{
if (selectionList2[item].equals("Rename"))
{
}
if (selectionList2[item].equals("Delete"))
{
}
}
});
builder.show();
return true;
}
else if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
groupPosition = ExpandableListView.getPackedPositionGroup(id);
Log.i("tablagrp", PRLists.get(groupPosition) + "-" + groupPosition);
selectionList2A = selectionListA.toArray(new CharSequence[selectionListA.size()]);
builder = new AlertDialog.Builder(ProductLists.this);
builder.setItems(selectionList2A, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, final int item)
{
if (selectionList2A[item].equals("Add item"))
{
}
else if (selectionList2A[item].equals("Rename group"))
{
}
else if (selectionList2A[item].equals("Delete group"))
{
}
}
});
builder.show();
return true;
}
return false;
}
});
}
public void refreshList() {
if (PRLists.size() >= 0) {
PRLists.clear();
PRListsID.clear();
}
groupData.clear();
childData.clear();
groupCheckBox.clear();
childCheckBox.clear();
info = new HotOrNot(this);
info.open();
//----------------------------query tables--------------------------------
c = info.showAllTables();
if (c.moveToFirst())
{
do{
PRLists.add(c.getString(0));
}while (c.moveToNext());
}
if (PRLists.size() >= 0)
{
for (int i=0; i<PRLists.size(); i++)
{
Log.d("PRLists(" + i + ")", PRLists.get(i) + "");
}
}
ExpandBaseAdapter adapter = new ExpandBaseAdapter(ProductLists.this, groupData, childData, groupCheckBox, childCheckBox);
ExpandableListView exList = (ExpandableListView) findViewById(R.id.layoutExListView);
exList.setAdapter(adapter);
max = 0;
for (int i = 0; i < PRLists.size(); i++)
{
Map<String, String> curGroupMap = new HashMap<String, String>();
groupData.add(curGroupMap);
curGroupMap.put(G_TEXT, PRLists.get(i).replaceAll("_", " ").substring(2, PRLists.get(i).replaceAll("_", " ").length()));
ArrayList parent = new ArrayList();
List<Map<String, String>> children = new ArrayList<Map<String, String>>();
ArrayList child = new ArrayList();
c2 = info.getAllTitlesPRtables(PRLists.get(i));
if (c2.moveToFirst())
{
do{
Map<String, String> curChildMap = new HashMap<String, String>();
children.add(curChildMap);
curChildMap.put(C_TITLE, c2.getString(1).replaceAll("_", " "));
curChildMap.put(C_TEXT, "Child ");
}while (c2.moveToNext());
}
if (children.size() > max) {
max = children.size();
}
childData.add(children);
}
info.close();
for ( int i = 0; i < PRLists.size(); i++) {
List<Map<String, Boolean>> childCB = new ArrayList<Map<String,Boolean>>();
for (int j = 0; j < max; j++) {
Map<String, Boolean> curCB = new HashMap<String, Boolean>();
childCB.add(curCB);
curCB.put(C_CB, false);
}
childCheckBox.add(childCB);
}
adapter.notifyDataSetChanged();
//expand only those groups that was expanded by the user
for (int i = 0; i < grpsfav.size(); i++) {
Log.i("grpsfav items", grpsfav.get(i));
exList.expandGroup(Integer.valueOf(grpsfav.get(i)));
}
}
//the Holder class-------------------------------------------------------------------
static class ViewHolder {
TextView cTitle;
// TextView cText;
CheckBox checkBox;
}
public class ExpandBaseAdapter extends BaseExpandableListAdapter {
String loadedFontSize, loadedFontType, loadedConfDel, loadedshowhints;
SharedPreferences sharedPreferences;
Context mContext;
private static final String G_TEXT = "G_TEXT";
//private static final String G_CB = "G_CB";
private static final String C_TITLE = "C_TITLE";
private static final String C_TEXT = "C_TEXT";
private static final String C_CB = "C_CB";
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
List<Map<String, Boolean>> groupCheckBox = new ArrayList<Map<String,Boolean>>();
List<List<Map<String, Boolean>>> childCheckBox = new ArrayList<List<Map<String,Boolean>>>();
private Context context;
ViewHolder holder;
public ExpandBaseAdapter(Context context,
List<Map<String, String>> groupData, List<List<Map<String, String>>> childData,
List<Map<String, Boolean>> groupCheckBox, List<List<Map<String, Boolean>>> childCheckBox) {
this.groupData = groupData;
this.childData = childData;
this.groupCheckBox = groupCheckBox;
this.childCheckBox = childCheckBox;
this.context = context;
mContext = context;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.groupitem, null);
}
TextView title = (TextView) view.findViewById(R.id.groupText);
title.setText(getGroup(groupPosition).toString());
ImageView image = (ImageView) view.findViewById(R.id.groupBox);
if (isExpanded) {
image.setBackgroundResource(R.drawable.expander_ic_maximized);
}
else {
image.setBackgroundResource(R.drawable.expander_ic_minimized);
}
return view;
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public Object getGroup(int groupPosition) {
return groupData.get(groupPosition).get(G_TEXT).toString();
}
public int getGroupCount() {
return groupData.size();
}
// **************************************
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null)
{
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.childitem, null);
holder = new ViewHolder();
holder.cTitle = (TextView) convertView.findViewById(R.id.child_title);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.multiple_checkbox);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.cTitle.setText(childData.get(groupPosition).get(childPosition).get(C_TITLE).toString());
if (getChildrenCount(groupPosition) > 0) {
Log.i("chlrden", getChildrenCount(groupPosition) + "");
holder.checkBox.setChecked(childCheckBox.get(groupPosition).get(childPosition).get(C_CB));
}
return convertView;
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public Object getChild(int groupPosition, int childPosition) {
return childData.get(groupPosition).get(childPosition).get(C_TITLE).toString();
}
public int getChildrenCount(int groupPosition) {
return childData.get(groupPosition).size();
}
// **************************************
public boolean hasStableIds() {
return true;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
public void SaveExpanded(String key, String value){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public void LoadExpanded(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
loadedexpanded = sharedPreferences.getString("expand", "false");
}
}
However, when I click it again, the group closes, BUT i don't get the group number. I only get it, when I open a group.
If I use
exList.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
if (groupPosition > 0){
return true;
}
return false;
}
});
I get the group number both times, but then the groups are not opening.
Any ideas?
In onCreate() your setting up your ExpListView (findViewById, adapter, group/child listener etc.). But in refresh() your setting up your ExpListView without setting the listener...you only call findViewById and set the adapter. You have to do the same like youd did in onCreate().
However I don't think it's neccessary that you "reinitialize" your ExpListView in refresh() and you should probably review your code. If you want to I would suggest that you define your ExpListView as member variable and in refresh you remove the line
ExpandableListView exList = (ExpandableListView) findViewById(R.id.layoutExListView);
in your refresh method
However the onGroupClickListener is not working properly, I have found another solution. I used setOnGroupExpandListener and setOnGroupCollapseListener and they are working magically!