I have an ExpandableListView created and working with static data, my problem is I am not sure how to get data from my sqlite database into the ExpandableListView. I have tried multiple websites and posts and have gotten very little.
If someone could please take a look at my code below and suggest a working solution.
Thanks
package com.example.pooveshin.vennsroadaccident2;
import android.app.Activity;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends Activity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
return false;
}
});
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Accident Number : 1");
listDataHeader.add("Accident Number : 2");
listDataHeader.add("Accident Number : 3");
// Adding child data
List<String> AccYV = new ArrayList<String>();
AccYV.add("Accident Number : ");
AccYV.add("Registration Number : ");
AccYV.add("Make & Model");
AccYV.add("Address of Owner");
AccYV.add("Name of Driver");
AccYV.add("Address of Driver");
AccYV.add("Tel no.Driver");
List<String> AccOV = new ArrayList<String>();
AccOV.add("Name of Driver");
AccOV.add("Identity Number");
AccOV.add("Residential Address");
AccOV.add("Tel no.Work");
AccOV.add("Make & Model");
AccOV.add("Licence Number");
List<String> AccCD = new ArrayList<String>();
AccCD.add("Date");
AccCD.add("Time");
AccCD.add("Place");
AccCD.add("Weather");
AccCD.add("Road Surface");
listDataChild.put(listDataHeader.get(0), AccYV); // Header, Child data
listDataChild.put(listDataHeader.get(1), AccOV);
listDataChild.put(listDataHeader.get(2), AccCD);
}
}
In DBHelper.java
public Cursor getYVAllData()
{
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Cursor res = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE_NAME,null);
return res;
}
you shoud make an adapter for expandablelistview like this
public class ExpandListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<ExpandListGroup> groups;
public ExpandListAdapter(Context context, ArrayList<ExpandListGroup> groups) {
this.context = context;
this.groups = groups;
}
public void addItem(ExpandListChild item, ExpandListGroup group) {
if (!groups.contains(group)) {
groups.add(group);
}
int index = groups.indexOf(group);
ArrayList<ExpandListChild> ch = groups.get(index).getItems();
ch.add(item);
groups.get(index).setItems(ch);
}
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
ArrayList<ExpandListChild> chList = groups.get(groupPosition).getItems();
return chList.get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view,
ViewGroup parent) {
ExpandListChild child = (ExpandListChild) getChild(groupPosition, childPosition);
if (view == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view = infalInflater.inflate(R.layout.expandlist_child_item, null);
}
TextView tv = (TextView) view.findViewById(R.id.tvChild);
tv.setText(child.getName().toString());
tv.setTag(child.getTag());
// TODO Auto-generated method stub
return view;
}
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
ArrayList<ExpandListChild> chList = groups.get(groupPosition).getItems();
return chList.size();
}
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return groups.get(groupPosition);
}
public int getGroupCount() {
// TODO Auto-generated method stub
return groups.size();
}
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isLastChild, View view,
ViewGroup parent) {
ExpandListGroup group = (ExpandListGroup) getGroup(groupPosition);
if (view == null) {
LayoutInflater inf = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view = inf.inflate(R.layout.expandlist_group_item, null);
}
TextView tv = (TextView) view.findViewById(R.id.tvGroup);
tv.setText(group.getName());
// TODO Auto-generated method stub
return view;
}
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}
public boolean isChildSelectable(int arg0, int arg1) {
// TODO Auto-generated method stub
return true;
}
}
then you should make child and group classes for list like this
child:
public class ExpandListChild {
private String Name;
private String Tag;
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getTag() {
return Tag;
}
public void setTag(String Tag) {
this.Tag = Tag;
}
}
group:
public class ExpandListGroup {
private String Name;
private ArrayList<ExpandListChild> Items;
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
public ArrayList<ExpandListChild> getItems() {
return Items;
}
public void setItems(ArrayList<ExpandListChild> Items) {
this.Items = Items;
}
}
and this is usage in your MainActivity :
ExpandList = (ExpandableListView) findViewById(R.id.expandableListView);
ExpListItems = SetStandardGroups(da.queryName());
ExpAdapter = new ExpandListAdapter(MainActivity.this, ExpListItems);
and this is my method for fiil that list:
public ArrayList<ExpandListGroup> SetStandardGroups(Cursor crsr) {
ArrayList<ExpandListGroup> list = new ArrayList<ExpandListGroup>();
ArrayList<ExpandListChild> list2;
Cursor c = crsr;
if (c.moveToFirst()) {
do {
String English = c.getString(c.getColumnIndex("English"));
String Farsi = c.getString(c.getColumnIndex("Farsi"));
ExpandListGroup gru1 = new ExpandListGroup();
gru1.setName(English);
ExpandListChild ch1_1 = new ExpandListChild();
ch1_1.setName(Farsi);
ch1_1.setTag(null);
list2 = new ArrayList<ExpandListChild>();
list2.add(ch1_1);
gru1.setItems(list2);
list.add(gru1);
} while (c.moveToNext());
}
c.close();
return list;
}
Related
I'm learning android and I'm testing right now with ExpandableListViews. I'm doing something like a dictionary with a SearchView. When I click on a child I want to start a new activity with the child name on the ActionBar and the meaning of the word(from strings.xml) in a TextView. The problem is that instead of the child name, the showed text is something like: com.example.jairo_2.myapplication.country#58f8f2e with each child. Could you help me?. I have simplified the code with a Toast that shows the child name. Thanks.
Error image
I have followed Android ExpandableListView Search Filter Example.
MainActivity.java:
package com.example.jairo_2.myapplication;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.SearchView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener{
private SearchView search;
private MyListAdapter listAdapter;
private ExpandableListView myList;
public ArrayList<Continent> continentList = new ArrayList<Continent>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
search = (SearchView) findViewById(R.id.search);
search.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
//display the list
displayList();
//expand all Groups
//expandAll();
setListener();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
//method to expand all groups
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.expandGroup(i);
}
}
//method to expand all groups
private void displayList() {
//display the list
loadSomeData();
//get reference to the ExpandableListView
myList = (ExpandableListView) findViewById(R.id.expandableList);
//create the adapter by passing your ArrayList data
listAdapter = new MyListAdapter(MainActivity.this, continentList);
//attach the adapter to the list
myList.setAdapter(listAdapter);
}
private void loadSomeData() {
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country("word1");
countryList.add(country);
country = new Country("word2");
countryList.add(country);
country = new Country("word3");
countryList.add(country);
Continent continent = new Continent("A",countryList);
continentList.add(continent);
countryList = new ArrayList<Country>();
country = new Country("China");
countryList.add(country);
country = new Country("Japan");
countryList.add(country);
country = new Country("Thailand");
countryList.add(country);
continent = new Continent("Asia",countryList);
continentList.add(continent);
}
#Override
public boolean onClose() {
listAdapter.filterData("");
expandAll();
return false;
}
#Override
public boolean onQueryTextChange(String query) {
listAdapter.filterData(query);
expandAll();
if (query.compareTo("") == 0){
int count = listAdapter.getGroupCount();
for (int i = 0; i <count ; i++)
myList.collapseGroup(i);}
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
listAdapter.filterData(query);
expandAll();
if (query.compareTo("") == 0){
int count = listAdapter.getGroupCount();
for (int i = 0; i <count ; i++)
myList.collapseGroup(i);}
return false;
}
void setListener() {
// This listener will show toast on group click
myList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView listview, View view,
int group_pos, long id) {
Toast.makeText(MainActivity.this, "You clicked : " + listAdapter.getGroup(group_pos), Toast.LENGTH_SHORT).show();
return false;
}
});
// This listener will expand one group at one time
// You can remove this listener for expanding all groups
//myList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
// Default position
//int previousGroup = -1;
//#Override
//public void onGroupExpand(int groupPosition) {
// if (groupPosition != previousGroup)
// Collapse the expanded group
// myList.collapseGroup(previousGroup);
//previousGroup = groupPosition;
// }
// });
// This listener will show toast on child click
myList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView listview, View view,
int groupPos, int childPos, long id) {
Toast.makeText(MainActivity.this, "You clicked : " + listAdapter.getChild(groupPos,childPos), Toast.LENGTH_SHORT).show();
return false;
}
});
}
}
MyListAdapter.java:
package com.example.jairo_2.myapplication;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class MyListAdapter extends BaseExpandableListAdapter {
private Context context;
public ArrayList<Continent> continentList;
private ArrayList<Continent> originalList;
public MyListAdapter(Context context, ArrayList<Continent> continentList) {
this.context = context;
this.continentList = new ArrayList<Continent>();
this.continentList.addAll(continentList);
this.originalList = new ArrayList<Continent>();
this.originalList.addAll(continentList);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<Country> countryList = continentList.get(groupPosition).getCountryList();
return countryList.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View view, ViewGroup parent) {
Country country = (Country) getChild(groupPosition, childPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.child_row, null);
}
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(country.getName().trim());
return view;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<Country> countryList = continentList.get(groupPosition).getCountryList();
return countryList.size();
}
#Override
public Object getGroup(int groupPosition) {
return continentList.get(groupPosition);
}
#Override
public int getGroupCount() {
return continentList.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isLastChild, View view,
ViewGroup parent) {
Continent continent = (Continent) getGroup(groupPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.group_row, null);
}
TextView heading = (TextView) view.findViewById(R.id.heading);
heading.setText(continent.getName().trim());
return view;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void filterData(String query){
query = query.toLowerCase();
Log.v("MyListAdapter", String.valueOf(continentList.size()));
continentList.clear();
if(query.isEmpty()){
continentList.addAll(originalList);
}
else {
for(Continent continent: originalList){
ArrayList<Country> countryList = continent.getCountryList();
ArrayList<Country> newList = new ArrayList<Country>();
for(Country country: countryList){
if(country.getName().toLowerCase().contains(query)){
newList.add(country);
}
}
if(newList.size() > 0){
Continent nContinent = new Continent(continent.getName(),newList);
continentList.add(nContinent);
}
}
}
Log.v("MyListAdapter", String.valueOf(continentList.size()));
notifyDataSetChanged();
}
}
Country.java:
package com.example.jairo_2.myapplication;
public class Country {
private String name = "";
public Country(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Continent.java
package com.example.jairo_2.myapplication;
import java.util.ArrayList;
public class Continent {
private String name;
private ArrayList<Country> countryList = new ArrayList<Country>();
public Continent(String name, ArrayList<Country> countryList) {
super();
this.name = name;
this.countryList = countryList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<Country> getCountryList() {
return countryList;
}
public void setCountryList(ArrayList<Country> countryList) {
this.countryList = countryList;
};
}
Use like this continentList.get(groupPosition).getCountryList().get(childposition)
in your Toast message section
This might be very easy question, but I'm looking for your help.
I'm using downloaded open source file. I have a list of Groups with populated Child's under it. I'm able to expand the list and see the Child's. How could I open new activity window with text information relater for specific Children when clicking on it?
Thank you for support.
MainActivity.java:
package com.example.expandablelistviewsearch;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ExpandableListView;
import android.widget.SearchView;
import android.widget.ExpandableListView.OnChildClickListener;
import java.util.ArrayList;
public class MainActivity extends Activity implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private SearchView search;
private MyListAdapter listAdapter;
private ExpandableListView myList;
private ArrayList<Continent> continentList = new ArrayList<Continent>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList.setOnChildClickListener(myListItemClicked); //added line
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
search = (SearchView) findViewById(R.id.search);
search.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
search.setIconifiedByDefault(true);
search.setOnQueryTextListener(this);
//search.setOnCloseListener(this);
// display the list
displayList();
// expand all Groups
//expandAll();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// method to expand all groups
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++) {
myList.expandGroup(i);
}
}
private OnChildClickListener myListItemClicked = new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
//get the group header
HeaderInfo headerInfo = deptList.get(groupPosition);
//get the child info
DetailInfo detailInfo = headerInfo.getProductList().get(childPosition);
//start new activity with specific child information
return false;
}
};
// method to expand all groups
private void displayList() {
// display the list
loadSomeData();
// get reference to the ExpandableListView
myList = (ExpandableListView) findViewById(R.id.expandableList);
// create the adapter by passing your ArrayList data
listAdapter = new MyListAdapter(MainActivity.this, continentList);
// attach the adapter to the list
myList.setAdapter(listAdapter);
}
private void loadSomeData() {
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country("Test1", "Test2", "Test3");
countryList.add(country);
Continent continent = new Continent("Main Test", countryList);
continentList.add(continent);
private void loadSomeData() {
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country("Test1", "Test2", "Test3");
countryList.add(country);
Continent continent = new Continent("Main Tes1t", countryList);
continentList.add(continent);
private void loadSomeData() {
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country("Test1", "Test2", "Test3");
countryList.add(country);
Continent continent = new Continent("Main Test2", countryList);
continentList.add(continent);
}
#Override
public boolean onClose() {
// TODO Auto-generated method stub
listAdapter.filterData("");
//expandAll();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
listAdapter.filterData(newText);
expandAll();
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
listAdapter.filterData(query);
expandAll();
return false;
}
}
MyListAdapter.java
package com.example.expandablelistviewsearch;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class MyListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<Continent> continentList;
private ArrayList<Continent> originalList;
public MyListAdapter(Context context, ArrayList<Continent> continentList) {
this.context = context;
this.continentList = new ArrayList<Continent>();
this.continentList.addAll(continentList);
this.originalList = new ArrayList<Continent>();
this.originalList.addAll(continentList);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
ArrayList<Country> countryList = continentList.get(groupPosition).getCountryList();
return countryList.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Country country = (Country) getChild(groupPosition, childPosition);
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.child_row, null);
}
TextView code = (TextView) convertView.findViewById(R.id.code);
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView fdd = (TextView) convertView.findViewById(R.id.fdd);
code.setText(country.getCode().trim());
name.setText(country.getName().trim());
fdd.setText(country.getFdd().trim());
//population.setText(NumberFormat.getNumberInstance(Locale.US).format(country.getPopulation()));
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
ArrayList<Country> countryList = continentList.get(groupPosition).getCountryList();
return countryList.size();
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return continentList.get(groupPosition);
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
return continentList.size();
}
#Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Continent continent = (Continent) getGroup(groupPosition);
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.group_row, null);
}
TextView heading = (TextView) convertView.findViewById(R.id.heading);
heading.setText(continent.getName().trim());
return convertView;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
public void filterData(String query)
{
query = query.toLowerCase();
Log.v("MyListAdapter", String.valueOf(continentList.size()));
continentList.clear();
if(query.isEmpty())
{
continentList.addAll(originalList);
} else {
for(Continent continent: originalList)
{
ArrayList<Country> countryList = continent.getCountryList();
ArrayList<Country> newList = new ArrayList<Country>();
for(Country country: countryList)
{
if(country.getCode().toLowerCase().contains(query) || country.getName().toLowerCase().contains(query))
{
newList.add(country);
}
}
if(newList.size() > 0)
{
Continent nContinent = new Continent(continent.getName(), newList);
continentList.add(nContinent);
}
}
}
Log.v("MyListAdapter", String.valueOf(continentList.size()));
notifyDataSetChanged();
}
}
You are almost there, under your code, you can send anything related to the child you click to the new activity using intent, then get the information out in the new activity
private OnChildClickListener myListItemClicked = new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
//get the group header
HeaderInfo headerInfo = deptList.get(groupPosition);
//get the child info
DetailInfo detailInfo = headerInfo.getProductList().get(childPosition);
//start new activity with specific child information
//--Add below codes to your code
Intent myIntent = new Intent(MainActivity.this, TargetActivity.class);
myIntent.putExtra("information",detailInfo.getInfor());
return false;
}
};
In the TargetActivity,
Intent tIntent= getIntent();
Bundle b = tIntent.getExtras();
String information = (String)b.get("information");
The string information is probably what you want to display
I would like to after clicking on the item child opened my new activity with the same name as the name of the item. That is item the "test" and if I click it open test.java class. I found a code that does this, but I do not know how to add it to my classes. Thank you for any help.
public class MyListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<Alphabet> alphabetList;
private ArrayList<Alphabet> originalList;
public MyListAdapter(Context context, ArrayList<Alphabet> alphabetList){
this.context = context;
this.alphabetList = new ArrayList<Alphabet>();
this.alphabetList.addAll(alphabetList);
this.originalList = new ArrayList<Alphabet>();
this.originalList.addAll(alphabetList);
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
return alphabetList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
ArrayList<Waste> wasteList = alphabetList.get(groupPosition).getWasteList();
return wasteList.size();
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return alphabetList.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
ArrayList<Waste> wasteList = alphabetList.get(groupPosition).getWasteList();
return wasteList.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Alphabet alphabet = (Alphabet) getGroup(groupPosition);
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.group_row, null);
}
TextView heading = (TextView) convertView.findViewById(R.id.heading);
heading.setText(alphabet.getName().trim());
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Waste waste = (Waste) getChild(groupPosition, childPosition);
if(convertView == null){
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.child_row, null);
}
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(waste.getName().trim());
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
public void filterData(String query)
{
query = query.toLowerCase();
Log.v("MyListAdapter", String.valueOf(alphabetList.size()));
alphabetList.clear();
if(query.isEmpty())
{
alphabetList.addAll(originalList);
} else {
for(Alphabet alphabet: originalList)
{
ArrayList<Waste> wasteList = alphabet.getWasteList();
ArrayList<Waste> newList = new ArrayList<Waste>();
for(Waste waste: wasteList)
{
if(waste.getName().toLowerCase().contains(query)){
newList.add(waste);
}
}
if(newList.size() > 0)
{
Alphabet nAlphabet = new Alphabet(alphabet.getName(), newList);
alphabetList.add(nAlphabet);
}
}
}
Log.v("MyListAdapter", String.valueOf(alphabetList.size()));
notifyDataSetChanged();
}
}
SegregateWasteActivity.java
public class SegregateWasteActivity extends Activity implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private SearchView search;
private MyListAdapter listAdapter;
private ExpandableListView myList;
private ArrayList<Alphabet> alphabetList = new ArrayList<Alphabet>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.segregate_waste_activity);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
search = (SearchView) findViewById(R.id.search);
search.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
displayList();
expandAll();
}
#Override
public boolean onClose() {
// TODO Auto-generated method stub
listAdapter.filterData("");
expandAll();
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
listAdapter.filterData(query);
expandAll();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
listAdapter.filterData(newText);
expandAll();
return false;
}
private void expandAll()
{
int count = listAdapter.getGroupCount();
for(int i = 0; i < count; i++)
{
myList.expandGroup(i);
}
}
private void displayList()
{
loadSomeData();
myList = (ExpandableListView) findViewById(R.id.expandableList);
listAdapter = new MyListAdapter(SegregateWasteActivity.this, alphabetList);
myList.setAdapter(listAdapter);
}
private void loadSomeData()
{
ArrayList<Waste> wasteList = new ArrayList<Waste>();
Waste waste = new Waste("Aerozol");
wasteList.add(waste);
waste = new Waste("Aaaa");
wasteList.add(waste);
Alphabet alphabet = new Alphabet("A", wasteList);
alphabetList.add(alphabet);
wasteList = new ArrayList<Waste>();
waste = new Waste("Butelka");
wasteList.add(waste);
alphabet = new Alphabet("B", wasteList);
alphabetList.add(alphabet);
}
}
and I want to this fragment throw:
#Override
protected void onListItemClick(ListView lv, View v, int position, long id){
super.onListItemClick(lv, v, position, id);
String openClass = classNames[position];
try{
Class selected = Class.forName("com.odpad.odpadygdansk.waste." + openClass);
Intent selectedIntent = new Intent(this, selected);
startActivity(selectedIntent);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
so I can click on an item from the list to go to the new activity with the same name as the class name.
I believe you want something like this:
expListView.setOnChildClickListener(new ExpandableListView
.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView elv, View view, int i,
int i2, long l) {
TextView tv = view.findViewById(R.id.name);
String name = (String) tv.getText();
try {
// Change package.name to your package
Class cls = Class.forName("package.name." + name);
Intent intent = new Intent(MainActivity.this, cls);
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return false;
}
});
The code is pretty much self-explanatory.
You could use the position argument i received in the click callback, to fetch the specific name instead of findViewById(). That would be somewhat more efficient.
I want to call another activity when i click button which is child view of expandable listview in Android.When i run the activity does not show the expandable listview.How to work on exapandable list view.Can some one give me idea how to do this.
Here is my Activity code
public class My_Project extends ExpandableListActivity
{
ExpandableListView expListView;
Button btnNewProject;
Button btn_myprojectdefinemyteam;
DBHelper databaseHelper;
SQLiteDatabase db;
ImageView imgButtonBack;
List dispDataList;
String[] array;
String[] Task_Title_Size;
String[] Task_Start_Date_Size;
String[] Task_CompletionDate_Size;
String[] Task_CompletionTime_Size;
String[] Task_Description_Size;
String[] Task_Status_Size;
String[] Task_IsActive_Size;
String[] dtrProjectNAmeSize;
public static final String Task_Title = "Task_Titles";
public static final String Task_Start_Date = "start_date";
public static final String Task_CompletionDate = "completion_date";
public static final String Task_CompletionTime = "completion_time";
public static final String Task_Description = "task_description";
public static final String Task_Status = "task_status";
public static final String Task_IsActive ="IS_Active";
private int ParentClickStatus=-1;
private int ChildClickStatus=-1;
Myexpandable_ListAdapter mAdapter;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.my_project);
imgButtonBack = (ImageView)findViewById(R.id.imagBackButton);//ImageView imgButtonBack;
imgButtonBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent iBack = new Intent(My_Project.this , Menu.class);
startActivity(iBack);
finish();
}
});
expListView = (ExpandableListView) findViewById(android.R.id.list);
databaseHelper = new DBHelper(getApplicationContext());
dispDataList=databaseHelper.viewMyProjectDetals();
dtrProjectNAmeSize=new String[dispDataList.size()];
System.out.println(" dtrProjectNAmeSize = " + dtrProjectNAmeSize);
if ( dispDataList.size() > 6 )
{
Task_Title_Size=(String[])dispDataList.get(0);
Task_Start_Date_Size=(String[]) dispDataList.get(1);
Task_CompletionDate_Size = (String[])dispDataList.get(2);
Task_CompletionTime_Size=(String[])dispDataList.get(3);
Task_Description_Size=(String[]) dispDataList.get(4);
Task_Status_Size = (String[])dispDataList.get(5);
Task_IsActive_Size = (String[])dispDataList.get(6);
for(int i=0;i<Task_Title_Size.length;i++)
{
System.out.println("New data :"+Task_Title_Size[i]);
}
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
for (int i = 0; i < Task_Title_Size.length ; i++)
{
Map<String, String> curGroupMap = new HashMap<String, String>();
groupData.add(curGroupMap);
curGroupMap.put(Task_Title,"" +Task_Title_Size[i]);
List<Map<String, String>> children = new ArrayList<Map<String, String>>();
Map<String, String> curChildMap = new HashMap<String, String>();
children.add(curChildMap);
curChildMap.put(Task_Start_Date,"" +Task_Start_Date_Size[i]);
curChildMap.put(Task_CompletionDate,"" +Task_CompletionDate_Size[i]);
curChildMap.put(Task_CompletionTime,"" +Task_CompletionTime_Size[i]);
curChildMap.put(Task_Description,"" +Task_Description_Size[i]);
curChildMap.put(Task_Status,"" +Task_Status_Size[i]);
curChildMap.put(Task_IsActive,"" +Task_IsActive_Size[i]);
childData.add(children);
}
mAdapter =new Myexpandable_ListAdapter(
this,
groupData,
R.layout.list_group,
new String[] { Task_Title },
new int[] {R.id.lblListHeader },
childData,
R.layout.child_item,
new String[] { Task_Start_Date , Task_CompletionDate , Task_CompletionTime , Task_Description , Task_Status , Task_IsActive},
new int[] { R.id.TextView_Projectdetails , R.id.textOne , R.id.textTwo , R.id.textThree , R.id.textFour, R.id.textFive}
);
expListView.setAdapter(mAdapter);
}
expListView.setOnGroupClickListener(new OnGroupClickListener()
{
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id)
{
return false;
}
});
//editTextTaskName = (EditText)findViewById(R.id.Task_Name);
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
dtrProjectNAmeSize.length + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
dtrProjectNAmeSize.length + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
btnNewProject = (Button)findViewById(R.id.buttonmyproject_NewProject);
btnNewProject.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(My_Project.this , Add_Project.class);
startActivity(i);
finish();
}
});
}
private class Myexpandable_ListAdapter extends BaseExpandableListAdapter {
public Myexpandable_ListAdapter(Context context,
List<? extends Map<String, ?>> groupData,
int expandedGroupLayout,
String[] groupFrom, int[] groupTo,
List<? extends List<? extends Map<String, ?>>> childData,
int childLayout, String[] childFrom,
int[] childTo) {
super();
// TODO Auto-generated constructor stub
}
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
Context context;
public Object getChild(int groupPosition, int childPosition)
{
//this.get(groupPosition).getChildren().get(childPosition);
String strchildPosition = this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosition);
System.out.println("Child Position =" + strchildPosition);
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosition);
}
//Call when child row clicked
#Override
public long getChildId(int groupPosition, int childPosition)
{
/****** When Child row clicked then this function call *******/
//Log.i("Noise", "parent == "+groupPosition+"= child : =="+childPosition);
if( ChildClickStatus!=childPosition)
{
ChildClickStatus = childPosition;
Toast.makeText(getApplicationContext(), "Parent :"+groupPosition + " Child :"+childPosition ,
Toast.LENGTH_LONG).show();
}
return childPosition;
}
public View getChildView1(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
return parent;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_item, null);
}
TextView txtListChild = (TextView) convertView.findViewById(R.id.TextView_Projectdetails);
TextView txtOneListChild = (TextView)convertView.findViewById(R.id.textOne);
TextView txtTwoListChild = (TextView)convertView.findViewById(R.id.textTwo);
TextView txtThreeListChild = (TextView)convertView.findViewById(R.id.textThree);
TextView txtFourListChild = (TextView)convertView.findViewById(R.id.textFour);
TextView txtFiveListChild = (TextView)convertView.findViewById(R.id.textFive);
txtListChild.setText(childText);
txtOneListChild.setText(childText);
txtTwoListChild.setText(childText);
txtThreeListChild.setText(childText);
txtFourListChild.setText(childText);
txtFiveListChild.setText(childText);
Button btnAssgnTask = (Button)convertView.findViewById(R.id.button_EditedTask);
btnAssgnTask.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
Button btnViewTask = (Button)convertView.findViewById(R.id.buttonViewTask);
btnViewTask.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return ParentClickStatus;
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}
Thanks in Advance.
your problem is here:
#Override
public int getGroupCount() {
return ParentClickStatus;
}
as you extends BaseExpandableListAdapter, getChildrenCount and getGroupCount handle number of your view and as ParentClickStatus is equal to -1 getGroupView never called
solution
you need return group row number that you have, so change your code with:
#Override
public int getGroupCount() {
return _listDataHeader.size();
}
for an example you can see section 15. Implementing an expandable ListView
UPDATE
you need change your constructor too:
public Myexpandable_ListAdapter(Context context,
List<? extends Map<String, ?>> groupData,
int expandedGroupLayout,
String[] groupFrom, int[] groupTo,
List<? extends List<? extends Map<String, ?>>> childData,
int childLayout, String[] childFrom,
int[] childTo) {
super();
// TODO Auto-generated constructor stub
}
you passed your data to here, but you don't set to any local data, for example you tried to use _listDataChild in getChild method, but you not initialize that at all, you need initialize that in constructor with your data that passed here.
I have an ArrayList of Person class containing age and name of the person. In the adapter (extends BaseAdapter), I have two TextViews(for setting the values of age and name) and a checkbox. This is needed to be inflated into alert dialog.
How can I implement this using multichoice of the alert dialog.
Also I did look at some examples but did not understand about the boolean[] values attribute in the alert dialog, this is the code I have so far but it still needs to implement that multichoice mode..
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:choiceMode="multipleChoice">
</ListView>
My alertdialog..
AlertDialog.Builder ab=new AlertDialog.Builder(CustomListActivity.this);
LayoutInflater linf=(LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View v1=linf.inflate(R.layout.dialog_list, null);
ab.setView(v1);
//ab.setTitle("Select a group");
lv=(ListView) v1.findViewById(R.id.listView1);
ma=new MyAdapter(CustomListActivity.this, plist);
lv.setAdapter(ma);
And MYAdapter ..
public class MyAdapter extends BaseAdapter
{
Context ctx;
ArrayList<Person> plist;
LayoutInflater linf;
public PersonHolder ph=null;
public MyAdapter(Context ctx, ArrayList<Person> plist) {
super();
this.ctx = ctx;
this.plist = plist;
}
public class PersonHolder
{
public TextView age;
public TextView name;
public CheckBox check;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return plist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return plist.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
linf=(LayoutInflater) ctx.getSystemService(ctx.LAYOUT_INFLATER_SERVICE);
if(convertView==null)
{
convertView=linf.inflate(R.layout.row_item, null);
ph=new PersonHolder();
ph.age=(TextView) convertView.findViewById(R.id.text1);
ph.name=(TextView) convertView.findViewById(R.id.text2);
ph.check=(CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(ph);
}
else
{
ph=(PersonHolder) convertView.getTag();
}
Person p=(Person) getItem(position);
ph.age.setText(p.getAge());
ph.name.setText(p.getName());
ph.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
// if(ph.check.isChecked())
// {
ph.check.setSelected(arg1);
// }
// else
// {
// ph.check.setSelected(false);
// }
}
});
return convertView;
}
}
Change your adapter to following and just call getSelected on adapter.
public class MyAdapter extends BaseAdapter
{
Context ctx;
ArrayList<Person> plist;
LayoutInflater linf;
public PersonHolder ph=null;
private ArrayList<Integer> selected=new ArrayList<Integer>();
public MyAdapter(Context ctx, ArrayList<Person> plist) {
super();
this.ctx = ctx;
this.plist = plist;
}
public class PersonHolder
{
public TextView age;
public TextView name;
public CheckBox check;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return plist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return plist.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
linf=(LayoutInflater) ctx.getSystemService(ctx.LAYOUT_INFLATER_SERVICE);
if(convertView==null)
{
convertView=linf.inflate(R.layout.row_item, null);
ph=new PersonHolder();
ph.age=(TextView) convertView.findViewById(R.id.text1);
ph.name=(TextView) convertView.findViewById(R.id.text2);
ph.check=(CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(ph);
}
else
{
ph=(PersonHolder) convertView.getTag();
}
Person p=(Person) getItem(position);
ph.age.setText(p.getAge());
ph.name.setText(p.getName());
ph.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
// if(ph.check.isChecked())
// {
ph.check.setSelected(arg1);
if(arg1){
selected.add(position);
}else{
selected.remove(position);
}
// }
// else
// {
// ph.check.setSelected(false);
// }
}
});
return convertView;
}
public ArrayList<Integer> getSelected(){
return selected;
}
}
I have created a multichoice dialog myself, this is what i am doing, basically you need to catch each click to the listview and memorize whatever it is you selected/set there.
private void startDayPickerDialog() {
String[] days = getActivity().getResources().getStringArray(R.array.dayNames);
days = Arrays.copyOf(days, 7);
final Adapter a = new Adapter(getActivity());
AlertDialog d = new AlertDialog.Builder(getActivity())
.setTitle(R.string.repeat)
.setAdapter(a, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).setPositiveButton(R.string.done, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
d.getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> lv, View view, int position, long id) {
CheckBox cb = (CheckBox)view.findViewById(R.id.checkbox);
cb.setChecked(!cb.isChecked());
a.getItem(position).setChecked(!a.getItem(position).isChecked());
}
});
d.setCanceledOnTouchOutside(true);
d.show();
}