Update Activity list in Android after deleting element - android

I've a problem, obviously!
I need to refresh the content called by a TabHost after having deleted an element (It's a favorite page and I gave the user the possibility to eliminate the favorite he desired), How can I do that?
Here is the code (The row is in an expandable list view) of the Favourite page.
package it.sii.android.jobaroundu;
public class Preferiti extends ExpandableListActivity{
//Initialize variables
private static final String STR_CHECKED = " has Checked!";
private static final String STR_UNCHECKED = " has unChecked!";
private int ParentClickStatus=-1;
private int ChildClickStatus=-1;
//aggiustare creando la classe annunci_parent e annunci_child
private ArrayList<Parent> pref=new ArrayList<Parent>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyDBHelper dbHelper = new MyDBHelper(this,"JobAroundU_DB", null, 1);
SQLiteDatabase db=dbHelper.getWritableDatabase();
Resources res = this.getResources();
Drawable devider = res.getDrawable(R.drawable.line);
// Set ExpandableListView values
getExpandableListView().setGroupIndicator(null);
getExpandableListView().setDivider(devider);
getExpandableListView().setChildDivider(devider);
getExpandableListView().setDividerHeight(1);
registerForContextMenu(getExpandableListView());
//RECUPERO RICERCHE RECENTI
String sqlSavedPreferences="SELECT * FROM MyPreferences";
Cursor cursor = db.rawQuery(sqlSavedPreferences, null);
//creo padre e aggiungo ad esso le info
while (cursor.moveToNext()){
Parent p= new Parent();
p.setPosizione(cursor.getString(1));
p.setAzienza(cursor.getString(2));
p.setId(cursor.getString(4));
Log.i("Parent ID", p.getId());
Child cp = new Child();
cp.setDescrizione(cursor.getString(3));
p.setChildren(new ArrayList<Child>());
p.getChildren().add(cp);
pref.add(p);
}
db.close();
cursor.close();
//se parents e' vuoto --> messaggio errore --> non esistono preferiti salvati
if (pref.isEmpty()) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.immagine);
image.setImageDrawable(getResources().getDrawable(R.drawable.icon_25761));
TextView text = (TextView) layout.findViewById(R.id.ToastTV);
text.setText("Non ci sono preferiti da visualizzare!!!");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
String n = getIntent().getStringExtra(getPackageName()+".Username");
Intent i = new Intent(this, PersonalPage.class);
i.putExtra(getPackageName()+".Username", n);
startActivity(i);
}
if (this.getExpandableListAdapter() == null) {
//Create ExpandableListAdapter Object
final MyExpandableListAdapter mAdapter = new MyExpandableListAdapter();
// Set Adapter to ExpandableList Adapter
this.setListAdapter(mAdapter);
}
else
{
// Refresh ExpandableListView data
((MyExpandableListAdapter)getExpandableListAdapter()).notifyDataSetChanged();
}
}
private class MyExpandableListAdapter extends BaseExpandableListAdapter{
private LayoutInflater inflater;
//protected SQLiteOpenHelper dbHelper2 =new MyDBHelper(PaginaRisultati.this,"JobAroundU_DB", null, 1);
public MyExpandableListAdapter(){
// Create Layout Inflator
inflater = LayoutInflater.from(Preferiti.this);
}
// This Function used to inflate parent rows view
#Override
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parentView){
final Parent parent = pref.get(groupPosition);
// Inflate grouprow.xml file for parent rows
convertView = inflater.inflate(R.layout.grouprow_pref, parentView, false);
// Get grouprow.xml file elements and set values
((TextView) convertView.findViewById(R.id.text1)).setText(parent.getPosizione());
((TextView) convertView.findViewById(R.id.TVAzienda)).setText(parent.getAzienda());
ImageView image=(ImageView)convertView.findViewById(R.id.image_tag);
image.setImageResource(R.drawable.yellow_star);
ImageButton bin = (ImageButton)convertView.findViewById(R.id.imageButton_bin);
bin.setFocusable(false);
bin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(final View v) {
AlertDialog.Builder alt_bld = new AlertDialog.Builder(Preferiti.this);
alt_bld.setMessage("Sei sicuro di voler eliminare l'utente dai preferiti?")
.setCancelable(false)
.setPositiveButton("Si", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
MyDBHelper dbHelper2 = new MyDBHelper(Preferiti.this,"JobAroundU_DB", null, 1);
SQLiteDatabase db2=dbHelper2.getWritableDatabase();
String sqlDelete = "DELETE FROM MyPreferences WHERE idDBJobs="+parent.getId()+";";
db2.execSQL(sqlDelete);
db2.close();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("CANCELLARE QUESTO PREFERITO?");
// Icon for AlertDialog
alert.setIcon(R.drawable.trash_empty);
alert.show();
//elimino il preferito dal db
Log.i("DELETING", "I'm deleting "+parent.getId()+" Position: "+parent.getPosizione());
}
});
return convertView;
}
// This Function used to inflate child rows view
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parentView){
final Parent parent = pref.get(groupPosition);
final Child child = parent.getChildren().get(childPosition);
// Inflate childrow.xml file for child rows
convertView = inflater.inflate(R.layout.childrow_pref, parentView, false);
// Get childrow.xml file elements and set values
/***DESCRIZIONE***/
((TextView) convertView.findViewById(R.id.TVDescrizione)).setText(child.getDescrizione());
ImageView image=(ImageView)convertView.findViewById(R.id.image_tag);
image.setImageResource(R.drawable.icon_16301);
return convertView;
}
#Override
public Object getChild(int groupPosition, int childPosition)
{
//Log.i("Childs", groupPosition+"= getChild =="+childPosition);
return pref.get(groupPosition).getChildren().get(childPosition);
}
//Call when child row clicked
#Override
public long getChildId(int groupPosition, int childPosition)
{
/****** When Child row clicked then this function call *******/
if( ChildClickStatus!=childPosition)
{
ChildClickStatus = childPosition;
}
return childPosition;
}
#Override
public int getChildrenCount(int groupPosition)
{
int size=0;
if(pref.get(groupPosition).getChildren()!=null)
size = pref.get(groupPosition).getChildren().size();
return size;
}
#Override
public Object getGroup(int groupPosition)
{
Log.i("Parent", groupPosition+"= getGroup ");
return pref.get(groupPosition);
}
#Override
public int getGroupCount()
{
return pref.size();
}
//Call when parent row clicked
#Override
public long getGroupId(int groupPosition)
{
ParentClickStatus=groupPosition;
if(ParentClickStatus==0)
ParentClickStatus=-1;
return groupPosition;
}
#Override
public void notifyDataSetChanged()
{
// Refresh List rows
super.notifyDataSetChanged();
}
#Override
public boolean isEmpty()
{
return ((pref == null) || pref.isEmpty());
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return true;
}
/******************* Checkbox Checked Change Listener ********************/
private final class CheckUpdateListener implements OnCheckedChangeListener
{
private final Parent parent;
private CheckUpdateListener(Parent parent)
{
this.parent = parent;
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
Log.i("onCheckedChanged", "isChecked: "+isChecked);
parent.setChecked(isChecked);
((MyExpandableListAdapter)getExpandableListAdapter()).notifyDataSetChanged();
final Boolean checked = parent.isChecked();
}
}
/***********************************************************************/
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
}
}
and here the code of the TabHost.
package it.sii.android.jobaroundu;
public class Preferiti extends ExpandableListActivity{
//Initialize variables
private static final String STR_CHECKED = " has Checked!";
private static final String STR_UNCHECKED = " has unChecked!";
private int ParentClickStatus=-1;
private int ChildClickStatus=-1;
//aggiustare creando la classe annunci_parent e annunci_child
private ArrayList<Parent> pref=new ArrayList<Parent>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyDBHelper dbHelper = new MyDBHelper(this,"JobAroundU_DB", null, 1);
SQLiteDatabase db=dbHelper.getWritableDatabase();
Resources res = this.getResources();
Drawable devider = res.getDrawable(R.drawable.line);
// Set ExpandableListView values
getExpandableListView().setGroupIndicator(null);
getExpandableListView().setDivider(devider);
getExpandableListView().setChildDivider(devider);
getExpandableListView().setDividerHeight(1);
registerForContextMenu(getExpandableListView());
//RECUPERO RICERCHE RECENTI
String sqlSavedPreferences="SELECT * FROM MyPreferences";
Cursor cursor = db.rawQuery(sqlSavedPreferences, null);
//creo padre e aggiungo ad esso le info
while (cursor.moveToNext()){
Parent p= new Parent();
p.setPosizione(cursor.getString(1));
p.setAzienza(cursor.getString(2));
p.setId(cursor.getString(4));
Log.i("Parent ID", p.getId());
Child cp = new Child();
cp.setDescrizione(cursor.getString(3));
p.setChildren(new ArrayList<Child>());
p.getChildren().add(cp);
pref.add(p);
}
db.close();
cursor.close();
//se parents e' vuoto --> messaggio errore --> non esistono preferiti salvati
if (pref.isEmpty()) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.immagine);
image.setImageDrawable(getResources().getDrawable(R.drawable.icon_25761));
TextView text = (TextView) layout.findViewById(R.id.ToastTV);
text.setText("Non ci sono preferiti da visualizzare!!!");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
String n = getIntent().getStringExtra(getPackageName()+".Username");
Intent i = new Intent(this, PersonalPage.class);
i.putExtra(getPackageName()+".Username", n);
startActivity(i);
}
if (this.getExpandableListAdapter() == null) {
//Create ExpandableListAdapter Object
final MyExpandableListAdapter mAdapter = new MyExpandableListAdapter();
// Set Adapter to ExpandableList Adapter
this.setListAdapter(mAdapter);
}
else
{
// Refresh ExpandableListView data
((MyExpandableListAdapter)getExpandableListAdapter()).notifyDataSetChanged();
}
}
private class MyExpandableListAdapter extends BaseExpandableListAdapter{
private LayoutInflater inflater;
//protected SQLiteOpenHelper dbHelper2 =new MyDBHelper(PaginaRisultati.this,"JobAroundU_DB", null, 1);
public MyExpandableListAdapter(){
// Create Layout Inflator
inflater = LayoutInflater.from(Preferiti.this);
}
// This Function used to inflate parent rows view
#Override
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parentView){
final Parent parent = pref.get(groupPosition);
// Inflate grouprow.xml file for parent rows
convertView = inflater.inflate(R.layout.grouprow_pref, parentView, false);
// Get grouprow.xml file elements and set values
((TextView) convertView.findViewById(R.id.text1)).setText(parent.getPosizione());
((TextView) convertView.findViewById(R.id.TVAzienda)).setText(parent.getAzienda());
ImageView image=(ImageView)convertView.findViewById(R.id.image_tag);
image.setImageResource(R.drawable.yellow_star);
ImageButton bin = (ImageButton)convertView.findViewById(R.id.imageButton_bin);
bin.setFocusable(false);
bin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(final View v) {
AlertDialog.Builder alt_bld = new AlertDialog.Builder(Preferiti.this);
alt_bld.setMessage("Sei sicuro di voler eliminare l'utente dai preferiti?")
.setCancelable(false)
.setPositiveButton("Si", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
MyDBHelper dbHelper2 = new MyDBHelper(Preferiti.this,"JobAroundU_DB", null, 1);
SQLiteDatabase db2=dbHelper2.getWritableDatabase();
String sqlDelete = "DELETE FROM MyPreferences WHERE idDBJobs="+parent.getId()+";";
db2.execSQL(sqlDelete);
db2.close();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("CANCELLARE QUESTO PREFERITO?");
// Icon for AlertDialog
alert.setIcon(R.drawable.trash_empty);
alert.show();
//elimino il preferito dal db
Log.i("DELETING", "I'm deleting "+parent.getId()+" Position: "+parent.getPosizione());
}
});
return convertView;
}
// This Function used to inflate child rows view
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parentView){
final Parent parent = pref.get(groupPosition);
final Child child = parent.getChildren().get(childPosition);
// Inflate childrow.xml file for child rows
convertView = inflater.inflate(R.layout.childrow_pref, parentView, false);
// Get childrow.xml file elements and set values
/***DESCRIZIONE***/
((TextView) convertView.findViewById(R.id.TVDescrizione)).setText(child.getDescrizione());
ImageView image=(ImageView)convertView.findViewById(R.id.image_tag);
image.setImageResource(R.drawable.icon_16301);
return convertView;
}
#Override
public Object getChild(int groupPosition, int childPosition)
{
//Log.i("Childs", groupPosition+"= getChild =="+childPosition);
return pref.get(groupPosition).getChildren().get(childPosition);
}
//Call when child row clicked
#Override
public long getChildId(int groupPosition, int childPosition)
{
/****** When Child row clicked then this function call *******/
if( ChildClickStatus!=childPosition)
{
ChildClickStatus = childPosition;
}
return childPosition;
}
#Override
public int getChildrenCount(int groupPosition)
{
int size=0;
if(pref.get(groupPosition).getChildren()!=null)
size = pref.get(groupPosition).getChildren().size();
return size;
}
#Override
public Object getGroup(int groupPosition)
{
Log.i("Parent", groupPosition+"= getGroup ");
return pref.get(groupPosition);
}
#Override
public int getGroupCount()
{
return pref.size();
}
//Call when parent row clicked
#Override
public long getGroupId(int groupPosition)
{
ParentClickStatus=groupPosition;
if(ParentClickStatus==0)
ParentClickStatus=-1;
return groupPosition;
}
#Override
public void notifyDataSetChanged()
{
// Refresh List rows
super.notifyDataSetChanged();
}
#Override
public boolean isEmpty()
{
return ((pref == null) || pref.isEmpty());
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return true;
}
/******************* Checkbox Checked Change Listener ********************/
private final class CheckUpdateListener implements OnCheckedChangeListener
{
private final Parent parent;
private CheckUpdateListener(Parent parent)
{
this.parent = parent;
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
Log.i("onCheckedChanged", "isChecked: "+isChecked);
parent.setChecked(isChecked);
((MyExpandableListAdapter)getExpandableListAdapter()).notifyDataSetChanged();
final Boolean checked = parent.isChecked();
}
}
/***********************************************************************/
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
}
}

