I am new in android and badly need to do animation in ExpandableLIstView in onGroupExpand and onGroupCollapse.
Please help me.
Given below is my code -
My MainActivity is
package comsam.myexpandablelistviedjsonapp;
import android.app.ProgressDialog;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.animation.PathInterpolatorCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ExpandListAdapter ExpAdapter;
private ExpandableListView ExpandList;
private Interpolator easeInOutQuart = PathInterpolatorCompat.create(0.77f, 0f, 0.175f, 1f);
private int lastExpandedPosition = -1;
ArrayList<Parent> list = new ArrayList<Parent>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView animatedButton = (ImageView) findViewById(R.id.parent_img);
ExpandList = (ExpandableListView)findViewById(R.id.exp_list);
new JSONAsyncTask().execute("http://local.agdits.com.bd/hrdemo/expandable.php");
ExpAdapter = new ExpandListAdapter(MainActivity.this, list);
ExpandList.setAdapter(ExpAdapter);
//to show which list has been clicked for Expand
ExpandList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(final int groupPosition) {
if (lastExpandedPosition != -1 && groupPosition != lastExpandedPosition) {
ExpandList.collapseGroup(lastExpandedPosition);
// setupLayoutAnimationClose(groupPosition);
// new AnimUtils().collapse(ExpandList);
}
lastExpandedPosition = groupPosition;
}
});
//to show which list has been clicked for Collapse
ExpandList.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int parentPosition) {
Toast.makeText(getBaseContext(), ExpAdapter.getGroupName(parentPosition) + " is collapse ", Toast.LENGTH_LONG).show();
}
});
//to show which Child has been clicked
ExpandList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int parentPosition, int childPosition, long id) {
Toast.makeText(getBaseContext(), ExpAdapter.getChildName(parentPosition, childPosition) + " from category " + ExpAdapter.getGroupName(parentPosition) + " is selected", Toast.LENGTH_LONG).show();
return false;
}
});
}
private void expand1() {
System.out.println("I am here expand");
}
private void collapse() {
System.out.println("I am here collapse");
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
//System.out.println(data);
ArrayList<Child> ch_list;
JSONArray jsonArray1 = new JSONArray(data);
for (int i = 0; i < jsonArray1.length(); i++) {
JSONObject object = jsonArray1.getJSONObject(i);
// System.out.println(object.getString("_id"));
Parent parent = new Parent();
parent.setParentName(object.getString("CategoryName"));
parent.setParentImage(object.getString("CatImage"));
//System.out.println(object.getString("CategoryName"));
//Make Child List Array
ch_list = new ArrayList<Child>();
JSONArray childArray = object.getJSONArray("child");
//System.out.println(childArray.length());
for (int j = 0; j < childArray.length(); j++) {
JSONObject childobject = childArray.getJSONObject(j);
Child child = new Child();
child.setName(childobject.getString("name"));
child.setImage(childobject.getString("image"));
ch_list.add(child);
}
// System.out.println(childArray);
//Child List to Parent Items
parent.setItems(ch_list);
list.add(parent);
}
return true;
}
//------------------>>
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
ExpAdapter.notifyDataSetChanged();
if(result == false) {
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
My ExpandListAdapter class is
package comsam.myexpandablelistviedjsonapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Created by tanvinn on 10/27/2015.
*/
public class ExpandListAdapter extends BaseExpandableListAdapter{
private Context context;
private ArrayList<Parent> parents;
public MainActivity activity;
public ImageLoader imageLoader;
public int lastExpandedGroupPosition=-1;
public ExpandListAdapter(Context context, ArrayList<Parent> parents) {
this.context = context;
this.parents = parents;
// Create ImageLoader object to download and show image in list
// Call ImageLoader constructor to initialize FileCache
imageLoader = new ImageLoader(activity);
}
#Override
public Object getChild(int parentPosition, int childPosition) {
ArrayList<Child> chList = parents.get(parentPosition).getItems();
return chList.get(childPosition);
}
#Override
public long getChildId(int parentPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int parentPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
Child child = (Child) getChild(parentPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_layout, null);
}
TextView tv = (TextView) convertView.findViewById(R.id.child_txt);
ImageView imageView = (ImageView)convertView.findViewById(R.id.child_img);
imageView.setImageResource(R.drawable.geofence1);
tv.setText(child.getName().toString());
//new DownloadImageTask(imageView).execute(child.getImage().toString());
imageLoader.DisplayImage(child.getImage().toString(), imageView);
return convertView;
}
#Override
public int getChildrenCount(int parentPosition) {
ArrayList<Child> chList = parents.get(parentPosition).getItems();
return chList.size();
}
#Override
public Object getGroup(int parentPosition) {
return parents.get(parentPosition);
}
#Override
public int getGroupCount() {
return parents.size();
}
#Override
public long getGroupId(int parentPosition) {
return parentPosition;
}
#Override
public View getGroupView(int parentPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
Parent parent1 = (Parent) getGroup(parentPosition);
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.parent_layout, null);
}
TextView tv = (TextView) convertView.findViewById(R.id.parent_txt);
ImageView imageView = (ImageView)convertView.findViewById(R.id.parent_img);
imageView.setImageResource(R.drawable.geofence1);
tv.setText(parent1.getParentName());
// new DownloadImageTask(imageView).execute(parent1.getParentImage().toString());
imageLoader.DisplayImage(parent1.getParentImage().toString(), imageView);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int parentPosition, int childPosition) {
return true;
}
public Object getGroupName(int parentPosition) {
Parent parent1 = (Parent) getGroup(parentPosition);
String parentName = parent1.getParentName();
return parentName;
}
public Object getChildName(int parentPosition, int childPosition) {
Child child = (Child) getChild(parentPosition, childPosition);
String childName = child.getName();
return childName;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Thanks in advance.
You can try with this AnimatedExpandableListView
listView = (AnimatedExpandableListView) findViewById(R.id.listView);
listView.setAdapter(YOUR_ADAPTER);
// In order to show animations, we need to use a custom click handler
// for our ExpandableListView.
listView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
// We call collapseGroupWithAnimation(int) and
// expandGroupWithAnimation(int) to animate group
// expansion/collapse.
if (listView.isGroupExpanded(groupPosition)) {
listView.collapseGroupWithAnimation(groupPosition);
} else {
listView.expandGroupWithAnimation(groupPosition);
}
return true;
}
});
Android ExpandableListView using animation
Animation for expandableListView
The following in item_animation_fall_down.xml (Place this xml file in res/anim folder)
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"android:duration="500">
<translate android:interpolator="#android:anim/accelerate_decelerate_interpolator"
android:fromYDelta="50%p" android:toYDelta="0" />
<alpha android:fromAlpha="0" android:toAlpha="1"
android:interpolator="#android:anim/accelerate_decelerate_interpolator" />
</set>
The following in getGroupView(....) {} block
convertView.setAnimation(AnimationUtils.loadAnimation(_context,R.anim.item_animation_fall_down));
The following in Activity class
expListView.setAnimation(AnimationUtils.loadAnimation(this,R.anim.item_animation_from_right));
The following in activity_home.xml ( to the root element)
android:fillAfter="true" android:fillEnabled="true"
Related
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;
}
});
I am creating an application in which I am parsing data using Json parsing. I've implemented listview and in my response i have totalpage and current page objects,
A new user will get items from the first page. While the user is scrolling through the listview, the list expands with items from the next page (and the next and the next etc.)
this is my response
http://pastie.org/10259792
The following is code I've tried:
HomeFragment
public class HomeFragment extends Fragment {
// Listview Adapter
ListViewAdapter adapters;
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONparserr jsonParser = new JSONparserr();
ArrayList<HashMap<String, String>> WebsiteList;
// albums JSONArray
JSONArray data = null;
String link_url;
ArrayList<HashMap<String, String>> arrayTemplist;
private AutoCompleteTextView inputSearch;
private ListView lv;
private static final String URL_ALBUMS = "";
private static final String WEBSITE_MENU_ID ="Brand_name";
private static final String TAG_MATCH="data";
//private static final String TAG_NAME="Brand_name";
private static final String TAG_PROFILE="id";
private static final String TAG_CAST="Company";
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
lv = (ListView)rootView.findViewById(R.id.listpehlu);
cd = new ConnectionDetector(getActivity());
WebsiteList = new ArrayList<HashMap<String, String>>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
inputSearch = (AutoCompleteTextView)rootView.findViewById(R.id.autoCompleteTextViewhomefrag);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
arrayTemplist= new ArrayList<HashMap<String,String>>();
String searchString =inputSearch.getText().toString().toLowerCase();
for (int i = 0; i < WebsiteList.size(); i++)
{
String currentString =WebsiteList.get(i).get(HomeFragment.this.WEBSITE_MENU_ID);
if (currentString.toLowerCase().startsWith(searchString ))
{
arrayTemplist.add(WebsiteList.get(i));
}
}
for (int i = 0; i < arrayTemplist.size(); i++)
{
String currentstrin = arrayTemplist.get(i).get(HomeFragment.this.WEBSITE_MENU_ID);
//Toast.makeText(getApplicationContext(), currentstrin, Toast.LENGTH_LONG).show();
}
SimpleAdapter adapters = new SimpleAdapter(getActivity(), arrayTemplist,R.layout.list_item_match, new String[] {WEBSITE_MENU_ID,TAG_CAST
}, new int[] {
R.id.txtbrndnm,R.id.txtbrndcomp});
lv.setAdapter(adapters);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Selected_Product_Listing tf = new Selected_Product_Listing();
Bundle bundle = new Bundle();
bundle.putString("prducts_name", WebsiteList.get(position).get((WEBSITE_MENU_ID)));
// bundle.putString("prducts_name", aList.get(position).get(INTEREST_ACCEPT_NAME));
tf.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
// Toast.makeText(getActivity(),"lets"+ WebsiteList.get(position).get(convertToBase64(convertToBase64(WEBSITE_MENU_ID))), Toast.LENGTH_LONG).show();
}
});
lv.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
{
}
}
});
return rootView;
}
public String convertToBase64(String text) {
byte[] data = null;
try {
data = text.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return Base64.encodeToString(data, Base64.DEFAULT);
}
class LoadAlbums extends AsyncTask<String, String, String> {
private JSONObject jsonObj;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
if (json != null) {
try {
jsonObj = new JSONObject(json);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_MATCH);
String totpage=jsonObj.getString("total_page");
System.out.println("Total Page"+totpage);
String curpage=jsonObj.getString("current_page");
System.out.println("Total Page"+curpage);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(WEBSITE_MENU_ID,c.getString(WEBSITE_MENU_ID));
map.put(TAG_PROFILE, c.getString(TAG_PROFILE));
map.put(TAG_CAST, c.getString(TAG_CAST));
WebsiteList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// updating UI from Background Thread
ListAdapter adapter = new SimpleAdapter(
getActivity(), WebsiteList,
R.layout.list_item_match, new String[] {WEBSITE_MENU_ID,TAG_CAST
}, new int[] {
R.id.txtbrndnm,R.id.txtbrndcomp});
lv.setAdapter(adapter);
}
}
EndlessAdapter
public class EndLessAdapter extends ArrayAdapter<String> {
private Context context;
private List<String> items;
private int layoutId;
public EndLessAdapter(Context context, List<String> items, int LayoutId) {
super(context,LayoutId,items);
this.context = context;
this.items = items;
this.layoutId = LayoutId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(layoutId,parent,false);
TextView tView = (TextView)convertView.findViewById(R.id.txt);
tView.setText(items.get(position));
return convertView;
}
}
EndlessLisView
public class EndlessListView extends ListView implements OnScrollListener {
private Context context;
private View footer;
private boolean isLoading;
private EndLessListener listener;
private BaseAdapter adapter;
public EndlessListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setOnScrollListener(this);
this.context = context;
}
public EndlessListView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnScrollListener(this);
this.context = context;
}
public EndlessListView(Context context) {
super(context);
this.setOnScrollListener(this);
this.context = context;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
// 4
public void addNewData() {
this.removeFooterView(footer);
// adapter.addAll(products);
adapter.notifyDataSetChanged();
isLoading = false;
}
public void setLoading()
{
isLoading = false;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
if(getAdapter() == null)
return;
if(getAdapter().getCount() == 0)
return;
int l = visibleItemCount + firstVisibleItem;
System.out.println("List View Total Item Count = "+totalItemCount+" , l = "+l+", is_loading = "+isLoading);
if(l >= totalItemCount && !isLoading){
// add footer layout
this.addFooterView(footer);
// set progress boolean
isLoading = true;
System.out.println("$$$$$$$$$ call loaddata $$$$$$$$$$$");
// call interface method to load new data
listener.loadData();
}
}
// Calling order from MainActivity
// 1
public void setLoadingView(int resId) {
footer = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(resId, null); // footer = (View)inflater.inflate(resId, null);
this.addFooterView(footer);
System.out.println("addfooter ====######");
}
// 2
public void setListener(EndLessListener listener) {
this.listener = listener;
}
// 3
public void setAdapter(BaseAdapter adapter) {
super.setAdapter(adapter);
this.adapter = adapter;
this.removeFooterView(footer);
}
public void removeFooter(){
this.removeFooterView(footer);
}
}
You can achieve this by using the following library in Github
https://github.com/nicolasjafelle/PagingListView
Simple create your PagingAdapter and add it to com.paging.listview.PagingListView.
You have to implements the new Pagingable interface and its onLoadMoreItems() method. For example:
listView.setHasMoreItems(true);
listView.setPagingableListener(new PagingListView.Pagingable() {
#Override
public void onLoadMoreItems() {
if (pager < 3) {
new CountryAsyncTask(false).execute();
} else {
listView.onFinishLoading(false, null);
}
}
});
Finally you can use the onFinishLoading(boolean hasMoreItems, List newItems) method to update the list.
listView.onFinishLoading(true, newItems);
Also remember to use this package in your layout files:
<com.paging.listview.PagingListView
android:id="#+id/paging_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Hello here you can find the nostra library for lazy loading and then you can
implement the following example for lazzy loading
https://github.com/nostra13/Android-Universal-Image-Loader
you can achieve Lazy loading by using the below
code
Lets start the coding about the lazy loading.
MainActivity.java
package com.sunil.lazyloading;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button btnlist=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnlist= (Button)findViewById(R.id.button_listview);
btnlist.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Intent intent = new Intent(this, ImageListActivity.class);
intent.putExtra("stringarrayimage", Constants.IMAGES);
startActivity(intent);
}
}
CustomAdapter.java
package com.sunil.adapter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sunil.lazyloading.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter{
private String imageurl[]=null;
private Context context=null;
DisplayImageOptions doption=null;
private ImageLoadingListener animateFirstListener =null;
public CustomAdapter(Activity activity, String[] imageurl)
{
this.context=activity;
this.imageurl=imageurl;
doption=new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).showStubImage(R.drawable.ic_stub).cacheInMemory(true).cacheOnDisc(true).displayer(new RoundedBitmapDisplayer(20)).build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public int getCount() {
return imageurl.length;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_list_row, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(imageurl[position], holder.image, doption, animateFirstListener);
return view;
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<string> displayedImages = Collections.synchronizedList(new LinkedList<string>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
private class ViewHolder {
public TextView text;
public ImageView image;
}
}
</string></string>
ImageListActivity.java
package com.sunil.lazyloading;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
MainActivity.java
package com.sunil.lazyloading;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button btnlist=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnlist= (Button)findViewById(R.id.button_listview);
btnlist.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Intent intent = new Intent(this, ImageListActivity.class);
intent.putExtra("stringarrayimage", Constants.IMAGES);
startActivity(intent);
}
}
CustomAdapter.java
package com.sunil.adapter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sunil.lazyloading.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter{
private String imageurl[]=null;
private Context context=null;
DisplayImageOptions doption=null;
private ImageLoadingListener animateFirstListener =null;
public CustomAdapter(Activity activity, String[] imageurl)
{
this.context=activity;
this.imageurl=imageurl;
doption=new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).showStubImage(R.drawable.ic_stub).cacheInMemory(true).cacheOnDisc(true).displayer(new RoundedBitmapDisplayer(20)).build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public int getCount() {
return imageurl.length;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_list_row, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(imageurl[position], holder.image, doption, animateFirstListener);
return view;
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<string> displayedImages = Collections.synchronizedList(new LinkedList<string>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
private class ViewHolder {
public TextView text;
public ImageView image;
}
}
</string></string>
ImageListActivity.java
package com.sunil.lazyloading;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.sunil.adapter.CustomAdapter;
public class ImageListActivity extends Activity implements OnItemClickListener{
private ListView listview=null;
private String[] imageUrls;
protected ImageLoader imageLoader=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagelist);
listview=(ListView)findViewById(R.id.listView_image);
imageLoader = ImageLoader.getInstance();
Bundle bundle = getIntent().getExtras();
imageUrls = bundle.getStringArray("stringarrayimage");
CustomAdapter adapter=new CustomAdapter(ImageListActivity.this, imageUrls);
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView arg0, View arg1, int position, long arg3) {
Intent intent = new Intent(this, ImagePagerActivity.class);
intent.putExtra("imageurlpostion", imageUrls);
intent.putExtra("imagepostion", position);
startActivity(intent);
}
#Override
public void onBackPressed() {
AnimateFirstDisplayListener.displayedImages.clear();
super.onBackPressed();
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<string> displayedImages = Collections.synchronizedList(new LinkedList<string>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_clear_memory_cache:
imageLoader.clearMemoryCache();
return true;
case R.id.item_clear_disc_cache:
imageLoader.clearDiscCache();
return true;
default:
return false;
}
}
}
activity_main.xml
<button android:id="#+id/button_listview" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="ListView ImageLoad">
imagelist.xml
<listview android:id="#+id/listView_image" android:layout_height="match_parent" android:layout_width="match_parent">
</listview>
item_list_row.xml
<imageview android:adjustviewbounds="true" android:contentdescription="#string/descr_image" android:id="#+id/image" android:layout_height="72dip" android:layout_margin="3dip" android:layout_width="72dip" android:scaletype="centerCrop">
<textview android:id="#+id/text" android:layout_gravity="left|center_vertical" android:layout_height="wrap_content" android:layout_marginleft="20dip" android:layout_width="fill_parent" android:textsize="22sp">
For the Example above you need to download the library universal image loader you can download the library ... happy coding :)
you didn't use EndlessListView in your Fragment. As I looked your response, it includes pagination. So, you need to request with page number to use endless scroll.
This is just flow for Endless Listview. If your code still doesn't work, I hope you can learn sample projects after read this messages. I added only parts you need. Thanks
Endless scroll only shows limited data on listview. When user scroll down to bottom, it will get next limited data from server. So you need to add current_page paramater in your request. I don't know exactly your api.
First, you need variable for current_page which initialize with 0
You have to know when to stop. You response has total_page field for that. Save and add validation
Then you need to know when to request next page. For that,you already have codes in onScroll within EndlessListView. That code calculate and tell when user scroll down to bottom and it called
listener.loadData();
to request new data. But you still need to add listener for that. You already have
public void setListener(EndLessListener listener) {
this.listener = listener;
}
You need to create Interface with the name EndlessListener and implements in your fragment. EndlessListener Interface will include loadData() function that request to server. After that you need to add listener for the listview.
endlessListView.setListener(this);
Try Loading data when listview reaches it's end. Implement OnScrollListener in your fragment. Refer this link Android - ListView to load more items when reached end
You MUST use Paging 3 library to resolve all problems in simplest way.
ListView 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" >
<ListView
android:id="#+id/orderlistview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
/>
</LinearLayout>
OrderList class
public class OrderList {
int _orderId;
int _orderincrement_id;
String _orderstatus;
String _orderdate;
String _ordership_to;
String _ordertotal;
String _ordercurrency_symbol;
// Empty constructor
public OrderList() {
}
// constructor
public OrderList(int _orderId, int _orderincrement_id, String _orderstatus,
String _orderdate, String _ordership_to, String _ordertotal,
String _ordercurrency_symbol) {
this._orderId = _orderId;
this._orderincrement_id = _orderincrement_id;
this._orderstatus = _orderstatus;
this._orderdate = _orderdate;
this._ordership_to = _ordership_to;
this._ordertotal = _ordertotal;
this._ordercurrency_symbol = _ordercurrency_symbol;
}
public int get_orderId() {
return _orderId;
}
public void set_orderId(int _orderId) {
this._orderId = _orderId;
}
public int get_orderincrement_id() {
return _orderincrement_id;
}
public void set_orderincrement_id(int _orderincrement_id) {
this._orderincrement_id = _orderincrement_id;
}
public String get_orderstatus() {
return _orderstatus;
}
public void set_orderstatus(String _orderstatus) {
this._orderstatus = _orderstatus;
}
public String get_orderdate() {
return _orderdate;
}
public void set_orderdate(String _orderdate) {
this._orderdate = _orderdate;
}
public String get_ordership_to() {
return _ordership_to;
}
public void set_ordership_to(String _ordership_to) {
this._ordership_to = _ordership_to;
}
public String get_ordertotal() {
return _ordertotal;
}
public void set_ordertotal(String _ordertotal) {
this._ordertotal = _ordertotal;
}
public String get_ordercurrency_symbol() {
return _ordercurrency_symbol;
}
public void set_ordercurrency_symbol(String _ordercurrency_symbol) {
this._ordercurrency_symbol = _ordercurrency_symbol;
}
}
Activity
public class OrderListFragment extends Fragment {
View rootView;
ListView lv;
List<OrderList> list ;
MyListAdapter adt;
DatabaseHandler db ;
ProgressDialog progress;
SharedPreferences pref;
public OrderListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragmentorderlist, container,
false);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
lv = (ListView) rootView.findViewById(R.id.orderlistview);
db = new DatabaseHandler(getActivity());
list = db.getAllOrderList();
if(list.size() == 0){
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Data.....");
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.show();
pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
String customer_id = pref.getString("customer_id", null);
Log.v("log_tag", "customer_id"+customer_id);
if(customer_id != null){
Log.v("log_tag", "customer_id 2332 ::: "+customer_id);
new FetchOrderListData().execute(customer_id);
}
}
adt = new MyListAdapter(getActivity());
lv.setAdapter(adt);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Bundle bundle = new Bundle();
bundle.putString("orderlist_increment_id", list.get(position).get_orderincrement_id()+"");
Fragment fragment = new OrderdetailFragment();
fragment.setArguments(bundle);
FragmentManager fragmentManager = OrderListFragment.this
.getActivity().getSupportFragmentManager();
FragmentTransaction mFragmentTransaction = fragmentManager
.beginTransaction();
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.replace(R.id.Frame_Layout, fragment)
.commit();
}
});
return rootView;
}
public class MyListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MyListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
convertView = mInflater.inflate(R.layout.custom_orderlistdata,
null);
TextView ordernumbertxt = (TextView) convertView
.findViewById(R.id.ordernumberTxt);
TextView orderdate = (TextView) convertView
.findViewById(R.id.orderdateTxt);
TextView orderamount = (TextView) convertView
.findViewById(R.id.orderAmountTxt);
TextView orderSatusTxt = (TextView) convertView
.findViewById(R.id.orderSatusTxt);
ordernumbertxt.setText(Html.fromHtml("<b>Order Number : </b>"+list.get(position).get_orderincrement_id()+""));
orderdate.setText(list.get(position).get_orderdate());
orderSatusTxt.setText(list.get(position).get_orderstatus());
String parts = list.get(position).get_ordertotal();
double d = Double.parseDouble(parts);
double dval = roundTwoDecimals(d);
orderamount.setText(Html.fromHtml("<b>Total : </b>"+list.get(position).get_ordercurrency_symbol()+" "+dval));
return convertView;
}
public double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
}
private class FetchOrderListData extends AsyncTask<String, Void, JSONObject> {
#Override
protected void onPreExecute() {
}
#Override
protected JSONObject doInBackground(String... args) {
JSONObject listSize = null;
Integer cust_id = Integer.parseInt(args[0]);
try {
listSize = DBAda.getAllOrderListData(cust_id);
////*** call your HTTP Service over here ***////
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listSize;
}
protected void onPostExecute(JSONObject jsonObj) {
db = new DatabaseHandler(getActivity());
if (progress != null) {
progress.hide();
}
if (jsonObj == null) {
return;
}
JSONArray json;
try {
json = jsonObj.getJSONArray("records");
for (int i = 0; i < json.length(); i++) {
JSONObject jobj;
try {
jobj = json.getJSONObject(i);
int order_id = Integer.parseInt(jobj.getString("order_id").toString());
int order_IncrementId = Integer.parseInt(jobj.getString("increment_id").toString());
String orderStatus = jobj.getString("status");
String orderdate = jobj.getString("date");
String ordershipto = jobj.getString("ship_to");
String ordertotal = jobj.getString("order_total");
String ordersymbol = jobj.getString("currency_symbol");
//db.addWishlistItem(new WishList(entity_id,quentity,comment,name,short_description,thumbnails,itemId));
db.addOrderListItem(new OrderList(order_id, order_IncrementId, orderStatus, orderdate, ordershipto, ordertotal, ordersymbol));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
lv = (ListView) rootView.findViewById(R.id.orderlistview);
db = new DatabaseHandler(getActivity());
list = db.getAllOrderList();
adt = new MyListAdapter(getActivity());
lv.setAdapter(adt);
}
}
}
iam currently doing a project in which i populate a Listview from JSON.
The JSON iam passing works perfectly and my listview shows all list values properly But problem occurs when i click on any list after 10/12th list the values which i get is repeated from the first.
The respective values are not retrieved.
I also refereed other post regarding this issue but now solved my problem.
Below is my code. I hope someone will find the solution for it.
package com.desitv.geojoy;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.SearchView;
import com.desitv.geojoy.R;
import com.desitv.geojoy.adapter.LatestGridAdapter;
import com.desitv.geojoy.item.ItemLatest;
import com.desitv.geojoy.util.AlertDialogManager;
import com.desitv.geojoy.util.Constant;
import com.desitv.geojoy.util.JsonUtils;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class LatestFragment extends SherlockFragment {
ListView lsv_latest;
List<ItemLatest> arrayOfLatestMusic;
LatestGridAdapter objAdapter;
AlertDialogManager alert = new AlertDialogManager();
ArrayList<String> allListImageUrl,allListChannelCatName;
ArrayList<String> allListChannelId,allListChannelCatId,allListChannelUrl,allListChannelName,allListChannelDesc;
String[] allArrayImage,allArrayChannelCatName;
String[] allArrayChannelId,allArrayChannelCatId,allArrayChannelurl,allArrayChannelName,allArrayChannelDesc;
private ItemLatest objAllBean;
private int columnWidth;
JsonUtils util;
int textlength = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.fragment_latest, container, false);
setHasOptionsMenu(true);
lsv_latest=(ListView)rootView.findViewById(R.id.lsv_latest);
arrayOfLatestMusic=new ArrayList<ItemLatest>();
allListImageUrl=new ArrayList<String>();
allListChannelCatName=new ArrayList<String>();
allListChannelCatId=new ArrayList<String>();
allListChannelId=new ArrayList<String>();
allListChannelName=new ArrayList<String>();
allListChannelUrl=new ArrayList<String>();
allListChannelDesc=new ArrayList<String>();
allArrayImage=new String[allListImageUrl.size()];
allArrayChannelCatName=new String[allListChannelCatName.size()];
allArrayChannelId=new String[allListChannelId.size()];
allArrayChannelCatId=new String[allListChannelCatId.size()];
allArrayChannelurl=new String[allListChannelUrl.size()];
allArrayChannelName=new String[allListChannelName.size()];
allArrayChannelDesc=new String[allListChannelDesc.size()];
util=new JsonUtils(getActivity());
if (JsonUtils.isNetworkAvailable(getActivity())) {
new MyTask().execute(Constant.LATEST_URL);
} else {
showToast("No Network Connection!!!");
alert.showAlertDialog(getActivity(), "Internet Connection Error",
"Please connect to working Internet connection", false);
}
lsv_latest.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
objAllBean=arrayOfLatestMusic.get(position);
int pos=objAllBean.getId();
Intent intplay=new Intent(getActivity(),TvDetails.class);
intplay.putExtra("POSITION", pos);
intplay.putExtra("CHANNEL_IMAGE", allArrayImage);
intplay.putExtra("CHANNEL_CATNAME", allArrayChannelCatName);
intplay.putExtra("CHANNEL_CATID", allArrayChannelCatId);
intplay.putExtra("CHANNEL_URL", allArrayChannelurl);
intplay.putExtra("CHANNEL_NAME", allArrayChannelName);
intplay.putExtra("CHANNEL_CID", allArrayChannelId);
intplay.putExtra("CHANNEL_DISCRIPTION", allArrayChannelDesc);
startActivity(intplay);
}
});
return rootView;
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
showToast("Server Connection Error");
alert.showAlertDialog(getActivity(), "Server Connection Error",
"May Server Under Maintaines Or Low Network", false);
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.LATEST_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemLatest objItem = new ItemLatest();
objItem.setId(objJson.getInt(Constant.CHANNEL_ID));
objItem.setCategoryId(objJson.getInt(Constant.CHANNEL_CATID));
objItem.setCategoryName(objJson.getString(Constant.CHANNEL_CAT_NAME));
objItem.setChannelName(objJson.getString(Constant.LATEST_CHANNEL_NAME));
objItem.setChannelUrl(objJson.getString(Constant.lATETST_CHANNEL_URL));
objItem.setDescription(objJson.getString(Constant.LATEST_CHANNEL_DESCRIPTION));
objItem.setImage(objJson.getString(Constant.LATEST_CHANNEL_IMAGE));
arrayOfLatestMusic.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
for(int j=0;j<arrayOfLatestMusic.size();j++)
{
objAllBean=arrayOfLatestMusic.get(j);
allListImageUrl.add(objAllBean.getImage());
allArrayImage=allListImageUrl.toArray(allArrayImage);
allListChannelCatName.add(objAllBean.getCategoryName());
allArrayChannelCatName=allListChannelCatName.toArray(allArrayChannelCatName);
allListChannelId.add(String.valueOf(objAllBean.getId()));
allArrayChannelId=allListChannelId.toArray(allArrayChannelId);
allListChannelCatId.add(String.valueOf(objAllBean.getCategoryId()));
allArrayChannelCatId=allListChannelCatId.toArray(allArrayChannelCatId);
allListChannelUrl.add(String.valueOf(objAllBean.getChannelUrl()));
allArrayChannelurl=allListChannelUrl.toArray(allArrayChannelurl);
allListChannelName.add(String.valueOf(objAllBean.getChannelName()));
allArrayChannelName=allListChannelName.toArray(allArrayChannelName);
allListChannelDesc.add(objAllBean.getDescription());
allArrayChannelDesc=allListChannelDesc.toArray(allArrayChannelDesc);
}
setAdapterToListview();
}
}
}
public void setAdapterToListview() {
objAdapter = new LatestGridAdapter(getActivity(), R.layout.latest_lsv_item,
arrayOfLatestMusic,columnWidth);
lsv_latest.setAdapter(objAdapter);
}
public void showToast(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_search, menu);
final SearchView searchView = (SearchView) menu.findItem(R.id.search)
.getActionView();
final MenuItem searchMenuItem = menu.findItem(R.id.search);
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus) {
searchMenuItem.collapseActionView();
searchView.setQuery("", false);
}
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
textlength=newText.length();
arrayOfLatestMusic.clear();
for(int i=0;i< allArrayChannelName.length;i++)
{
if(textlength <= allArrayChannelName[i].length())
{
if(newText.toString().equalsIgnoreCase((String) allArrayChannelName[i].subSequence(0, textlength)))
{
ItemLatest objItem = new ItemLatest();
objItem.setId(Integer.parseInt(allArrayChannelId[i]));
objItem.setCategoryId(Integer.parseInt(allArrayChannelCatId[i]));
objItem.setCategoryName(allArrayChannelCatName[i]);
objItem.setDescription(allArrayChannelDesc[i]);
objItem.setImage(allArrayImage[i]);
objItem.setChannelName(allArrayChannelName[i]);
objItem.setChannelUrl(allArrayChannelurl[i]);
arrayOfLatestMusic.add(objItem);
}
}
}
setAdapterToListview();
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
// Do something
return true;
}
});
}
}
LatestGridAdapter code
package com.desitv.geojoy.adapter;
import java.util.List;
import com.desitv.geojoy.R;
import com.desitv.geojoy.imageloader.ImageLoader;
import com.desitv.geojoy.item.ItemLatest;
import com.desitv.geojoy.util.Constant;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class LatestGridAdapter extends ArrayAdapter<ItemLatest>{
private Activity activity;
private List<ItemLatest> itemsLatest;
private ItemLatest objLatestBean;
private int row;
public ImageLoader imageLoader;
public LatestGridAdapter(Activity act, int resource, List<ItemLatest> arrayList, int columnWidth) {
super(act, resource, arrayList);
this.activity = act;
this.row = resource;
this.itemsLatest = arrayList;
imageLoader=new ImageLoader(activity);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(row, null);
holder = new ViewHolder();
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
if ((itemsLatest == null) || ((position + 1) > itemsLatest.size()))
return view;
objLatestBean = itemsLatest.get(position);
holder.imgv_latetst=(ImageView)view.findViewById(R.id.picture);
holder.name=(TextView)view.findViewById(R.id.text);
holder.txt_category=(TextView)view.findViewById(R.id.text_category);
imageLoader.DisplayImage(Constant.SERVER_IMAGE_UPFOLDER_THUMB+objLatestBean.getImage().toString(), holder.imgv_latetst);
holder.name.setText(objLatestBean.getChannelName().toString());
holder.txt_category.setText(objLatestBean.getCategoryName().toString());
return view;
}
public class ViewHolder {
public ImageView imgv_latetst;
public TextView name,txt_category;
}
}
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;
}
}
}
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.