EditText disappears after closing expandedView - android

The problem I am having is the text that I type in the expanded view, is not being saved. The moment I close one group to open another, all the values saved in the first disappear. Can anyone advise me what to do so it can be saved not just for when I open the expandedView but also for when I restart it or resume it. I'm not sure how to use the onResume and onRestart functions. Thanks
I am attaching the code as well:
import android.content.Context;
import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.TextView;
public class MyAdapter extends BaseExpandableListAdapter
{
private int counter;
SharedPreferences getPrefs;
private Context context;
String[] parent= new String [4];
String[][] child= new String [4][4];
String [][] weights= new String [4][4];
boolean KU=false;
boolean MC=false;
boolean TI=false;
boolean C=false;
boolean allEdited=false;
EditText et1;
EditText et2;
EditText et3;
EditText et4;
public MyAdapter(Context context)
{
this.context=context;
}
#Override
public Object getChild(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
ViewGroup parent)
{
counter++;
if (!allEdited)
{
et1= new EditText (context);
et2= new EditText (context);
et3= new EditText (context);
et4= new EditText (context);
child[groupPosition][0]=et1.getText().toString();
child[groupPosition][1]=et2.getText().toString();
child[groupPosition][2]=et3.getText().toString();
child[groupPosition][3]=et4.getText().toString();
}
if(!KU)
{
et1.setText(child[groupPosition][childPosition]);
et1.setPadding(50, 10, 10, 10);
et1.setTextSize(15);
et1.setTextColor(Color.WHITE);
et1.setFocusable(true);
et1.setInputType(0x00000002);
weights[groupPosition][0]=(et1.getText().toString());
}
if (!et1.getText().toString().equals(""))
{
KU=true;
}
if(KU)
{
et1.setText(weights[groupPosition][0]);
et1.setFreezesText(true);
}
if (!MC)
{
et2.setText(child[groupPosition][childPosition]);
et2.setPadding(50, 10, 10, 10);
et2.setTextSize(15);
et2.setTextColor(Color.WHITE);
et2.setFocusable(true);
et2.setInputType(0x00000002);
weights[groupPosition][1]=(et2.getText().toString());
}
else if (!et2.getText().toString().equals(""))
{
MC=true;
}
weights[groupPosition][1]=(et2.getText().toString());
if(MC)
{
et1.setText(weights[groupPosition][1]);
}
if (!TI)
{
et3.setText(child[groupPosition][childPosition]);
et3.setPadding(50, 10, 10, 10);
et3.setTextSize(15);
et3.setTextColor(Color.WHITE);
et3.setFocusable(true);
et3.setInputType(0x00000002);
weights[groupPosition][2]=(et3.getText().toString());
}
else if (!et3.getText().toString().equals(""))
{
TI=true;
}
weights[groupPosition][2]=(et3.getText().toString());
if(TI)
{
et3.setText(weights[groupPosition][2]);
}
if (!C)
{
et4.setText(child[groupPosition][childPosition]);
et4.setPadding(50, 10, 10, 10);
et4.setTextSize(15);
et4.setTextColor(Color.WHITE);
et4.setFocusable(true);
et4.setInputType(0x00000002);
weights[groupPosition][3]=(et4.getText().toString());
}
else if (!et4.getText().toString().equals(""))
{
C=true;
}
weights[groupPosition][3]=(et1.getText().toString());
if(C)
{
et4.setText(weights[groupPosition][3]);
}
if (KU && MC && TI && C)
{
allEdited=true;
}
if (counter==1)
return et1;
else if (counter==2)
return et2;
else if (counter==3)
return et3;
else if (counter==4)
return et4;
else
counter=0; return et1;
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return child[groupPosition].length;
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public int getGroupCount()
{
return parent.length;
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
{
TextView tv= new TextView (context);
this.parent[groupPosition]=tv.getText().toString();
getPrefs = PreferenceManager.getDefaultSharedPreferences(context);
String allCourses= getPrefs.getString("allClasses", "Please enter your course code");
String[] courses= allCourses.split(",");
for (int i=0;i<courses.length;i++)
{
this.parent[i]=courses[i];
}
tv.setText(this.parent[groupPosition]);
tv.setPadding(50, 10, 10, 10);
tv.setTextSize(20);
tv.setTextColor(Color.GREEN);
return tv;
}

you should use a Custom List Adapter, and whenever you type something in textview, have a list and assign it to the list for particular index(position)

As #Kapil said you can use list to store the values but those values will be destroyed once the activity is destroyed. If you want a permanent storage i.e. the values should remain even if you restart the app the should use Shared Preferences or SQLite Database.

Related

How can I Pass Name & Country from Entry Item

I am developer a Apps which contain Various Name & Country List. I want to pass Employee Name & Country name to another activity on click on Child Item of Expandable ListView.
How to set On Click Listener Method on my Activity?
package nasir.main.activity;
import java.util.ArrayList;
import nasir.adapter.EntryItem;
import nasir.adapter.MyListAdapter;
import nasir.adapter.SectionItem;
import nasir.bd.poem.R;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.SearchView;
public class Employee_List extends Activity implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {
Button Collapse;
Button Expand;
private SearchView search;
private MyListAdapter listAdapter;
private ExpandableListView myList;
private ArrayList<SectionItem> section = new ArrayList<SectionItem>();
ArrayList<EntryItem> items = new ArrayList<EntryItem>();
ExpandableListView expandableList = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poem_list);
expandableList = (ExpandableListView) findViewById(R.id.expandableList);
Expand = (Button) findViewById(R.id.Expand);
Collapse = (Button) findViewById(R.id.Collapse);
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);
Collapse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.collapseGroup(i);
}
Collapse.setVisibility(View.GONE);
Expand.setVisibility(View.VISIBLE);
}
});
Expand.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.expandGroup(i);
}
Expand.setVisibility(View.GONE);
Collapse.setVisibility(View.VISIBLE);
}
});
// display the list
displayList();
// expand all Groups
// expandAll();
collapseAll();
}
// method to expand all groups
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++) {
myList.expandGroup(i);
}
}
//method to Collapse all groups
private void collapseAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.collapseGroup(i);
}
}
// method to expand all groups
private void displayList() {
// display the list
load_Part_1_Data();
// get reference to the ExpandableListView
myList = (ExpandableListView) findViewById(R.id.expandableList);
// create the adapter by passing your ArrayList data
listAdapter = new MyListAdapter(Poem_List.this, section);
// attach the adapter to the list
myList.setAdapter(listAdapter);
myList.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2,
int arg3, long arg4) {
// TODO Auto-generated method stub
Intent intent = new Intent(Poem_List.this, Details_Information.class);
startActivity(intent);
return false;
}
});
}
private void load_Part_1_Data() {
items = new ArrayList<EntryItem>();
section.add(new SectionItem(R.drawable.ic_launcher, "", items));
items.add(new EntryItem(R.drawable.ic_launcher, "Margerate Milan", "Computer Operator", getString(R.string.app_name)));
items.add(new EntryItem(R.drawable.ic_launcher, "Abraham Jhon", "Salse Man", getString(R.string.app_name)));
items = new ArrayList<EntryItem>();
section.add(new SectionItem(R.drawable.blank_image, "", items));
items.add(new EntryItem(R.drawable.ic_launcher, "England", "Europe", getString(R.string.app_name)));
items.add(new EntryItem(R.drawable.ic_launcher, "Japan", "Asia", getString(R.string.app_name)));
}
#Override
public boolean onClose() {
listAdapter.filterData("");
expandAll();
return true;
}
#Override
public boolean onQueryTextChange(String query) {
listAdapter.filterData(query);
expandAll();
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
listAdapter.filterData(query);
expandAll();
return false;
}
}
MyListAdapter.Class
package nasir.adapter;
import java.util.ArrayList;
import nasir.bd.poem.R;
import nasir.main.activity.Details_Information;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<SectionItem> continentList;
private ArrayList<SectionItem> originalList;
public MyListAdapter(Context context, ArrayList<SectionItem> continentList) {
this.context = context;
this.continentList = new ArrayList<SectionItem>();
this.continentList.addAll(continentList);
this.originalList = new ArrayList<SectionItem>();
this.originalList.addAll(continentList);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<EntryItem> countryList = continentList.get(groupPosition).getSectionList();
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) {
final EntryItem country = (EntryItem) getChild(groupPosition, childPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.child_row, null);
}
ImageView Rank = (ImageView) view.findViewById(R.id.Rank);
TextView Poem = (TextView) view.findViewById(R.id.Poem);
TextView Poetry = (TextView) view.findViewById(R.id.Poetry);
Rank.setImageResource(country.getRank());
Poem.setText(country.getPoem().trim());
Poetry.setText(country.getPoetry().trim());
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Details_Information.class);
Bundle bundle=new Bundle();
intent.putExtras(bundle);
intent.putExtra("header", country.getDetails_Doc());
context.startActivity(intent);
}
});
return view;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<EntryItem> countryList = continentList.get(groupPosition).getSectionList();
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) {
SectionItem continent = (SectionItem) 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());
ImageView Group_icon = (ImageView) view.findViewById(R.id.Group_Icon);
Group_icon.setImageResource(continent.getIcon());
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 (SectionItem continent : originalList) {
ArrayList<EntryItem> countryList = continent.getSectionList();
ArrayList<EntryItem> newList = new ArrayList<EntryItem>();
for (EntryItem country : countryList) {
if (country.getPoem().toLowerCase().contains(query) || country.getPoetry().toLowerCase().contains(query) ) {
newList.add(country);
}
}
if (newList.size() > 0) {
SectionItem nContinent = new SectionItem(continent.getIcon(), continent.getName(), newList);
continentList.add(nContinent);
}
}
}
Log.v("MyListAdapter", String.valueOf(continentList.size()));
notifyDataSetChanged();
}
}
In the Employee_List activity , you can access the data through index of child and group obtaining from ChildClickListener
myList.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2,
int arg3, long arg4) {
// TODO Auto-generated method stub
//Here You can access the child data by
final EntryItem country = (EntryItem) listAdapter .getChild(arg2, arg3);
//From here you can pass the data through Intent
...
return false;
}
});