The solution is calling notifyDataSetChanged() after the delete operation:
pref.clear();
MyDBHelper dbHelper = new MyDBHelper(this,"JobAroundU_DB", null, 1);
SQLiteDatabase db=dbHelper.getWritableDatabase();
String sqlSavedPreferences="SELECT * FROM MyPreferences";
Cursor cursor = db.rawQuery(sqlSavedPreferences, null);
while (cursor.moveToNext()){
Parent p= new Parent();
p.setPosizione(cursor.getString(1));
p.setAzienza(cursor.getString(2));
p.setId(cursor.getString(4));
Log.i("Parent ID", p.getId());
Child cp = new Child();
cp.setDescrizione(cursor.getString(3));
p.setChildren(new ArrayList<Child>());
p.getChildren().add(cp);
pref.add(p);
}
db.close();
cursor.close();
// Refresh ExpandableListView data
((MyExpandableListAdapter)getExpandableListAdapter()).notifyDataSetChanged();
Add the above code to your delete method and it should work.

Related

Highlight Header View of expandable list view if Its at least one Child View is highlighted on Android Studio

I want Header View on expandable List View is automatically changed background color right after initial program if there is at least one of Child View be highlighted
I get this program from http://tutorialscache.com/expandable-listview-android-tutorials/ as an example
Here is the ExpandableCustomAdapter Class
public class ExpandableCustomAdapter extends BaseExpandableListAdapter{
//Initializing variables
private List<String> headerData;
private HashMap<String, ArrayList<ChildDataModel>> childData;
private Context mContext;
private LayoutInflater layoutInflater;
// constructor
public ExpandableCustomAdapter(Context mContext, List<String> headerData,
HashMap<String, ArrayList<ChildDataModel>> childData) {
this.mContext = mContext;
this.headerData = headerData;
this.childData = childData;
this.layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getGroupCount() {
return this.headerData.size();
}
#Override
public int getChildrenCount(int headPosition) {
return this.childData.get(this.headerData.get(headPosition)).size();
}
#Override
public Object getGroup(int headPosition) {
return this.headerData.get(headPosition);
}
#Override
public Object getChild(int headPosition, int childPosition) {
return this.childData.get(this.headerData.get(headPosition))
.get(childPosition);
}
#Override
public long getGroupId(int headPosition) {
return headPosition;
}
#Override
public long getChildId(int headPosition, int childPosition) {
return this.childData.get(this.headerData.get(headPosition))
.get(childPosition).getId();
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int headPosition, boolean is_expanded, View view, ViewGroup headGroup) {
// Heading of each group
String heading = (String) getGroup(headPosition);
if (view==null){
view = layoutInflater.inflate(R.layout.list_header,null);
}
TextView headerTv = view.findViewById(R.id.headerTv);
headerTv.setText(heading+"");
headerTv.setBackgroundColor( Color.BLUE );
return view;
}
#Override
public View getChildView(int headPosition, int childPosition, boolean islastChild, View view, ViewGroup viewGroup) {
ChildDataModel child = (ChildDataModel) getChild(headPosition, childPosition);
if (view == null) {
view = layoutInflater.inflate(R.layout.child_item, null);
}
TextView childTv = (TextView) view.findViewById(R.id.childTv);
ImageView childImg = (ImageView) view.findViewById(R.id.childImg);
childTv.setText(child.getTitle());
if(child.getTitle().equalsIgnoreCase( "China" ))
{
childTv.setBackgroundColor( Color.RED );
}
childImg.setImageResource(child.getImage());
return view;
}
#Override
public boolean isChildSelectable(int headPosition, int childPosition) {
return true;
}
}
Here is ChildDataModel Class
public class ChildDataModel {
long id;
int image;
String title;
public ChildDataModel(int id, String country, int image) {
this.setId(id);
this.setTitle(country);
this.setImage(image);
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
Log.d("response ","ID: "+getId()+" Title: "+getTitle());
return super.toString();
}
}
Here is MainActivity Class
public class MainActivity extends AppCompatActivity {
ExpandableCustomAdapter expandableCustomAdapter;
ExpandableListView expandableListView;
List<String> headerData;
HashMap<String,ArrayList<ChildDataModel>> childData;
ChildDataModel childDataModel;
Context mContext;
ArrayList<ChildDataModel> asianCountries,africanCountries,nAmericanCountries,sAmericanCountries;
private int lastExpandedPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
//initializing arraylists
headerData = new ArrayList<>();
childData = new HashMap<String,ArrayList<ChildDataModel>>();
asianCountries = new ArrayList<>();
africanCountries = new ArrayList<>();
nAmericanCountries = new ArrayList<>();
sAmericanCountries = new ArrayList<>();
// link listview from activity_main.xml
expandableListView = findViewById(R.id.expandAbleListView);
//populating data of world continents and their countries.
headerData.add("ASIA");
//adding countries to Asian continent
childDataModel = new ChildDataModel(1,"Afghanistan",R.drawable.afghanistan);
asianCountries.add(childDataModel);
childDataModel = new ChildDataModel(2,"China",R.drawable.china);
asianCountries.add(childDataModel);
childDataModel = new ChildDataModel(3,"India",R.drawable.india);
asianCountries.add(childDataModel);
childDataModel = new ChildDataModel(4,"Pakistan",R.drawable.pakistan);
asianCountries.add(childDataModel);
childData.put(headerData.get(0),asianCountries);
headerData.add("AFRICA");
//adding countries to African continent
childDataModel = new ChildDataModel(1,"South Africa",R.drawable.southafrica);
africanCountries.add(childDataModel);
childDataModel = new ChildDataModel(2,"Zimbabwe",R.drawable.zimbabwe);
childData.put(headerData.get(1),africanCountries);
headerData.add("NORTH AMERICA");
//adding countries to NORTH AMERICA continent
childDataModel = new ChildDataModel(1,"Canada",R.drawable.canada);
nAmericanCountries.add(childDataModel);
childData.put(headerData.get(2),nAmericanCountries);
headerData.add("SOUTH AMERICA");
//adding countries to SOUTH AMERICA continent
childDataModel = new ChildDataModel(1,"Argentina",R.drawable.argentena);
sAmericanCountries.add(childDataModel);
childData.put(headerData.get(3),sAmericanCountries);
//set adapter to list view
expandableCustomAdapter = new ExpandableCustomAdapter(mContext,headerData,childData);
expandableListView.setAdapter(expandableCustomAdapter);
//child click listener
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView expandableListView, View view, int headPosition, int childPosition, long id) {
Toast.makeText(mContext,
headerData.get(headPosition)
+ " has country "
+ childData.get(
headerData.get(headPosition)).get(
childPosition).getTitle(), Toast.LENGTH_SHORT)
.show();
return false;
}
});
//group expanded
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int headPosition) {
if (lastExpandedPosition != -1
&& headPosition != lastExpandedPosition) {
expandableListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = headPosition;
Toast.makeText(mContext,
headerData.get(headPosition) + " continent expanded",
Toast.LENGTH_SHORT).show();
}
});
//group collapsed
expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int headPosition) {
Toast.makeText(mContext,
headerData.get(headPosition) + " continent collapsed",
Toast.LENGTH_SHORT).show();
}
});
//Group Indicator
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
parent.smoothScrollToPosition(groupPosition);
if (parent.isGroupExpanded(groupPosition)) {
ImageView imageView = v.findViewById(R.id.expandable_icon);
imageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right));
} else {
ImageView imageView = v.findViewById(R.id.expandable_icon);
imageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_down));
}
return false ;
}
});
}
}
I expect to handle it without event like setOnChildClickListener, setOnGroupExpandListener,setOnGroupCollapseListener, etc. Thanks for help
change getGroupView to:
#Override
public View getGroupView(int headPosition, boolean is_expanded, View view, ViewGroup headGroup) {
// Heading of each group
String heading = (String) getGroup(headPosition);
if (view==null){
view = layoutInflater.inflate(R.layout.list_header,null);
}
TextView headerTv = view.findViewById(R.id.headerTv);
headerTv.setText(heading+"");
boolean hasSelected = false;
ArrayList<ChildDataModel> childs =
childData.get(headerData.getItemAtIndex(headPosition));
for(int i=0;i<childs.size();i++){
if(childs.get(i).isSelected){
hasSelected = true;
}}
if(hasSelected)
headerTv.setBackgroundColor( Color.BLUE );
else
headerTv.setBackgroundColor( Color.RED);
return view;
}
you most highlight the header view when getGroupView executed if childs highl sign selected chileds and if selected eny then highlight header
Thank you #hunixa siuri It does work well. However Code must be edited a little as below
#Override
public View getGroupView(int headPosition, boolean is_expanded, View view, ViewGroup headGroup) {
// Heading of each group
String heading = (String) getGroup(headPosition);
if (view==null){
view = layoutInflater.inflate(R.layout.list_header,null);
}
TextView headerTv = view.findViewById(R.id.headerTv);
headerTv.setText(heading+"");
boolean hasSelected = false;
ArrayList<ChildDataModel> childs = childData.get(headerData.get(headPosition));
for(int i=0;i<childs.size();i++){
if(childs.get(i).getTitle().equalsIgnoreCase( "China" )){
hasSelected = true;
}}
if(hasSelected)
view.setBackgroundColor( Color.BLUE );
else
view.setBackgroundColor( Color.RED);
return view;
}

