Android ExpandableListView get group number when closing group - android

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!

Related

How can i sort ExpandableListview?

I am using one ExpndableListview with two arraylist and one Adapter.
How can I sort both child and parent arraylist data in descending order.
1.parent Arraylist
private List<PhoneNumber> listDataHeader = new ArrayList<>();
2.child list
private HashMap<String, List<SubBalance>> listDataChild = new HashMap<>();
And I am using Adapter code in Activity class as below :
listAdapter = new ExpandableAdapter(getActivity(), listDataHeader, listDataChild, AccountProfileFragment.this);
ExpandableAdapter code
public class ExpandableAdapter extends BaseExpandableListAdapter implements OnClickListener, OnCheckedChangeListener {
private Context context;
private List<PhoneNumber> _listDataHeader;
private HashMap<String, List<SubBalance>> _listDataChild;
private DataSwitchListner listner;
private Activity activity;
private LoadingDialog loading;
public ExpandableAdapter(Activity activity, List<PhoneNumber> listDataHeader, HashMap<String, List<SubBalance>> listChildData, DataSwitchListner listner) {
loading = LoadingDialog.getInstance();
this.context = activity;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
this.listner = listner;
this.activity = activity;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition).getNumber()).get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#SuppressLint("InflateParams")
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.item_exp_child, null);
}
SubBalance account = (SubBalance) getChild(groupPosition, childPosition);
TextView currency = (TextView) convertView.findViewById(R.id.currency);
TextView balance = (TextView) convertView.findViewById(R.id.balance);
TextView expiry = (TextView) convertView.findViewById(R.id.expiry);
TextView days = (TextView) convertView.findViewById(R.id.days);
TextView daysLabel = (TextView) convertView.findViewById(R.id.daysLabel);
TextView lblInfinite = (TextView) convertView.findViewById(R.id.lblInfinite);
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.imgIcon);
ProgressBar progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
LinearLayout llChart = (LinearLayout) convertView.findViewById(R.id.llChart);
if (account != null && account.getCurrencyName() != null && currency != null) {
currency.setText(account.getCurrencyName());
balance.setText(account.getBalance());
String expDateStr = account.getExpiryDate();
Log.e("expDateStr12345",expDateStr);
Date expDate;
if (expDateStr.contains(".")) {
/* expiry.setText(DateUtils.convertFromOldFormatToNewFormat(expDateStr,
DateUtils.FORMAT_1,
DateUtils.FORMAT_4));*/
expiry.setText(DateUtils.convertFromOldFormatToNewFormat(expDateStr,
DateUtils.FORMAT_1,
DateUtils.FORMAT_1));
expDate = DateUtils.convertFromString(expDateStr, DateUtils.FORMAT_1);
LogEvent.Log("ExpandableAdapterdate1", "Phone: " + expDate);
} else {
expiry.setText(DateUtils.convertFromOldFormatToNewFormat(expDateStr,
DateUtils.FORMAT_1_WOD,
DateUtils.FORMAT_1_WOD));
expDate = DateUtils.convertFromString(expDateStr, DateUtils.FORMAT_1_WOD);
LogEvent.Log("ExpandableAdapterdate", "Phone: " + expDate);
}
long daysBetween = DateUtils.daysBetween(new Date(), expDate);
Log.e("expDateStr12345",""+daysBetween);
int progress = 0;
if (daysBetween > 0) {
progress = 100;
if (daysBetween <= 30) {
progress = (int) ((daysBetween / 30.0) * 100);
}
}
days.setTypeface(Methods.getNovaBoldItalic());
Log.e("expDateStr12345",""+days);
if (daysBetween > 100) {
progressBar.setVisibility(View.VISIBLE);
llChart.setVisibility(View.VISIBLE);
lblInfinite.setVisibility(View.INVISIBLE);
//days.setText("NO");
days.setText("No");
daysLabel.setText("VENCE");
progress = 0;
// Log.e("expDateStr12345",""+days);
} else {
progressBar.setVisibility(View.VISIBLE);
llChart.setVisibility(View.VISIBLE);
lblInfinite.setVisibility(View.INVISIBLE);
days.setText(Long.toString(daysBetween));
// Log.e("expDateStr12345",""+days.getText().toString());
}
progressBar.setProgress(progress);
try {
if (account.getIconResource() != null) {
imgIcon.setImageResource(Integer.parseInt(account.getIconResource()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition).getNumber()).size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#SuppressLint("InflateParams")
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
PhoneNumber account = (PhoneNumber) getGroup(groupPosition);
CheckBox cbxIsOn;
FontTextView lblPhoneNumber = null;
TextView lblBalance = null,
lblTarrif = null,
lblBundles = null,
lblReload = null,
lblAddbundle = null,
lblHistory = null;
LinearLayout llHeader = null;
ImageView imgIndicator = null;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.item_exp_parent1, null);
}
cbxIsOn = (CheckBox) convertView.findViewById(R.id.cbxIsOn);
lblPhoneNumber = (FontTextView) convertView.findViewById(R.id.lblPhoneNumber);
lblBalance = (TextView) convertView.findViewById(R.id.lblBalance);
lblTarrif = (TextView) convertView.findViewById(R.id.lblTarrif);
lblBundles = (TextView) convertView.findViewById(R.id.lblBundles);
imgIndicator = (ImageView) convertView.findViewById(R.id.imgIndicator);
llHeader = (LinearLayout) convertView.findViewById(R.id.llHeader);
lblReload = (TextView) convertView.findViewById(R.id.lblReload);
lblAddbundle = (TextView) convertView.findViewById(R.id.lblAddbundle);
lblHistory = (TextView) convertView.findViewById(R.id.lblHistory);
if (isExpanded)
llHeader.setVisibility(View.VISIBLE);
else
llHeader.setVisibility(View.GONE);
if (account.getIsVerified().equalsIgnoreCase("0")) {
cbxIsOn.setEnabled(false);
lblTarrif.setVisibility(View.INVISIBLE);
lblBundles.setVisibility(View.INVISIBLE);
lblBalance.setVisibility(View.INVISIBLE);
} else {
cbxIsOn.setEnabled(true);
lblTarrif.setVisibility(View.VISIBLE);
lblBundles.setVisibility(View.VISIBLE);
lblBalance.setVisibility(View.VISIBLE);
}
lblReload.setTag(groupPosition);
lblAddbundle.setTag(groupPosition);
lblHistory.setTag(groupPosition);
lblReload.setOnClickListener(this);
lblAddbundle.setOnClickListener(this);
lblHistory.setOnClickListener(this);
if (account != null) {
LogEvent.Log("Expandable Adapter", "Phone: " + account.getNumber());
lblPhoneNumber.setText(account.getNumber());
LogEvent.Log("Expandable Adapter", "Plan: " + account.getTariffName());
lblTarrif.setText(account.getTariffName());
LogEvent.Log("Expandable Adapter", "Bundle: " + account.getBundles());
lblBundles.setText(account.getBundles());
if (account.getCacheBalance() != null) {
lblBalance.setText("S/ " + account.getCacheBalance());
}
imgIndicator.setSelected(isExpanded);
cbxIsOn.setOnCheckedChangeListener(null);
cbxIsOn.setChecked(account.isEnabled());
cbxIsOn.setTag(groupPosition);
cbxIsOn.setOnCheckedChangeListener(this);
}
return convertView;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
#Override
public void onClick(final View view) {
final PhoneNumber ph = (PhoneNumber) getGroup((int) view.getTag());
final String phone = ph.getNumber();
LogEvent.Log("Expandable Adapter", "Phone: " + ph.getNumber());
LogEvent.Log("Expandable Adapter", "Phone Id: " + ph.getId());
switch (view.getId()) {
case R.id.lblReload:
SPManager.save(SPManager.KEY_CURRENT_PHONE, phone);
SPManager.save(SPManager.KEY_CURRENT_PHONE_ID, ph.getId());
getBalances(MainActivity.FRAG_RELOAD);
break;
case R.id.lblAddbundle:
SPManager.save(SPManager.KEY_CURRENT_PHONE, phone);
SPManager.save(SPManager.KEY_CURRENT_PHONE_ID, ph.getId());
getBalances(MainActivity.FRAG_PACKAGES);
break;
case R.id.lblHistory:
SPManager.save(SPManager.KEY_CURRENT_PHONE, phone);
SPManager.save(SPManager.KEY_CURRENT_PHONE_ID, ph.getId());
getBalances(MainActivity.FRAG_HISTORY);
break;
default:
break;
}
}
private void getBalances(final int gotoThis) {
String currentPhoneNumber = SPManager.retrive(SPManager.KEY_CURRENT_PHONE);
try {
QueryBuilder<PhoneNumber, Integer> qb = App.getDbHelper().getPhoneNumbersDao().queryBuilder();
qb.where().eq("number", currentPhoneNumber);
PhoneNumber phoneNumber = qb.queryForFirst();
String token = SPManager.retrive(SPManager.KEY_TOKEN);
String subId = SPManager.retrive(SPManager.KEY_CURRENT_PHONE_ID);
MyEndpoint e = new MyEndpoint();
e.setUrl(Urls.BASE_URL_NEW);
RestAdapter.Builder builder = new RestAdapter.Builder();
builder.setEndpoint(e);
if (loading != null && !loading.isShowing()) {
loading.showDialog(context);
}
eLog("Balances: " + Urls.BASE_URL_NEW + Urls.METHOD_BALANCES);
// eLog("Balances: " + Webservices.balance(subId, token));
eLog("Balances: " + Webservices.balance(subId, token));
builder.build().create(RetroClient.class).balancesWb(Webservices.balance(subId, token),
new Callback<BalancesResponse>() {
#Override
public void success(BalancesResponse m, retrofit.client.Response arg1) {
if (loading != null && loading.isShowing()) {
loading.dismissDialog();
}
if (Strings.RESPONSE_SUCCESS.equalsIgnoreCase(m.getCode())) {
Methods.updateCurrentBalanceCurrency(m.getMain().getBalance(), m.getMain().getCurrency());
eLog("Sliding menu go to: " + gotoThis);
((MainActivity) activity).selectSideMenu(gotoThis, true);
} else {
DialogUtil.displayAlert(context,
context.getString(R.string.dialog_title_error),
Strings.getError(m.getError(), context),
context.getString(R.string.dialog_button_ok));
}
}
#Override
public void failure(RetrofitError e) {
eLog("Error from retrofit: " + e.getMessage());
if (loading != null && loading.isShowing()) {
loading.dismissDialog();
}
}
});
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int pos = (int) buttonView.getTag();
PhoneNumber ph = _listDataHeader.get(pos);
_listDataHeader.get(pos).setEnabled(buttonView.isChecked());
listner.onDataSwitched(isChecked, ph.getNumber(), ph.getSubscriberId());
}
public void eLog(String str) {
Log.e("TAG", "" + str);
}
Please help me how can i sort expandableListview data in decending order
Thank you
public static <K, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
Comparator<K> valueComparator = new Comparator<K>() {
public int compare(K k1, K k2) {
int compare = map.get(k2).compareTo(map.get(k1));
if (compare == 0) return 1;
else return compare;
}
};
Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
sortedByValues.putAll(map);
return sortedByValues;
}

Fully displayed listview image is not displaying properly

its my following code.
public class Wishlist extends Activity {
Button checkout;
ListView ListCart;
String name, cusid, ffname, llname, phone, fax, password, email;
String[] qu, s;
int[] g;
int k = 0;
String cost;
ProgressDialog pDialog = null;
List<CartProducts> product_list;
Context ctx;
Integer pos = 0, total = 0, q = 0, gtot = 0, total1 = 0, sum = 0;
SQLiteDatabase FavData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modifywishlist);
Intent page1 = getIntent();
cusid = page1.getStringExtra("cus_id");
ffname = page1.getStringExtra("fname");
llname = page1.getStringExtra("lname");
phone = page1.getStringExtra("ph");
fax = page1.getStringExtra("fax");
password = page1.getStringExtra("password");
email = page1.getStringExtra("email");
ListCart = (ListView) findViewById(R.id.list_item);
pDialog = new ProgressDialog(this);
ctx = this;
FavData = Wishlist.this.openOrCreateDatabase("SHOPPING_CARTFAV", MODE_PRIVATE, null);
FavData.execSQL("CREATE TABLE IF NOT EXISTS fav_items(product_id varchar, name varchar, price varchar, quantity integer, model varchar, image varchar, manufacturer varchar )");
ArrayList<CartProducts> myList = new ArrayList<CartProducts>();
Cursor crsr = FavData.rawQuery("SELECT * FROM fav_items", null);
final String[] productID = new String[crsr.getCount()];
final String[] ProductName = new String[crsr.getCount()];
final String[] ProductPrice = new String[crsr.getCount()];
final String[] ProductQuantity = new String[crsr.getCount()];
final String[] ProductModel = new String[crsr.getCount()];
final String[] ProductImage = new String[crsr.getCount()];
final String[] ProductManufacturer = new String[crsr.getCount()];
int j = 0;
while (crsr.moveToNext()) {
String id = crsr.getString(crsr.getColumnIndex("product_id"));
productID[j] = id;//product_id,name,price,quantity,model,image,manufacturer
name = crsr.getString(crsr.getColumnIndex("name"));
ProductName[j] = name;
String price = crsr.getString(crsr.getColumnIndex("price"));
ProductPrice[j] = price;
String s = ProductPrice[j].toString();
s = s.replace(",", "");
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
part1 = part1.replace("₹", "");
total = Integer.parseInt(part1); // Toast.makeText(Table.this, part1, Toast.LENGTH_SHORT).show();
String qnty = crsr.getString(crsr.getColumnIndex("quantity"));
ProductQuantity[j] = qnty;
String s2 = ProductQuantity[j].toString();
total1 = Integer.parseInt(s2);
sum = total * total1;
String model = crsr.getString(crsr.getColumnIndex("model"));
ProductModel[j] = model;
String image = crsr.getString(crsr.getColumnIndex("image"));
ProductImage[j] = image;
String manufacturer = crsr.getString(crsr.getColumnIndex("manufacturer"));
ProductManufacturer[j] = manufacturer;
//Toast.makeText(getApplicationContext(), productID[j] + "" + ProductName[j] + "" + ProductPrice[j] + "" + ProductQuantity[j] + "" + ProductModel[j] + "" + ProductImage[j] + "" + ProductManufacturer[j], Toast.LENGTH_SHORT).show();
myList.add(new CartProducts(productID[j], ProductName[j], ProductPrice[j], ProductQuantity[j], ProductModel[j], ProductImage[j], ProductManufacturer[j]));
gtot = gtot + sum;
j++;
}
ListCart.setAdapter(new Wishlist_Listadapter(ctx, R.layout.activity_wishlist_cartrow, myList));
getListViewSize(ListCart);
String s1 = ProductPrice.toString();
}
public static void getListViewSize(ListView myListView) {
ListAdapter myListAdapter = myListView.getAdapter();
if (myListAdapter == null) {
//do nothing return null
return;
}
//set listAdapter in loop for getting final size
int totalHeight = 0;
for (int size = 0; size < myListAdapter.getCount(); size++) {
View listItem = myListAdapter.getView(size, null, myListView);
if (listItem != null) {
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
}
//setting listview item in adapter
ViewGroup.LayoutParams params = myListView.getLayoutParams();
if (params != null) {
params.height = totalHeight
+ (myListView.getDividerHeight() * (myListAdapter
.getCount() - 1));
myListView.setLayoutParams(params);
// print height of adapter on log
}
myListView.requestLayout();
// print height of adapter on log
Log.i("height of listItem:", String.valueOf(totalHeight));
}
}
Adapter class
Public class Wishlist_Listadapter extends ArrayAdapter<CartProducts> {
Bitmap bitmap;
ImageView img;
String urll, name,totalps;
SQLiteDatabase FavData;
Integer total = 0, quanty = 1, grandtot = 0, i = 0;
String it;
Button addbtn, minbtn;
EditText editqu;
int total1 = 0, quantity=0, fulltotal = 0, sum;
SQLiteOpenHelper dbhelper;
Wishlist_Listadapter cart = Wishlist_Listadapter.this;
private int resource;
private LayoutInflater inflater;
private Context context;
int count=1 ;
public Wishlist_Listadapter(Context ctx, int resourceId, List<CartProducts> objects) {
super(ctx, resourceId, objects);
resource = resourceId;
inflater = LayoutInflater.from(ctx);
context = ctx;
}
public View getView(int position, View convertView, ViewGroup parent) {
/* create a new view of my layout and inflate it in the row */
convertView = (RelativeLayout) inflater.inflate(resource, null);
final ViewHolder viewholder;
viewholder = new ViewHolder();
final CartProducts banqt = getItem(position);
totalps=(banqt.getPrice());
String s = totalps.toString();
s = s.replace(",", "");
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
part1 = part1.replace("₹", "");// Toast.makeText(getContext(), part1, Toast.LENGTH_LONG).show();
total = Integer.parseInt(part1);
quanty = Integer.parseInt(banqt.getQuantity());
grandtot = total *quanty;
viewholder.total = (TextView) convertView.findViewById(R.id.txt_total);
viewholder.total.setText(String.valueOf(grandtot));
Button delet = (Button) convertView.findViewById(R.id.btn_remove);
delet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*delete function*/
it = banqt.getProduct_id();
FavData = context.openOrCreateDatabase("SHOPPING_CARTFAV", context.MODE_PRIVATE, null);
FavData.execSQL("DELETE FROM fav_items WHERE product_id=" + it + ";");
Intent intent = ((Wishlist) context).getIntent();
((Wishlist) context).finish();
context.startActivity(intent);
}
});
viewholder.txtName = (TextView) convertView.findViewById(R.id.product_name);
viewholder.txtName.setText(banqt.getName());
img = (ImageView) convertView.findViewById(R.id.img_product);
urll = banqt.getImage().toString();
urll = urll.replaceAll(" ", "%20");// Toast.makeText(getContext(),urll,Toast.LENGTH_LONG).show();
new LoadImage().execute(urll);
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView total;
EditText editqu;
TextView txtprice;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if (image != null) {
img.setImageBitmap(image);
// pDialog.dismiss();
} else {
// pDialog.dismiss();
Toast.makeText(getContext(), "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
}
listview is working properly
i just inflate cardview in listview.
when using this code image cannot displaying. only dispaly last image in list view
params.height = totalHeight
+ (myListView.getDividerHeight() * (myListAdapter
.getCount() - 1));
my problem is: In listview only displaying last image
check this image:
Try adding your ImageView to Holder class and use like viewholder.img.setImageBitmap(new LoadImage().execute(urll)) and change the return type to Bitmap
Use BaseAdapter instead of ArrayAdapter. Load and show image with UIL, Picasso or other image loader library.
public class ImageAdapter extends BaseAdapter {
private List<ImageBean> list;
private ArrayList<ImageBean> arraylist;
private LayoutInflater inflater;
public ImageAdapter(Context context, List<ImageBean> list) {
this.list = list;
inflater = LayoutInflater.from(context);
this.arraylist = new ArrayList<>();
}
#Override
public int getCount() {
return list.size();
}
#Override
public ImageBean getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.recycler_view_item, parent, false);
holder.ivImage = (ImageView) convertView.findViewById(R.id.ivImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Loading image with UIL example
ImageLoader.getInstance().displayImage(getItem(position).getUrl(), holder.ivImage, ImageUtils.UIL_USER_AVATAR_DISPLAY_OPTIONS);
return convertView;
}
private class ViewHolder {
public ImageView ivImage;
}
}