How to create another activity on Expandable List View Child what gonna present recent and upcoming event pulled from Database?

I'm working on my project where I created Expandable List View with Men's and Women's sports. Each of them expands the list with sports like soccer, baseball, basketball, volleyball, golf. Now I'm at the point where I have to click on the one of the sports what gonna open new page, on that page will be presented previous games with results and upcoming events for each sport. All information's will be fetched from data base form athletic website. I do not how to make new page for individual sports with all information's what should be presented. Here is my code. Thanks in advance! Here is my code:
1)**MainActivity.java**
package com.example.athletic_project.java;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Toast;
public class MainActivity<View> extends ActionBarActivity {
ExpandableListView exv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
exv=(ExpandableListView)findViewById(R.id.expandableListView1);
exv.setAdapter(new MyAdapter(this));
exv.setOnChildClickListener(new OnChildClickListener(){
#Override
public boolean onChildClick(ExpandableListView parent,
android.view.View v, int groupPosition, int childPosition,
long id) {
// TODO Auto-generated method stub
String itemclicked=MyAdapter.childList[groupPosition][childPosition];
Toast.makeText(MainActivity.this, itemclicked + " is clicked.", Toast.LENGTH_SHORT).show();
return false;
}
});
}
}
2)**MyAdapter.java**
package com.example.athletic_project.java;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class MyAdapter extends BaseExpandableListAdapter {
private Context context;
Typeface typeface;
static String []parentList = {"Men's Sports","Women's Sports"};
static String [][]childList = {
{
"Baseball","Basketball","Bowling","Cross Country","Golf","Soccer","Track & Field"
},
{
"Baseball","Basketball","Bowling","Cross Country","Golf","Soccer","Track & Field","Volleyball"
}
};
public MyAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context=context;
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
return parentList.length;
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return childList[groupPosition].length;
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return null;
}
#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 0;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
typeface=Typeface.createFromAsset(context.getAssets(),"fonts/KGTribecaStamp.ttf");
TextView tv = new TextView(context);
tv.setText(parentList[groupPosition]);
tv.setPadding(45, 10, 10, 10);
tv.setTextSize(18);
tv.setTextColor(Color.BLUE);
tv.setTypeface(typeface);
return tv;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
typeface=Typeface.createFromAsset(context.getAssets(),"fonts/KGTribecaStamp.ttf");
TextView tv = new TextView(context);
tv.setText(childList[groupPosition][childPosition]);
tv.setPadding(45, 10, 10, 10);
tv.setTextSize(15);
tv.setTextColor(Color.WHITE);
tv.setTypeface(typeface);
return tv;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
3)**activity_main.xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/mtfinal"
>
<ExpandableListView
android:id="#+id/expandableListView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:dividerHeight="1.5dp"
>
</ExpandableListView>
</LinearLayout>
In addChildView add onClickListener like
tv.setOnClickListener(itemClick)
itemClick field of adapter. Initilize it from constructor (may be null of no clicks expected)
Also set to view tag
tv.setTag
Later in click listener get tag as key of pressed item and start your activity with this extra in intent to fetch appropriate data from DB to show
Like this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
exv=(ExpandableListView)findViewById(R.id.expandableListView1);
exv.setAdapter(new MyAdapter(this, new OnClickListener() {
#Override
public void onClick(android.view.View v) {
// or any other key Object
if( v.getTag() instanceof String ) {
startPageActivity( (String)v.getTag());
}
}
}));
}
private void startPageActivity(String key) {
Intent intent=new Intent(MainActivity.this, SomeActivity.class);
intent.putExtra(KEY_NAME, key);
startActivity(intent);
}
public MyAdapter(Context context, OnClickListener listener) {
this.listener=listener;
this.context=context;
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
TextView tv = new TextView(context);
tv.setText(childList[groupPosition][childPosition]);
tv.setPadding(45, 10, 10, 10);
tv.setTextSize(15);
tv.setTextColor(Color.BLACK);
// setup listener
tv.setOnClickListener(listener);
// u may set any Object
tv.setTag(childList[groupPosition][childPosition]);
return tv;
}
public class SomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String stringKey = getIntent().getExtras().getString(MainActivity.KEY_NAME);
//do something with passed key - fro example get data from DB to show
Toast.makeText(this, stringKey + " in new activity", Toast.LENGTH_SHORT).show();
}
}