How to delete item from custom listview on long click in android?

I have a listview with custom base adapter which validate some items in listview. What i want is when i long click on item oflistview, a dialog should open stating "Yes" or "No" and when i tap on "Yes" it should delete that item from adapter.How can i do that.
Here is code of Adapter
private static final String TAG = CDealAppListingAdapter.class.getSimpleName();
private static final String DEAL_CODE = "DealCode";
private static final String HEADER_TEXT = "headerText";
private static final String LOGO_PATH = "logoPath";
private final Context m_Context;// declaring context variable
private final ArrayList<CDealAppDatastorage> s_oDataset;// declaring array list ariable
public CDealAppListingAdapter(Context m_Context, ArrayList<CDealAppDatastorage> mDataList) {
this.m_Context = m_Context;
s_oDataset = mDataList;
}
#Override
public int getCount() {// get total arraylist size
return s_oDataset.size();
}
#Override
public Object getItem(int position) {// get item position in array list
return s_oDataset.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressWarnings("deprecation")
#SuppressLint({"SetTextI18n", "InflateParams"})
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.deallisting_card_view, null);
viewHolder.m_Header = (TextView) convertView.findViewById(R.id.headingText);
viewHolder.m_DummyText = (TextView) convertView.findViewById(R.id.subHeadingText);
viewHolder.m_logoImage = (ImageView) convertView.findViewById(R.id.appImage);
viewHolder.m_getBtn = (Button) convertView.findViewById(R.id.getDealBtn);
viewHolder.mProgress = (ProgressBar) convertView.findViewById(R.id.progressBar3);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.m_getBtn.setOnClickListener(new View.OnClickListener() {// onclick getDeal Btn
#Override
public void onClick(View v) {//send to deal detail page onclick getDeal Btn
if (NetworkUtil.isConnected(m_Context)) {
Intent i = new Intent(v.getContext(), CDealAppListingDetails.class);
i.putExtra(DEAL_CODE, s_oDataset.get(position).getM_szsubHeaderText());// get deal code from deal data storage
i.putExtra(HEADER_TEXT, s_oDataset.get(position).getM_szHeaderText());// get deal name from deal dta storage
i.putExtra(LOGO_PATH, s_oDataset.get(position).getM_szLogoPath());
v.getContext().startActivity(i);
} else {
/*here I am getting error*/
CSnackBar.showSnackBarError(v, m_Context.getString(R.string.no_internet_connection), v.getContext());
}
}
});
CDealAppDatastorage m = s_oDataset.get(position);
viewHolder.m_Header.setText(m.getM_szHeaderText());
viewHolder.m_DummyText.setText(m.getM_szDetails());
viewHolder.m_getBtn.setText("GET " + m.getM_szDealValue() + " POINTS");// set deal button text
Picasso.with(m_Context).load(m.getM_szLogoPath()).into(viewHolder.m_logoImage, new Callback() {
#Override
public void onSuccess() {
Log.e(TAG, "OnSuccess Called::");
viewHolder.mProgress.setVisibility(View.INVISIBLE);
}
#Override
public void onError() {
Log.e(TAG, "OnError Called::");
}
});
return convertView;
}
private class ViewHolder {
public TextView m_Header, m_Subheader, m_DummyText;
public ImageView m_logoImage;
public Button m_getBtn;
public ProgressBar mProgress;
}
}
There are two ways to remove item on long press.
1 From class
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
return false;
}
});
2 From adapter
viewHolder.m_getBtn.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
return false;
}
});
Sample code structure below;
listview.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// TODO Auto-generated method stub
//show dialog asking user option to delete or not
//On OK click, dataset.remove(position);
//adapter.notifyDatasetChanged();
return true;
}
});
Remove selected item from arraylist and referesh listview
s_oDataset.remove(youritemPostion);
notifyDataSetChanged();
after you click YES
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// TODO Auto-generated method stub
//call Dialog builder class here.
}
});
First call setOnItemLongClickListener and inside that call Dialogbuilder class ,And inside that dialog builder set your buttons on that dialog using .setPositiveButton or .setNegativeButton methods