Android Custom ArrayAdapter does not take an array

I correctly fill an array? NewsData_data cannot be resolved to a variable.
NewsData NewsData_data[] = new NewsData[]
{
new NewsData(header[i], short_text[i], team[i], datatime[i], photo_url[i])
};
Problem in:
NewsDataAdapter adapter = new NewsDataAdapter(this,
R.layout.news_details, NewsData_data);
NewsData_data cannot be resolved to a variable. How to fix this error?
public void ListDrwaer() {
String[] header;
String[] short_text;
String[] team;
String[] datatime;
String[] photo_url;
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
header[i] = jsonChildNode.optString("header");
short_text[i] = jsonChildNode.optString("short_text");
team[i] = jsonChildNode.optString("team");
datatime[i] = jsonChildNode.optString("datatime");
photo_url[i] = jsonChildNode.optString("photo_url");
NewsData NewsData_data[] = new NewsData[]
{
new NewsData(header[i], short_text[i], team[i], datatime[i], photo_url[i])
};
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(this,
R.layout.news_details, NewsData_data);
View header1 = getActivity().getLayoutInflater().inflate(R.layout.news_details, null);
listView.addHeaderView(header1);
listView.setAdapter(adapter);
}
public class NewsData {
public String header;
public String short_text;
public String team;
public String datatime;
public String photo_url;
public NewsData(){
super();
}
public NewsData(String header,
String short_text,
String team,
String datatime,
String photo_url) {
super();
this.header = header;
this.short_text = short_text;
this.team = team;
this.datatime = datatime;
this.photo_url = photo_url;
}
}
public class NewsDataAdapter extends ArrayAdapter<NewsData>{
Context context;
int layoutResourceId;
NewsData data[] = null;
public NewsDataAdapter(Context context, int layoutResourceId, NewsData[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
NewsDataHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new NewsDataHolder();
holder.img_news = (ImageView)row.findViewById(R.id.img_news);
holder.header = (TextView)row.findViewById(R.id.header);
holder.short_text = (TextView)row.findViewById(R.id.short_text);
holder.team = (TextView)row.findViewById(R.id.team);
holder.datatime = (TextView)row.findViewById(R.id.datatime);
row.setTag(holder);
}
else
{
holder = (NewsDataHolder)row.getTag();
}
NewsData NewsData = data[position];
Picasso.with(context).load(NewsData.photo_url).into(holder.img_news);
holder.header.setText(NewsData.header);
holder.short_text.setText(NewsData.short_text);
holder.team.setText(NewsData.team);
holder.datatime.setText(NewsData.datatime);
return row;
}
class NewsDataHolder
{
ImageView img_news;
TextView header;
TextView short_text;
TextView team;
TextView datatime;
}
}
Problem in:
NewsDataAdapter adapter = new NewsDataAdapter(this,
R.layout.news_details, NewsData_data);
NewsData_data cannot be resolved to a variable
You need to declare your array outside of the try block so that it is visible to the ArrayAdapter constructor.
As corsair922 mentioned, you'll want to declare your NewsData_data array outside your try catch block, otherwise you won't have access to it from outside the block. Additionally, you want to initialize your array once, and populate the array elements as you go as opposed to reinitializing your array each time:
Edit, I would also recommend you spend some time getting familiar with the Java coding conventions. They will make your code easier to maintain/tidier and will allow other people to better understand your code (http://www.oracle.com/technetwork/java/codeconv-138413.html).
public void ListDrwaer() {
String[] header;
String[] short_text;
String[] team;
String[] datatime;
String[] photo_url;
NewsData NewsData_data[];
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
NewsData_data = new NewsData[jsonMainNode.length()];
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
header[i] = jsonChildNode.optString("header");
short_text[i] = jsonChildNode.optString("short_text");
team[i] = jsonChildNode.optString("team");
datatime[i] = jsonChildNode.optString("datatime");
photo_url[i] = jsonChildNode.optString("photo_url");
NewsData_data[i] = new NewsData(header[i], short_text[i], team[i], datatime[i], photo_url[i]);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(this, R.layout.news_details, NewsData_data);
View header1 = getActivity().getLayoutInflater().inflate(R.layout.news_details, null);
listView.addHeaderView(header1);
listView.setAdapter(adapter);
}

Missing data in Section list view in Android?

I am working with Section list view in Android to show Call details according to date.
Means under a particular date number of call details. But when I get 2 calls under the same date, the last date is visible only and the list does not show the rest of the calls of that date.
Calls under different dates are shown correctly but calls under same date are not shown correctly, only the last call is shown.
I am using the below code:
public String response = "{ \"Message\":\"Success\", "
+ "\"Data\":[ { \"ACCOUNT\":\"000014532497\", "
+ "\"DATE\":\"8/6/2006\", \"TIME\":\"15:37:14\", "
+ "\"CH_ITEM\":\"341T\", \"ITEM\":\"TIMEUSED\", "
+ "\"DESCRIPTION\":\"FROM3103475779\", \"DETAIL\":"
+ "\"UnitedKingdom011441980849463\", \"QUANTITY\":84, "
+ "\"RATE\":0.025, \"AMOUNT\":2.1, \"ACTUAL\":83.2, "
+ "\"NODE_NAME\":\"TNT02\", \"USER_NAME\":\"Shailesh Sharma\""
+ ", \"MODULE_NAME\":\"DEBIT\", \"ANI\":\"3103475779\", "
+ "\"DNIS\":\"3103210104\", \"ACCOUNT_GROUP\":\"WEBCC\", "
+ "\"SALES_REP\":\"sascha_d\", \"SALES_REP2\":\"\", \"SALES_REP3"
+ "\":\"\", \"IN_PORT\":\"I10\", \"EXTRA1\":\"RATE\", \"EXTRA2\":"
+ "\"44\", \"EXTRA3\":\"UnitedKingdom\", \"OUT_PORT\":\"I70\", "
+ "\"CRN\":\"WEBCC\", \"CallId\":null, \"ID\":4517734, \"PhoneNumber"
+ "\":\"011441980849463\" }, {\"ACCOUNT\":\"000014532497\",\"DATE\":"
+ "\"8/6/2006\",\"TIME\":\"09:22:57\",\"CH_ITEM\":\"541T\",\"ITEM\":"
+ "\"TIMEUSED\",\"DESCRIPTION\":\"FROM3103475779\",\"DETAIL\":"
+ "\"UnitedKingdom011447914422787\",\"QUANTITY\":1,\"RATE\":0.29,"
+ "\"AMOUNT\":0.29,\"ACTUAL\":0.5,\"NODE_NAME\":\"TNT02\",\"USER_NAME"
+ "\":\"Tusshar\",\"MODULE_NAME\":\"DEBIT\",\"ANI\":\"3103475779\",\"DNIS"
+ "\":\"6173950047\",\"ACCOUNT_GROUP\":\"WEBCC\",\"SALES_REP\":\"sascha_d"
+ "\",\"SALES_REP2\":\"\",\"SALES_REP3\":\"\",\"IN_PORT\":\"I30\",\"EXTRA1"
+ "\":\"RATE\",\"EXTRA2\":\"44\",\"EXTRA3\":\"UnitedKingdom-Special\","
+ "\"OUT_PORT\":\"I90\",\"CRN\":\"WEBCC\",\"CallId\":null,\"ID\":4535675,"
+ "\"PhoneNumber\":\"011447914422787\"}, ], \"NumberOfContacts\":2, "
+ "\"TotalCharges\":4.830000000000001 }";
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if (message != null && message.equalsIgnoreCase("Success")) {
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
for (int i = 0; i < dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
_date = history.getString("DATE");
String updatedDate = createDateFormat(_date);
// notes =new ArrayList<String>();
itemList = new ArrayList<Object>();
// ADDING DATE IN THE ARRAYLIST<String>
days.add(updatedDate);
_username = history.getString("USER_NAME");
_number = history.getString("PhoneNumber");
_time = history.getString("TIME");
_amount = history.getString("AMOUNT");
_duration = history.getString("QUANTITY");
/*
* notes.add(_username); notes.add(_number);
* notes.add(_time);
*/
AddObjectToList(_username, _number, _time, _amount,
_duration);
// listadapter = new <String>(this, R.layout.list_item,
// notes);
listadapter = new ListViewCustomAdapter(this, itemList);
adapter.addSection(days.get(i), listadapter);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class SeparatedListAdapter extends BaseAdapter {
/*
* public final Map<String, Adapter> sections = new
* LinkedHashMap<String, Adapter>();
*/
public final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>();
public final ArrayAdapter<String> headers;
public final static int TYPE_SECTION_HEADER = 0;
public SeparatedListAdapter(Context context) {
headers = new ArrayAdapter<String>(context, R.layout.list_header);
}
public void addSection(String section, Adapter adapter) {
this.headers.add(section);
this.sections.put(section, adapter);
}
public Object getItem(int position) {
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return section;
if (position < size)
return adapter.getItem(position - 1);
// otherwise jump into next section
position -= size;
}
return null;
}
public int getCount() {
// total together all sections, plus one for each section header
int total = 0;
for (Adapter adapter : this.sections.values())
total += adapter.getCount() + 1;
return total;
}
#Override
public int getViewTypeCount() {
// assume that headers count as one, then total all sections
int total = 1;
for (Adapter adapter : this.sections.values())
total += adapter.getViewTypeCount();
return total;
}
#Override
public int getItemViewType(int position) {
int type = 1;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return TYPE_SECTION_HEADER;
if (position < size)
return type + adapter.getItemViewType(position - 1);
// otherwise jump into next section
position -= size;
type += adapter.getViewTypeCount();
}
return -1;
}
public boolean areAllItemsSelectable() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (getItemViewType(position) != TYPE_SECTION_HEADER);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int sectionnum = 0;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return headers.getView(sectionnum, convertView, parent);
if (position < size)
return adapter.getView(position - 1, convertView, parent);
// otherwise jump into next section
position -= size;
sectionnum++;
}
return null;
}
#Override
public long getItemId(int position) {
return position;
}
}
This is my actual requirement:
This is what is happening right now.
SectionListExampleActivity is my Main class in which I am getting RESPONSE from JSON web service. In getJSONResposne method I am calling the EntryAdaptor.
There are two separate geter setter classes for SECTION HEADER and ITEM ENTRY for each header.
public class SectionListExampleActivity extends Activity implements OnClickListener, OnItemSelectedListener, IServerResponse {
/** Called when the activity is first created. */
private ArrayList<Item> items = new ArrayList<Item>();
boolean firstTime = true;
private Spinner _spinner=null;
private ArrayAdapter _amountAdaptor = null;
private ArrayList<String> _monthList =new ArrayList<String>();
private ListView _list=null;
private Button _monthButton=null;
private ImageButton _backImageButton=null;
private ImageButton _headerImageButton=null;
private String _token;
private String _account;
private Point p=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_history);
String response = this.getIntent().getExtras().getString("history_resp");
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
_list = (ListView)findViewById(R.id.listview);
getJSON_Response(response,Constant.PID_ACCOUNT_HISTORY);
EntryAdapter adapter = new EntryAdapter(this, items);
_list.setAdapter(adapter);
_monthList.add("Months");
_monthList.add("January");
_monthList.add("February");
_monthList.add("March");
_monthList.add("April");
_monthList.add("May");
_monthList.add("June");
_monthList.add("July");
_monthList.add("August");
_monthList.add("September");
_monthList.add("October");
_monthList.add("November");
_monthList.add("December");
_spinner = (Spinner)findViewById(R.id.month_spinner);
_amountAdaptor = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item,
_monthList);
_spinner.setAdapter(_amountAdaptor);
_spinner.setOnItemSelectedListener(this);
_monthButton = (Button)findViewById(R.id.monthSpinner_button);
_monthButton.setOnClickListener(this);
_backImageButton = (ImageButton)findViewById(R.id.back_ImageButton);
_backImageButton.setOnClickListener(this);
_headerImageButton =(ImageButton)findViewById(R.id.header_ImageButton);
_headerImageButton.setOnClickListener(this);
}
private void getJSON_Response(String response,int pid) {
switch (pid) {
case Constant.PID_ACCOUNT_HISTORY:
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if(message!=null && message.equalsIgnoreCase("Success")){
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
String lastAddedDate = null;
for (int i = 0; i <dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
String date = history.getString("DATE");
if(firstTime || !(date.equalsIgnoreCase(lastAddedDate))){
firstTime=false;
lastAddedDate = date;
items.add(new SectionItem(date));
}
String username= history.getString("USER_NAME");
String number = history.getString("PhoneNumber");
String time = history.getString("TIME");
String amount=history.getString("AMOUNT");
String duration =history.getString("QUANTITY");
items.add(new EntryItem(username,duration,amount,number,time));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
default:
break;
}
}
#Override
public void onClick(View v) {
if(v==_monthButton){
_spinner.performClick();
}else if(v==_backImageButton){
SectionListExampleActivity.this.finish();
}else if(v== _headerImageButton){
if (p != null)
showPopup(SectionListExampleActivity.this, p);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long arg3) {
if(position!=0){
switch (parent.getId()) {
case R.id.month_spinner:
String selectedItem = _spinner.getSelectedItem().toString();
_monthButton.setBackgroundResource(R.drawable.month_blank);
_monthButton.setText(selectedItem);
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String _historyURL = Constant.prodORdevUrl + "GetAccountHistory?token="+_token+"&account="+_account+"&month="+month+"&year="+year;
getHistory(_historyURL,true);
break;
default:
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
public class EntryAdapter extends ArrayAdapter<Item> implements IServerResponse {
private Context context;
private ArrayList<Item> items;
private LayoutInflater vi;
private String _token;
private String _account;
public EntryAdapter(Context context,ArrayList<Item> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.list_item_section, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
String date =createDateFormat(si.getTitle());
sectionView.setText(date);
}else{
EntryItem ei = (EntryItem)i;
v = vi.inflate(R.layout.list_item_entry, null);
final RelativeLayout relay = (RelativeLayout)v.findViewById(R.id.account_history_item_relay);
final TextView username = (TextView)v.findViewById(R.id.user_name_textview);
final TextView amount = (TextView)v.findViewById(R.id.amount_textview);
final TextView duration = (TextView)v.findViewById(R.id.duration_textview);
final TextView phone = (TextView)v.findViewById(R.id.phone_no_textview);
final TextView time = (TextView)v.findViewById(R.id.time_textview);
relay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
makeCall(phone.getText().toString());
}
});
if (username != null)
username.setText(ei.username);
if(amount != null)
amount.setText(ei.duration + "min");
if(duration != null)
duration.setText("$"+ ei.amount);
if(phone != null)
phone.setText(ei.number);
if(time != null)
time.setText(ei.time);
}
}
return v;
}
void makeCall(String destination) {
if(_token!=null && _account!=null){
if(destination!=null && !destination.equals("")){
String phoneNumber = Constant.getPhoneNumber(this.context.getApplicationContext());
if(phoneNumber!=null && phoneNumber.length()>0){
String callURL =WebService.WEB_SERVICE_URL+"PlaceLongDistanceCall?token="+_token +
"&phonenumber="+phoneNumber+"&destinationNumber="+destination+"&authtoken="+_token;
getCall(callURL,true);
}else{
Constant.showToast(this.context, Constant.INSERT_SIM);
}
}else{
Constant.showToast(this.context, "In valid destination number.");
}
}
}
}

query title column from database and set it to TextView

I had query title column from database and want to set it in TextView in GridView.
How?
CafeDatasource
public List<Model_Insert> findTblCafe(){
List<Model_Insert> model_Inserts = new ArrayList<Model_Insert>();
Cursor cursor = database.query(CafeDbOpenHelper.TABLE_CAFE, rtv_tbl_Cafe,
null, null, null, null, null);
Log.i("number", "return" + cursor.getCount()+ " rows");
if(cursor.getCount() > 0){
while (cursor.moveToNext()) {
Model_Insert model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_ID)));
model_Insert.setCafe_Title(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_TITLE)));
model_Insert.setCafe_Been(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_BEEN)));
model_Insert.setCafe_Want(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_WANT)));
model_Insert.setCafe_Address(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_ADDRESS)));
model_Insert.setCafe_Thumb(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_THUMB)));
model_Insert.setCafe_Description(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_DESCRIPTION)));
model_Insert.setCafe_WifiRate(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_WIFI_RATE)));
model_Insert.setCafe_CoffeeRate(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_COFFEE_RATE)));
model_Insert.setCafe_Latitude(cursor.getDouble(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_LATITUDE)));
model_Insert.setCafe_Longitude(cursor.getDouble(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_LONGITUDE)));
model_Inserts.add(model_Insert);
}
}
return model_Inserts;
}
MainActivity
public ArrayList<HashMap<String, String>> placeList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card);
===============================================================
dataSource = new CafeDataSource(this);
dataSource.open();
List<Model_Insert> model_Inserts = dataSource.findTblCafe();// query database (findTblCafe)
if(model_Inserts.size() == 0){
new DownloadImageTask().execute();
model_Inserts = dataSource.findTblCafe();
}
===============================================================
} // End onCreate
public void ShowAllContent() {
GridView gridView1 = (GridView) findViewById(R.id.grid_all);
gridView1.setAdapter(new ImageAdapter(TopActivity.this, placeList));
}
public class DownloadImageTask extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... params) {
placeList = new ArrayList<HashMap<String,String>>();
JSONParser jParser = new JSONParser();
JSONObject jsonO = jParser.getJSONUrl(url);
try {
places = jsonO.getJSONArray("place");
for (int i = 0; i < places.length(); i++) {
JSONObject jobj = places.getJSONObject(i);
int cafe_id = jobj.getInt(TAG_CAFE_ID);
String cafe_title = jobj.getString(TAG_CAFE_TITLE);
int cafe_been = jobj.getInt(TAG_CAFE_BEEN);
int cafe_want = jobj.getInt(TAG_CAFE_WANT);
String cafe_address = jobj.getString(TAG_CAFE_ADDRESS);
String cafe_thumb = jobj.getString(TAG_CAFE_THUMB);
String cafe_description = jobj.getString(TAG_CAFE_DESCRIPTION);
int cafe_wifi_rate = jobj.getInt(TAG_CAFE_WIFI_RATE);
int cafe_coffee_rate = jobj.getInt(TAG_CAFE_COFFEE_RATE);
double cafe_latitude = jobj.getDouble(TAG_CAFE_LATITUDE);
double cafe_longitude = jobj.getDouble(TAG_CAFE_LONGITUDE);
// Table Save
Model_Insert model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cafe_id);
model_Insert.setCafe_Been(cafe_been);
model_Insert.setCafe_Want(cafe_want);
model_Insert = dataSource.createTableCafeSave(model_Insert);
Log.i("data", " ID " + model_Insert.getCafe_Id());
// Table Cafe
model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cafe_id);
model_Insert.setCafe_Title(cafe_title);
model_Insert.setCafe_Been(cafe_been);
model_Insert.setCafe_Want(cafe_want);
model_Insert.setCafe_Address(cafe_address);
model_Insert.setCafe_Thumb(cafe_thumb);
model_Insert.setCafe_Description(cafe_description);
model_Insert.setCafe_WifiRate(cafe_wifi_rate);
model_Insert.setCafe_CoffeeRate(cafe_coffee_rate);
model_Insert.setCafe_Latitude(cafe_latitude);
model_Insert.setCafe_Longitude(cafe_longitude);
model_Insert = dataSource.createTableCafe(model_Insert);
Log.i("data", " Picture " + model_Insert.getCafe_Id());
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_CAFE_TITLE, cafe_title);
placeList.add(map);
}
// for " piture " Object in json
pictures = jsonO.getJSONArray("pictures");
for (int i = 0; i < pictures.length(); i++) {
JSONObject jObj = pictures.getJSONObject(i);
int cafe_id = jObj.getInt(TAG_CAFE_ID);
String picture_url = jObj.getString(TAG_PICTURE_URL);
// Table Picture
Model_Insert model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cafe_id);
model_Insert.setPitureUrl(picture_url);
model_Insert = dataSource.createTablePicture(model_Insert);
Log.i("pic", " Picture " + model_Insert.getPitureurl());
HashMap<String, String> map = new HashMap<String, String>();
placeList.add(map);
}
} catch (JSONException e) {
// TODO: handle exception
}
return null;
}
protected void onPostExecute(Void unused) {
ShowAllContent(); // When Finish Show Content
}
}
private static class ViewHolder {
public ImageView imageview;
public TextView txtTitle;
}
public class ImageAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String,String>>();
public ImageAdapter(Context c, ArrayList<HashMap<String, String>> myArrayList){
context = c;
MyArr = myArrayList;
}
#Override
public int getCount() {
return MyArr.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View converView, ViewGroup parent) {
ViewHolder viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(converView == null){
converView = inflater.inflate(R.layout.grid_item, null);
}
viewHolder.imageview = (ImageView) converView.findViewById(R.id.imv_card_cafe);
viewHolder.txtTitle = (TextView) converView.findViewById(R.id.txt_title);
/* String str = "frute : juse text";
Integer len;
len = str.length();
if(len > 20){
String result = str.substring(0, 15);
viewHolder.txtTitle.setText(result);
}
else {
viewHolder.txtTitle.setText(str);
} */
=============================================================================
viewHolder.txtTitle.setText(...............................?);
=============================================================================
viewHolder.imageview.setImageResource(mThumb[position]);
return converView;
}
}
because you are getting all titles inside model_Inserts List you will need to pass this List to Custom BaseAdapter for showing in TextView as :
Change ShowAllContent() method as:
public void ShowAllContent() {
GridView gridView1 = (GridView) findViewById(R.id.grid_all);
gridView1.setAdapter(new ImageAdapter(TopActivity.this, placeList,model_Inserts));
}
and ImageAdapter constructor as :
public class ImageAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> MyArr =
new ArrayList<HashMap<String,String>>();
List<Model_Insert> model_Inserts=null;
public ImageAdapter(Context c,
ArrayList<HashMap<String, String>> myArrayList,
List<Model_Insert> model_Inserts){
context = c;
MyArr = myArrayList;
this.model_Inserts=model_Inserts;
}
///your code here...
now use model_Inserts for getting Title to show inside getView

Categories

Resources