saving hashmaps locally on android

I have an expandableListView which contains a number of checkboxes inside. For my app, I would like to be able to save the check value of these checklists, however, I can't use sharedPreferences, as i Have to use a Hashmap which contains an array of booleans. This is my code
import java.util.HashMap;
import java.util.Map.Entry;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
public class ExpListAdapter extends BaseExpandableListAdapter {
private Context context;
//second attempt to hold the values
private SharedPreferences inventorylistcheckStateData;
private String[] parentList = { "Bedding", "Bedroom Items", "Clothing",
"Bags", "Stationary", "Documents", "Electronics", "Toiletries",
"Kitchen Items" };
// used to retain our checklist values, which for some reason dont stick.
private HashMap<Integer, boolean[]> checkState;
// multidimensional string storage is needed as you are storing values for
// two lists.
private String[][] childList = {
{ "Single/Double sheets", "Single/Double duvet + Covers",
"Pillows + Pillow cases" },
{ "Alarm Clock", "Posters", "Door Wedge", "Lamp", "Small Bin",
"Hamper Basket" },
{ "Casual Clothes, i.e T shirts, jeans, hoodies",
"Smart clothing for interviews and presentations",
"Warm Clothing (especially for newcastle)",
"'Party Clothes' clothes for going out",
"Underwear and socks", "pyjamas", "Comfortable shoes",
"Sports trainers", "Swimwear" },
{ "Everyday bag/backpack", "Gym bag", "Clear Pencil Case",
"Purse/Wallet", "Watch" },
{ "Pins", "A4 Notebooks", "Pens/Pencils", "Highlighters", "Ruler",
"Rubber", "Selotape", "Hole Puncher", "A4 Binders",
"Calculater", "Calender" },
{ "Passport photos", "Passport",
"Driving License (some form of id)", "Your NI Card",
"Insurance Documents", "NHS Medical Card",
"Insurance documents", "Letter of Acceptance",
"Scholarship/bursury letters",
"Rail Card(if you have one)", "C.V" },
{ "Laptop+Charger", "Mouse", "Phone + Charger", "Ethernet Cables",
"USB memory stick", "Headphones", "Digital Camera",
"MP3 Player" },
{ "Shampoo", "Razors", "Toothbrush and toothpaste",
"Make-up/remover", "HairBrush",
"Condoms or other protection!!!" },
{ "Frying Pan", "Wok", "Tin Opener", "Bottle opener", "Glasses",
"Cheese Grater", "Knives", "Chopping Board", "Scissors",
"Tea Towels", "Tupperware", "Cling Film", "Cutlery",
"Crockery" } };
public ExpListAdapter(Context context) {
this.context = context;
// initialised check
checkState = new HashMap<Integer, boolean[]>();
}
public Object getChild(int groupPosition, int childPosition) {
return childPosition;
}
//
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return 0;
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final int mGroupPosition = groupPosition;
final int mChildPosition = childPosition;
CheckBox checkbox = new CheckBox(context);
checkbox.setOnCheckedChangeListener(null);
if (checkState.containsKey(mGroupPosition)) {
boolean getChecked[] = checkState.get(mGroupPosition);
checkbox.setChecked(getChecked[mChildPosition]);
} else {
boolean getChecked[] = new boolean[getChildrenCount(mGroupPosition)];
checkState.put(mGroupPosition, getChecked);
checkbox.setChecked(false);
}
checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
boolean getChecked[] = checkState.get(mGroupPosition);
getChecked[mChildPosition] = isChecked;
checkState.put(mGroupPosition, getChecked);
} else {
boolean getChecked[] = checkState.get(mGroupPosition);
getChecked[mChildPosition] = isChecked;
checkState.put(mGroupPosition, getChecked);
}
}
});
checkbox.setText(childList[groupPosition][childPosition]);
checkbox.setPadding(40, 0, 0, 0);
//SharedPreferences.Editor editor = inventorylistcheckStateData.edit();
//for (Entry<Integer, boolean[]> entry: checkState.entrySet()) editor.putBoolean(entry.getKey().toString(), entry.getValue());
return checkbox;
}
// returns the number of children you are having.
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return childList[groupPosition].length;
}
// returns the number of parents you have.
public Object getGroup(int groupPosition) {
return groupPosition;
}
public int getGroupCount() {
// TODO Auto-generated method stub
return parentList.length;
}
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
TextView text = new TextView(context);
text.setText(parentList[groupPosition]);
text.setPadding(40, 0, 0, 0);
return text;
}
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
Is there anyway i can save the checklists , or do I have to change everything?
SharedPreferences keyValues = getContext().getSharedPreferences("Your_Shared_Prefs"), Context.MODE_PRIVATE);
SharedPreferences.Editor keyValuesEditor = keyValues.edit();
for (String s : checklist.keySet()) {
keyValuesEditor.putString(s, checklist.get(s));
}
keyValuesEditor.commit();