CheckBox in child of exapndablelistview (android)

Problem is with checkbox. When user click on child, app should show toast message on which child user clicked. It works fine if I click on textview of child, but when i click on checkbox, nothing heppend. Also when I click on child item, I want that my checkbox change state. Do you see something that I can't see. Here is my code for main activity
private ExpandableAdapter adapter;
private ExpandableListView expandableList;
private List<Pitanja> pitanjas = new ArrayList<Pitanja>();
private ArrayList<Pitanja> listaPitanja = new ArrayList<Pitanja>();
private List<Odgovor> odgovors = new ArrayList<Odgovor>();
public static HashMap<Integer, Integer> pitanjaa;
private Intent intent;
private ProgressDialog pDialog;
private TextView output;
private List<Ispit> ispitList;
private String pozicija;
private Button posalji;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ispit);
output = (TextView) findViewById(R.id.ispit_datum);
output.setMovementMethod(new ScrollingMovementMethod());
pitanjaa = new HashMap<Integer, Integer>();
posalji = (Button) findViewById(R.id.posaljiIspitButton);
posalji.setOnClickListener(this);
generateData();
initEx();
intent = getIntent();
RequestPackage p = new RequestPackage();
p.setUri("http://arka.foi.hr/WebDiP/2012_projekti/WebDiP2012_085/AIR/ispit.php");
p.setMethod("POST");
p.setParam("id_kolegij", intent.getStringExtra("id_predmeta"));
Log.i("Saljem podatke ", intent.getStringExtra("id_predmeta"));
MyTask task = new MyTask();
task.execute(p);
}
private void updateDisplay(){
Collections.shuffle(ispitList);
output.setText(String.valueOf(ispitList.get(0).getId()));
MyRequest task = new MyRequest();//this works fine
RequestPackage r = new RequestPackage();//works
r.setMethod("POST");//works
r.setUri("http://arka.foi.hr/WebDiP/2012_projekti/WebDiP2012_085/AIR/pitanja.php");//works
r.setParam("id_kolegij", output.getText().toString());//works
task.execute(r);
}
private void initEx(){
adapter = new ExpandableAdapter(IspitActivity.this, listaPitanja);
expandableList = (ExpandableListView) findViewById(R.id.expandableIspitListView);
expandableList.setAdapter(adapter);
for (int i=0;i<adapter.getGroupCount();i++){
expandableList.collapseGroup(i);
}
expandableList.setOnChildClickListener(new OnChildClickListener(){
#Override
public boolean onChildClick(ExpandableListView arg0, View arg1,
int arg2, int arg3, long arg4) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Klikno si na " + adapter.getChild(arg2, arg3).getText() + " " + adapter.getChild(arg2, arg3).getTocan_netocan(), Toast.LENGTH_SHORT).show();
if (Integer.parseInt(adapter.getChild(arg2, arg3).getTocan_netocan()) == 0)
pitanjaa.put(arg2, arg3);
Log.i("pitanja koja si odgovorio su", pitanjaa.toString());
adapter.getChild(arg2, arg3).setSelected(true);
return true;
}
});
}
private void generateData(){
Pitanja p;
for (int i=0;i<pitanjas.size();i++){
ArrayList<Odgovor> od = new ArrayList<Odgovor>();
for (int z=0;z<odgovors.size();z++){
if (odgovors.get(z).getId_pitanja().contains(String.valueOf(pitanjas.get(i).getId()))){
od.add(odgovors.get(z));
}
}
pozicija = pitanjas.get(i).getText();
p = new Pitanja(i, pozicija, od);
listaPitanja.add(p);
}
}
private class MyTask extends AsyncTask<RequestPackage, String, List<Ispit>>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(IspitActivity.this);
pDialog.setMessage("Dobavljam podatke...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected List<Ispit> doInBackground(RequestPackage... params) {
String content = HttpManager.getData(params[0]);
ispitList = JSONParser.parseIspit(content.substring(1, content.length()-1));
Log.i("Parsirano izgleda sljedeci", content.substring(1, content.length()-1));
return ispitList;
}
#Override
protected void onPostExecute(List<Ispit> result) {
super.onPostExecute(result);
pDialog.dismiss();
updateDisplay();
}
}
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), PregledActivity.class);
startActivity(intent);
}
}
Here is my expandablelistview adapter
public class ExpandableAdapter extends BaseExpandableListAdapter{
LayoutInflater inflater;
private List<Pitanja> groups;
public ExpandableAdapter(Context context,List<Pitanja> groups) {
super();
this.groups=groups;
inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(Odgovor child,Pitanja group) {
if(!groups.contains(group)) {
groups.add(group);
}
int index=groups.indexOf(group);
ArrayList<Odgovor> ch=groups.get(index).getOdgovors();
ch.add(child);
groups.get(index).setOdgovors(ch);
}
public Odgovor getChild(int groupPosition, int childPosition) {
ArrayList<Odgovor> ch=groups.get(groupPosition).getOdgovors();
return ch.get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<Odgovor> ch=groups.get(groupPosition).getOdgovors();
return ch.size();
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
Odgovor child= (Odgovor) getChild(groupPosition,childPosition);
TextView childName=null;
CheckBox cb = null;
if(convertView==null) {
convertView=inflater.inflate(R.layout.child_item, null);
}
childName=(TextView) convertView.findViewById(R.id.textview_child_item);
childName.setText(child.getText());
cb = (CheckBox) convertView.findViewById(R.id.checkbox_child_item);
if (child.isSelected())
cb.setChecked(true);
return convertView;
}
public Pitanja getGroup(int groupPosition) {
return groups.get(groupPosition);
}
public int getGroupCount() {
return groups.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
TextView groupName = null;
Pitanja group=(Pitanja) getGroup(groupPosition);
if(convertView==null) {
convertView=inflater.inflate(R.layout.parent_item, null);
}
groupName=(TextView) convertView.findViewById(R.id.parent_item);
groupName.setText(group.getText());
return convertView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
}
my child view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/checkbox_child_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" />
<TextView
android:id="#+id/textview_child_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
If I changle focusable of my checkbox, it doesn't work too. Someone have idea
The CheckBox will consume the click event before passing it on to the ExpandableListView click event. You'll need to manually attached a click listener to the CheckBox in the getChildView() method if you want to see those click events.

Override default expandablelistview expand behaviour

How does one go about manually expanding and collapsing an expandablelistview? I know of expandGroup(), but am not sure where to set the onClickListener(), as half of this code, is in a separate library project.
ExpandableDeliveryList
package com.goosesys.dta_pta_test;
[imports removed to save space]
public class ExpandableDeliveryList<T> extends ExpandableListActivity {
private ArrayList<GooseDeliveryItem> parentItems = new ArrayList<GooseDeliveryItem>();
private ArrayList<DeliverySiteExtras> childItems = new ArrayList<DeliverySiteExtras>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// CREATE THE EXPANDABLE LIST AND SET PROPERTIES //
final ExpandableListView expandList = getExpandableListView();
expandList.setDividerHeight(0);
expandList.setGroupIndicator(null);
expandList.setClickable(false);
// LIST OF PARENTS //
setGroupParents();
// CHILDREN //
setChildData();
// CREATE ADAPTER //
GooseExpandableArrayAdapter<?> adapter = new GooseExpandableArrayAdapter<Object>(
R.layout.goose_delivery_item,
R.layout.goose_delivery_item_child,
parentItems,
childItems);
adapter.setInflater((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
expandList.setAdapter(adapter);
expandList.setOnChildClickListener(this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case android.R.id.home:
{
Intent intent = new Intent(this, Main.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
return true;
}
default:
{
return super.onOptionsItemSelected(item);
}
}
}
public void setGroupParents()
{
DatabaseHelper dbHelper = new DatabaseHelper(this);
List<DeliverySite> sites = new ArrayList<DeliverySite>();
sites = dbHelper.getAllSites();
GooseDeliveryItem[] deliveries = new GooseDeliveryItem[sites.size()];
for(int i=0; i<sites.size(); i++)
{
Delivery del = new Delivery();
try
{
del = dbHelper.getDeliveryByJobNo(sites.get(i).id);
}
catch(Exception e)
{
e.printStackTrace();
}
final GooseDeliveryItem gdi;
if((Double.isNaN(sites.get(i).lat)) || (Double.isNaN(sites.get(i).lng)))
{
gdi = new GooseDeliveryItem(sites.get(i).id, sites.get(i).company);
}
else
{
gdi = new GooseDeliveryItem(sites.get(i).id, sites.get(i).company, sites.get(i).lat, sites.get(i).lng);
}
if(del.getReportedFully() == 1)
{
gdi.isReportedFully = true;
}
deliveries[i] = gdi;
}
// FINALLY ADD THESE ITEMS TO THE PARENT ITEMS LIST ARRAY //
for(GooseDeliveryItem g : deliveries)
parentItems.add(g);
}
public void setChildData()
{
//DatabaseHelper dbHelper = new DatabaseHelper(this);
ArrayList<DeliverySiteExtras> extras = new ArrayList<DeliverySiteExtras>();
for(int i=0; i<parentItems.size(); i++)
{
DeliverySiteExtras dse = new DeliverySiteExtras();
extras.add(dse);
}
childItems = extras;
}
}
ArrayAdapter
package com.goosesys.gooselib.Views;
[imports removed to save space]
public class GooseExpandableArrayAdapter<Object> extends BaseExpandableListAdapter
{
private Activity activity;
private ArrayList<DeliverySiteExtras> childItems;
private LayoutInflater inflater;
ArrayList<GooseDeliveryItem> parentItems;
private DeliverySiteExtras child;
private int layoutId;
private int childLayoutId;
public GooseExpandableArrayAdapter(int layoutId, int childLayoutId, ArrayList<GooseDeliveryItem> parents, ArrayList<DeliverySiteExtras> children)
{
this.layoutId = layoutId;
this.childLayoutId = childLayoutId;
this.parentItems = (ArrayList<GooseDeliveryItem>) parents;
this.childItems = (ArrayList<DeliverySiteExtras>)children;
}
public GooseExpandableArrayAdapter(ArrayList<GooseDeliveryItem> parents, ArrayList<DeliverySiteExtras> children, int layoutId)
{
this.parentItems = parents;
this.childItems = children;
this.layoutId = layoutId;
}
public void setInflater(LayoutInflater inflater, Activity activity)
{
this.inflater = inflater;
this.activity = activity;
}
#Override
public Object getChild(int arg0, int arg1)
{
return null;
}
#Override
public long getChildId(int arg0, int arg1)
{
return 0;
}
/*
* Child view get method
* Utilise this to edit view properties at run time
*/
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
{
child = childItems.get(groupPosition);
if(convertView == null)
{
convertView = inflater.inflate(this.childLayoutId, null);
}
// GET ALL THE OBJECT VIEWS AND SET THEM HERE //
setGeoLocation(groupPosition, convertView);
convertView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
}
});
return convertView;
}
#Override
public void onGroupCollapsed(int groupPosition)
{
super.onGroupCollapsed(groupPosition);
}
#Override
public void onGroupExpanded(int groupPosition)
{
super.onGroupExpanded(groupPosition);
}
#Override
public int getChildrenCount(int groupPosition)
{
return 1; //childItems.get(groupPosition);
}
#Override
public Object getGroup(int groupPosition)
{
return null;
}
#Override
public int getGroupCount()
{
return parentItems.size();
}
#Override
public long getGroupId(int arg0)
{
return 0;
}
/*
* Parent View Object get method
* Utilise this to edit view properties at run time.
*/
#Override
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
{
if(convertView == null)
{
convertView = inflater.inflate(this.layoutId, null);
}
// GET ALL OBJECT VIEWS AND SET THEM HERE -- PARENT VIEW //
TextView name = (TextView)convertView.findViewById(R.id.customerName);
name.setText(parentItems.get(groupPosition).customerText);
ImageView go = (ImageView)convertView.findViewById(R.id.moreDetails);
go.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i = new Intent(activity, DeliveryJobActivity.class);
i.putExtra("obj", parentItems.get(groupPosition));
activity.startActivity(i);
}
});
return convertView;
}
#Override
public boolean hasStableIds()
{
return false;
}
#Override
public boolean isChildSelectable(int arg0, int arg1)
{
return false;
}
private void setGeoLocation(final int groupPosition, View parent)
{
GeoLocation geoLocation = new GeoLocation(activity);
final double lat = geoLocation.getLatitude();
final double lng = geoLocation.getLongitude();
// GET OUR START LOCATION //
Location startLocation = new Location("Start");
startLocation.setLatitude(lat);
startLocation.setLongitude(lng);
// GET OUR DESTINATION //
Location destination = new Location("End");
destination.setLatitude(((GooseDeliveryItem)parentItems.get(groupPosition)).latitude);
destination.setLongitude(((GooseDeliveryItem)parentItems.get(groupPosition)).longitude);
double distanceValue = startLocation.distanceTo(destination);
TextView tv = (TextView)parent.findViewById(R.id.extraHeader);
tv.setText(parentItems.get(groupPosition).customerText + " information:");
TextView ds = (TextView)parent.findViewById(R.id.deliveryDistance);
ds.setText("Distance (from location): " + String.valueOf(Math.ceil(distanceValue * GooseConsts.METERS_TO_A_MILE)) + " Mi (approx)");
ImageView img = (ImageView)parent.findViewById(R.id.directionsImage);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// invoke google maps with lat / lng position
Intent navigation = new Intent(Intent.ACTION_VIEW, Uri.parse(
"http://maps.google.com/maps?saddr="
+ (lat) + "," + (lng)
+ "&daddr="
+ ((GooseDeliveryItem)parentItems.get(groupPosition)).latitude + ","
+ ((GooseDeliveryItem)parentItems.get(groupPosition)).longitude
));
activity.startActivity(navigation);
}
});
}
}
Ideally, my bosses would like to have a "+" button, that when clicked expands the listview manually. Rather than clicking anywhere on the view and it doing it automatically. Is this possible? Also, setting setClickable(false) seems to have no effect. Because it'll still expand when any list item is clicked. Am I missing something there also?
Cheers.
You can add an ExpandableListView Group Click Listener ("ExpandableListView::setOnGroupClickListener") to monitor and suppress click event for the ListView Groups. Using your code example, this would be done in your "ExpandableDeliveryList" module after you create the ExpandableListView.
Then in your "+" (and "-") Button click handlers, you can add logic to expand/collapse some or all of the ListView Groups using the "ExpandableListView::expandGroup()" and "ExpandableListView::collapseGroup()" methods.
You do not need to return "false" from the overridden "isChildSelectable()" method as this has no effect on what you are trying to accomplish (and will prevent anyone from clicking/selecting child items in the ListView).
Code examples are shown below:
// CREATE THE EXPANDABLE LIST AND SET PROPERTIES //
final ExpandableListView expandList = getExpandableListView();
//...
expandList.setOnGroupClickListener(new android.widget.ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick( ExpandableListView parent,
View view,
int groupPosition,
long id) {
// some code...
// return "true" to consume the event (and prevent the Group from expanding/collapsing) / "false" to allow the Group to expand/collapse normally
return true;
}
});
To manually expand and collapse the ListView Groups:
// enumerate thru the ExpandableListView Groups
// [in this code example, a single index is used...]
int groupPosition = 0;
// expand the ListView Group/s
if (m_expandableListView.isGroupExpanded(groupPosition) == false) {
// API Level 14+ allows you to animate the Group expansion...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
m_expandableListView.expandGroup(groupPosition, true);
}
// else just expand the Group without animation
else {
m_expandableListView.expandGroup(groupPosition);
}
}
// collapse the ListView Group/s
else {
m_expandableListView.collapseGroup(groupPosition);
}
Hope this Helps.