when scroll up & down in expandable list views get change

Im using an expandable list in my app,my question is when i scroll up and down in the list, views get changed, please let me know how to fix this
Thanks,
Sam.
below is the code
package com.test.android;
import java.util.ArrayList;
import java.util.Random;
import android.app.ExpandableListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.TextView;
/**
* Demonstrates expandable lists using a custom {#link ExpandableListAdapter}
* from {#link BaseExpandableListAdapter}.
*/
public class ExpandableList1 extends ExpandableListActivity {
MyExpandableListAdapter mAdapter;
ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up our adapter
mAdapter = new MyExpandableListAdapter(this);
setListAdapter(mAdapter);
}
/**
* A simple adapter which maintains an ArrayList of photo resource Ids.
* Each photo is displayed as an image. This adapter supports clearing the
* list of photos and adding a new photo.
*
*/
private Handler actionhandler = new Handler(){
/* (non-Javadoc)
* #see android.os.Handler#handleMessage(android.os.Message)
*/
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
mAdapter.notifyDataSetChanged();
progressDialog.dismiss();
}
};
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
private ArrayList<String> groups = new ArrayList<String>();
private ArrayList<ArrayList<String>> children = new ArrayList<ArrayList<String>>();
private Context context;
public MyExpandableListAdapter(Context context) {
super();
this.context = context;
groups.add("People Names");
groups.add("Dog Names");
groups.add("Cat Names");
groups.add("Fish Names");
ArrayList<String> child1 = new ArrayList<String>();
child1.add("Arnold-1");
child1.add("Barry-2");
child1.add("Chuck-3");
child1.add("David-4");
child1.add("Arnold-5");
child1.add("Barry-6");
child1.add("Chuck-7");
child1.add("David-8");
child1.add("Arnold-9");
child1.add("Barry-10");
child1.add("Chuck-11");
child1.add("David-12");
child1.add("Arnold-13");
child1.add("Barry-14");
child1.add("Chuck-15");
child1.add("David-16");
children.add(child1);
ArrayList<String> child2 = new ArrayList<String>();
child2.add("Ace-17");
child2.add("Bandit-18");
child2.add("Cha-Cha-19");
child2.add("Deuce-20");
children.add(child2);
ArrayList<String> child3 = new ArrayList<String>();
child3.add("Fluffy-21");
child3.add("Snuggles-22");
child3.add("Fluffy-23");
child3.add("Snuggles-24");
child3.add("Fluffy-25");
child3.add("Snuggles-26");
child3.add("Fluffy-27");
child3.add("Snuggles-28");
child3.add("Fluffy-29");
child3.add("Snuggles-30");
child3.add("Fluffy-31");
child3.add("Snuggles-32");
child3.add("Fluffy-33");
child3.add("Snuggles-34");
children.add(child3);
ArrayList<String> child4 = new ArrayList<String>();
child4.add("Goldy-35");
child4.add("Bubbles-36");
child4.add("dummy-37");
child4.add("Goldy-38");
child4.add("Bubbles-39");
child4.add("dummy-40");
child4.add("Goldy-41");
child4.add("Bubbles-42");
child4.add("dummy-43");
child4.add("Goldy-44");
child4.add("Bubbles-45");
child4.add("dummy-46");
child4.add("Goldy-47");
child4.add("Bubbles-48");
child4.add("dummy-49");
children.add(child4);
}
public Object getChild(int groupPosition, int childPosition) {
return children.get(groupPosition).get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public int getChildrenCount(int groupPosition) {
//if childern not avaibles.
return children.get(groupPosition).size();
}
private void getMoreData(int groupPosition, int childPosition){
Log.e("getMoreData", "calling groupPosition:"+groupPosition +"|childPosition:"+childPosition);
//remove the dummay record
children.get(groupPosition).remove(childPosition);
//adding a new group with data.
Random randomGenerator = new Random();
int count = randomGenerator.nextInt(100);
groups.add("More Data:" + count);
ArrayList<String> newData = new ArrayList<String>();
newData.add("Arnold"+count);
newData.add("Barry"+ count);
newData.add("Chuck"+ count);
newData.add("David"+ count);
children.add(newData);
//removing a record from exssitng group.
children.get(0).remove(0);
children.get(0).add("add to group0 shaggy");
//adding a record to group
children.get(1).add("shaggy add to group 2 shaggy");
//remove a groiup and corresponding childrens
groups.remove(2);
children.remove(2);
//adding a new record to last group.
children.get(groups.size()-1).add("new record");
//adding a dummy record to last group.
children.get(groups.size()-1).add("dummy");
}
public TextView getGenericView() {
// Layout parameters for the ExpandableListView
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, 64);
TextView textView = new TextView(ExpandableList1.this);
textView.setLayoutParams(lp);
// Center the text vertically
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
textView.setPadding(36, 0, 0, 0);
return textView;
}
public Button getGenericButton(final int groupPosition,final int childPosition) {
// Layout parameters for the ExpandableListView
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, 64);
Button button = new Button(ExpandableList1.this);
button.setText("More");
button.setLayoutParams(lp);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
progressDialog = ProgressDialog.show(context, null, "Please Wait");
new Thread(){
/* (non-Javadoc)
* #see java.lang.Thread#run()
*/
#Override
public void run() {
getMoreData(groupPosition,childPosition);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
actionhandler.sendEmptyMessage(0);
}
}.start();
}
});
// Center the text vertically
button.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
button.setPadding(36, 0, 0, 0);
return button;
}
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
Log.e("getChildView", groupPosition + "===" +groups.size());
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.chilldlayout_data, null);
// parent.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
}
if( groupPosition == groups.size()-1 && isLastChild){
//adding a button.
Button button = (Button)convertView.findViewById(R.id.more_button);
button.setVisibility(View.VISIBLE);
button.setText("More");
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
progressDialog = ProgressDialog.show(context, null, "Please Wait");
new Thread(){
/* (non-Javadoc)
* #see java.lang.Thread#run()
*/
#Override
public void run() {
getMoreData(groupPosition,childPosition);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
actionhandler.sendEmptyMessage(0);
}
}.start();
}
});
// Center the text vertically
button.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
button.setPadding(36, 0, 0, 0);
return convertView;
}else{
Button button = (Button)convertView.findViewById(R.id.more_button);
button.setVisibility(View.GONE);
TextView textView = (TextView)convertView.findViewById(R.id.textView_data);
textView.setText(getChild(groupPosition, childPosition).toString());
return convertView;
}
}
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
public int getGroupCount() {
return groups.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;
}
}
}