How should I correct the code to get rid of these "value not used" warnings?

These are the error messages I am getting please advise.
The value of the field LocationListActivity.adapter is not used
The value of the field LocationListActivity.lv1 is not used
The value of the field LocationListActivity.titleString is not used
public class LocationListActivity extends ExpandableListActivity {
private ArrayAdapter<String> adapter = null;
private String name;
private ArrayList<List<LocationData>> locations; //Array list of all locations
private ArrayList<LocationData> locationList; // locations for each group
private ListView lv1;
private ArrayList<String> locationSection = new ArrayList<String>();
private ArrayList<String> sectionLocations = new ArrayList<String>();
private ArrayList<ArrayList<String>> allLocations = new ArrayList<ArrayList<String>>();
private String titleString;
private ExpandableListAdapter mAdapter;
private Button search;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_list_activity);
search = (Button)findViewById(R.id.search_button);
search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(LocationListActivity.this, LocationListSearchActivity.class));
}
});
//PARSE locations.xml
try {
this.locations = new ArrayList<List<LocationData>>();
this.locationList = new ArrayList<LocationData>();
XmlResourceParser xrp = this.getResources().getXml(R.xml.locations);
LocationData currentLocation = null;
while(xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
currentLocation = new LocationData();
if(xrp.getEventType() == XmlResourceParser.START_TAG) {
if(xrp.getName().equals("section")) {
locationSection.add(xrp.getAttributeValue(null, "title"));
}
else if(xrp.getName().equals("location")) {
currentLocation.setBuilding((xrp.getAttributeValue(null, "building")));
name = xrp.getAttributeValue(null, "name");
sectionLocations.add(name);
currentLocation.setName(name);
currentLocation.setDetailName((xrp.getAttributeValue(null, "detailName")));
currentLocation.setLat(Double.parseDouble(xrp.getAttributeValue(null, "lat")));
currentLocation.setLng(Double.parseDouble(xrp.getAttributeValue(null, "lng")));
currentLocation.setPhone(xrp.getAttributeValue(null, "phone"));
locationList.add(currentLocation);
}
}
else if(xrp.getEventType() == XmlResourceParser.END_TAG) {
if(xrp.getName().equals("section")) {
allLocations.add(new ArrayList<String>(sectionLocations));
sectionLocations.clear();
locations.add(new ArrayList<LocationData>(locationList));
locationList.clear();
}
}
xrp.next();
}
xrp.close();}
catch (XmlPullParserException xppe) {}
catch (IOException e) {}
// Set up our adapter
mAdapter = new MyExpandableListAdapter();
setListAdapter(mAdapter);
}
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
public Object getChild(int groupPosition, int childPosition) {
return allLocations.get(groupPosition).get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public int getChildrenCount(int groupPosition) {
return allLocations.get(groupPosition).size();
}
public TextView getGenericView() {
// Layout parameters for the ExpandableListView
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, 80);
TextView textView = new TextView(LocationListActivity.this);
textView.setLayoutParams(lp);
// Center the text vertically
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
textView.setBackgroundResource(R.drawable.button_click);
textView.setTypeface(null, android.graphics.Typeface.BOLD);
textView.setTextColor(0xFF000000);
textView.setPadding(55, 0, 0, 0);
return textView;
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(getChild(groupPosition, childPosition).toString());
textView.setTypeface(null, android.graphics.Typeface.NORMAL);
return textView;
}
public Object getGroup(int groupPosition) {
return locationSection.get(groupPosition);
}
public int getGroupCount() {
return locationSection.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(getGroup(groupPosition).toString());
return textView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
}
public boolean onChildClick (ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Intent i = new Intent( LocationListActivity.this, LocationInfoActivity.class );
i.putExtra("name", locations.get(groupPosition).get(childPosition).getName());
i.putExtra("building", locations.get(groupPosition).get(childPosition).getBuilding());
i.putExtra("detailName", locations.get(groupPosition).get(childPosition).getDetailName());
i.putExtra("lat", locations.get(groupPosition).get(childPosition).getLat());
i.putExtra("lng", locations.get(groupPosition).get(childPosition).getLng());
i.putExtra("phone", locations.get(groupPosition).get(childPosition).getPhone());
startActivity(i);
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = this.getMenuInflater();
inflater.inflate(R.menu.menu_home, menu);
return true;
}
//Called when user selects a menu item;
#Override
public boolean onOptionsItemSelected( MenuItem item ){
switch(item.getItemId()) {
case R.id.menu_search:
startActivity(new Intent(this, LocationListSearchActivity.class));
finish();
break;
case R.id.menu_about:
startActivity(new Intent(this, AboutActivity.class));
finish();
break;
}
return true;
}
}
You can use
#SuppressWarnings("unused")
Note: Similar thing happened to me. I had variables that all was used but warning still appeared. So in this case this approach is very good.
But if you have variables which you already not using nowhere, i recommend to remove them or comment them.
You could remove or comment out those variables. If you don't want to do that you can also change the warnings within Eclipse.
There have been times where I had variables that I KNOW were used and I couldn't figure out why it kept saying they were not. For some reason, certain errors in other part of the program might be making that happen. Alternately, if you are not going to use what it has highlighted, then I would just delete it.

Categories

Resources