Android - cannot refresh ExpendableListView, it freezes

I have an ExpandableListView in which if I add some Groups during onCreate() of the activity, it's fine, but if I try to add Groups later on and then do notifyDataSetChanged() the ExpandableListView just freezes - everything else in the activity works, just the Exp.ListView hangs.
Here as you can see I add two Groups (with children) to the Exp.ListView and they function just fine. If I try to call addTeam() though it freezes/hangs.
package org.mytest;
import java.util.ArrayList;
import eigc.doubango.ScreenTeam.ScreenTeamItemGroup;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ImageView;
import android.widget.TextView;
public class ScreenTeam extends Activity {
private TeamListAdapter mTeamListAdapter;
private ExpandableListView mTeamList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_team);
mTeamListAdapter = new TeamListAdapter(getLayoutInflater());
mTeamList = (ExpandableListView) findViewById(R.id.screen_team_teamslist);
mTeamList.setAdapter(mTeamListAdapter);
mTeamList.setGroupIndicator(null);
/* TEST */
ScreenTeamItemGroup grp1 = new ScreenTeamItemGroup("team1",1);
ScreenTeamItemChild ch1 = new ScreenTeamItemChild("child1");
ScreenTeamItemChild ch2 = new ScreenTeamItemChild("child2");
grp1.addTeamMember(ch1);
grp1.addTeamMember(ch2);
ScreenTeamItemGroup grp2 = new ScreenTeamItemGroup("team2",2);
ScreenTeamItemChild ch3 = new ScreenTeamItemChild("child1");
ScreenTeamItemChild ch4 = new ScreenTeamItemChild("child2");
ScreenTeamItemChild ch5 = new ScreenTeamItemChild("child3");
grp2.addTeamMember(ch3);
grp2.addTeamMember(ch4);
grp2.addTeamMember(ch5);
mTeamListAdapter.addTeam(grp1);
mTeamListAdapter.addTeam(grp2);
}
/*
* Callbacks
*/
/* adds a team */
public void addTeam() {
ScreenTeamItemGroup grp1 = new ScreenTeamItemGroup("team1",1);
ScreenTeamItemChild ch1 = new ScreenTeamItemChild("child1");
ScreenTeamItemChild ch2 = new ScreenTeamItemChild("child2");
grp1.addTeamMember(ch1);
grp1.addTeamMember(ch2);
mTeamListAdapter.addTeam(grp1);
mTeamListAdapter.notifyDataSetChanged();
}
/*
* Aux classes
*/
/* team group item */
static class ScreenTeamItemGroup {
final String mItemText;
final int mIconResId;
final int mTeamID;
public ArrayList<ScreenTeamItemChild> mTeamMembers;
public ScreenTeamItemGroup(String itemText, int id) {
mItemText = itemText;
mTeamID = id;
mIconResId = R.drawable.teams;
mTeamMembers = new ArrayList<ScreenTeamItemChild>();
}
public void addTeamMember(ScreenTeamItemChild member) {
if (member != null)
mTeamMembers.add(member);
}
}
/* team child item */
static class ScreenTeamItemChild {
final int mIconResId;
final String mItemText;
public ScreenTeamItemChild(String itemText) {
mIconResId = R.drawable.p2p;
mItemText = itemText;
}
}
/* handles the list of teams */
static class TeamListAdapter extends BaseExpandableListAdapter {
public ArrayList<ScreenTeamItemGroup> mTeams;
private final LayoutInflater mInflater;
public TeamListAdapter(LayoutInflater inflater) {
mInflater = inflater;
mTeams = new ArrayList<ScreenTeamItemGroup>();
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return mTeams.get(groupPosition).mTeamMembers.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
View view = convertView;
final ScreenTeamItemChild item = (ScreenTeamItemChild)getChild(groupPosition,childPosition);
if(item == null){
return null;
}
if (view == null) {
view = mInflater.inflate(R.layout.screen_team_item, null);
}
((TextView) view.findViewById(R.id.screen_team_item_text)).setText(item.mItemText);
((ImageView) view.findViewById(R.id.screen_team_item_icon)).setImageResource(item.mIconResId);
return view;
}
#Override
public int getChildrenCount(int groupPosition) {
return mTeams.get(groupPosition).mTeamMembers.size();
}
#Override
public Object getGroup(int groupPosition) {
return mTeams.get(groupPosition);
}
#Override
public int getGroupCount() {
return mTeams.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view = convertView;
final ScreenTeamItemGroup item = (ScreenTeamItemGroup)getGroup(groupPosition);
if(item == null){
return null;
}
if (view == null) {
view = mInflater.inflate(R.layout.screen_team_item, null);
}
((TextView) view.findViewById(R.id.screen_team_item_text)).setText(item.mItemText);
((ImageView) view.findViewById(R.id.screen_team_item_icon)).setImageResource(item.mIconResId);
return view;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return false;
}
public void addTeam(ScreenTeamItemGroup grp) {
if (grp != null)
mTeams.add(grp);
}
}
}
A few things:
You don't want to make your TeamListAdapter a static subclass.
Try putting the logic for adding a team into an AsyncTask as this could freeze up the UI thread.
Also, what are your logs saying?
I solved this by using runOnUiThread in my addTeam() instead and it worked flawlessly.

Categories

Resources