I want to implement this type of list-view. Problem is when i scroll the list, view got refreshed. The task is to show groups expanded up to 3 child's by default and when click on '+'(plus) button, child-items of that group will be expanded and new button will be shown below that group for collapsing that group to default layout means 3 child-items to show with plus('+') button. Plus button is shown when any group have child-items more than 3, if child-items are less than 3 or equal to 3 then all child-items will be shown with no plus button, but if child-items are more than 3 then plus button will be shown. Here 'DIAPERS' and 'LAUNDRY DETERGENT' are the group names.
Present scenario:- If child-position > 3, then set text-view visibility to 'GONE' and button visibility to 'VISIBLE'. But problem is that if childitems are more than 4 and i click to plus button to expand group , then only 4 child-items are shown 5 or next childitems are not shown.
If you want the code of this, please ask in the comments, I will provide you the code.
First of all you have need to set a minimum limit to the child view of expandable list view. Like 2 or 3 child for the very first time will get downloaded or fetched from your database or webservices.
Then on that limit variable you can restrict expandable list view to display only first 2 and 3 child item.
Then with the child limit variable you have also needed a flag variable which contain information like "value 1 if list have more than 3 child's and 0 if list have 3 or less than three child's."
On the value of flag variable you can set plus button hidden and visible value in android.
For plus button click i think the below given code will help. on click just make a another call to the database and fetch all the child items and display them and refresh the expandable list view.
public class ProductListingExpandableAdapter extends BaseExpandableListAdapter {
public String TAG = ProductListingExpandableAdapter.class.getSimpleName();
private Context _context;int clickedPosition;
private List<String> _listDataHeader; // header titles child data in format of header title, child title
private HashMap<String, ArrayList<String>> _listDataChild;
ArrayList<String> CategoryId;
String stateId,countryID;
ArrayList<ProductDataBean> ProductList; ArrayList<ProductListingDisplayCheck> checkArrayList;
int _ListSize;String user_id;
ProductDataBean bean;
/* Variable to do lazy loading of images */
Handler handler;
Runnable runnable;
/* array list to hold data */
ArrayList<String> BrandList;
ImageLoader imageLoader;
private DisplayImageOptions options;
Activity a; String RetailerImageUrl,BrandImageUrl;
public ProductListingExpandableAdapter(Context context, List<String> listDataHeader, HashMap<String, ArrayList<String>> listChildData,
int size,ArrayList<ProductDataBean> ProductList,ArrayList<ProductListingDisplayCheck> checkArrayList,ArrayList<String> CategoryId, String user_id,String stateId,String countryID)
{
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
this.CategoryId = CategoryId;
this.checkArrayList = checkArrayList;
this._ListSize = size;
this.ProductList = ProductList;
this.checkArrayList = checkArrayList;
this.user_id = user_id;
this.countryID = countryID;
this.stateId = stateId;
options = new DisplayImageOptions.Builder()
.showImageForEmptyUrl(R.drawable.thumb_demo).cacheInMemory()
.cacheOnDisc().build();
imageLoader = ImageLoader.getInstance();
Log.d("....return the the event image loader class...==", ""+imageLoader.getClass());
}
#Override
public Object getChild(int groupPosition, int childPosititon)
{
//Log.i("Object getChild",String.valueOf(this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon)));
return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public View getChildView(final int groupPosition, final int childPosition,boolean isLastChild, View convertView, ViewGroup parent)
{
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null)
{
LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.custom_brand_retailer_layout_new, null);
}
RelativeLayout ParentLayout= (RelativeLayout) convertView.findViewById(R.id.parentLayout);
/* Retailer Image*/
ImageView retailerImage = (ImageView) convertView.findViewById(R.id.retailerImage);
/* Brand Image */
ImageView brandImage = (ImageView) convertView.findViewById(R.id.brandImage);
/* Product PricePerUnit */
TextView pricePerUnit = (TextView) convertView.findViewById(R.id.pricePerItem);
/* Product PricePerUnit */
TextView packetPrice = (TextView) convertView.findViewById(R.id.pricePerPacket);
/* Product Name */
TextView productName = (TextView) convertView.findViewById(R.id.ProductName);
/* Group close Images */
RelativeLayout addMore = (RelativeLayout) convertView.findViewById(R.id.addMore);
/* Minus Button Image */
ImageView minusItems = (ImageView) convertView.findViewById(R.id.minusItems);
/* Minus Button Image */
ImageView plusItems = (ImageView) convertView.findViewById(R.id.plusItems);
try {
JSONObject jObject = new JSONObject(childText); // Log.i("jObject",String.valueOf(jObject));
pricePerUnit.setText ("$"+jObject.getString("pricePerItem"));
packetPrice .setText ("$"+jObject.getString("product_price"));
String itemNameString = "";
String title = jObject.getString("product_name");
if (title.length() > 44)
{
itemNameString = title.substring(0, 45)+"...";
}
else
{ itemNameString = title;
}
productName.setText(itemNameString);
RetailerImageUrl = jObject.getString("retailer_image_url_small");
BrandImageUrl = jObject.getString("brand_image_url");
// String RetailerImageUrl = jObject.getString("pricePerItem");
} catch (JSONException e)
{
e.printStackTrace();
}
//=========================================================================================
// Log.e("Pagination ArrayList size", String.valueOf(Constants.PaginationPosition.size()));
String PaginationPos = Constants.PaginationPosition.get(groupPosition);
Log.e ("PaginationPos", String.valueOf(PaginationPos));
// Log.e("is last child", String.valueOf(isLastChild));
/* Hide or Show Group Close option */
Log.e("Pagination ArrayList size", String.valueOf(Constants.PaginationPosition.size()));
if(PaginationPos.equals("1") && childPosition == 2 && isLastChild == true )
{
addMore.setVisibility(View.VISIBLE); minusItems.setVisibility(View.GONE ); plusItems.setVisibility(View.VISIBLE);
}
else if(PaginationPos.equals("0") && childPosition > 2 && isLastChild == true )
{
addMore.setVisibility(View.GONE);
}
else if(PaginationPos.equals("2") && childPosition > 2 && isLastChild == true )
{
plusItems.setVisibility(View.GONE);
addMore.setVisibility (View.VISIBLE);
minusItems.setVisibility(View.VISIBLE);
minusItems.setVisibility(View.VISIBLE);
minusItems.setImageResource(R.drawable.minus);
}
else
{
addMore.setVisibility(View.GONE);
}
//==================================================================================
minusItems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Constants.listDataHeader.get(groupPosition)", Constants.listDataHeader.get(groupPosition));
String keyword = Constants.listDataHeader.get(groupPosition);
String alternate = ProductListingExpandableListViewActivity.demoJsonObjectTesting;
// check whether the list for keyword is present
ArrayList<String> alternateList = _listDataChild.get(keyword);
if(alternateList == null)
{
Log.i(TAG, "list is null");
/* alternateList = new ArrayList<String>();
_listDataChild.put(keyword, alternateList); */
}
else
{
Constants.PaginationPosition.set(groupPosition, "1");
ArrayList<String> newList = new ArrayList<String>();
int size = alternateList.size();
Log.e("alternateList size", String.valueOf( alternateList.size()));
for(int i=0;i<3;i++)
{
newList.add(alternateList.get(i));
}
alternateList.clear();
for(int i=0;i<3;i++)
{
alternateList.add(newList.get(i));
}
Log.i("alternate list size",String.valueOf( alternateList.size()));
ProductListingExpandableAdapter.this.notifyDataSetChanged();
//ProductListingExpandableAdapter.this.notifyDataSetInvalidated();
/*Intent showSearchResult = new Intent(_context,ProductListingExpandableListViewActivity.class);
showSearchResult.putExtra("ShowSeachResult", "2");
_context.startActivity(showSearchResult);
((Activity)_context).finish();
Apply our splash exit (fade out) and main entry (fade in) animation transitions.
((Activity)_context). overridePendingTransition(R.anim.mainfadein, R.anim.splashfadeout);*/
}
}
});
addMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("addMore images list clicked", "addMore image clicked");
//Clicked postion of group
clickedPosition = groupPosition;
String keyword = Constants.listDataHeader.get(groupPosition);
Log.i("keyword", keyword);
for( int ii = 0;ii<Constants.listDataHeader.size();ii ++)
{
String currentKeyword = Constants.listDataHeader.get(ii);
if(currentKeyword.equals(keyword)==false)
{
// check whether the list for keyword is present
ArrayList<String> alternateList = _listDataChild.get(currentKeyword);
if(alternateList == null)
{
Log.i(TAG,Constants.listDataHeader.get(groupPosition)+ " List is null");
/*alternateList = new ArrayList<String>();
_listDataChild.put(keyword, alternateList); */
}
else
{
if(alternateList.size()>2)
{
Constants.PaginationPosition.set(ii, "1");
Log.i(TAG,Constants.listDataHeader.get(groupPosition)+ "inside else");
ArrayList<String> newList = new ArrayList<String>();
int size = alternateList.size();
Log.e("alternateList size", String.valueOf( alternateList.size()));
for (int i=0; i<3;i++)
{
newList.add(alternateList.get(i));
}
alternateList.clear();
for (int j=0; j<3; j++)
{
alternateList.add(newList.get(j));
}
Log.i("alternate list size",String.valueOf( alternateList.size()));
}}
}
}
/* Calling json webservices */
new LoadProductData(_context,groupPosition).execute();
}
});
/* Lazy loading class method for loading Retailer images */
imageLoader.init(ImageLoaderConfiguration.createDefault(_context));
if(RetailerImageUrl.equals("no image"))
{
retailerImage.setBackgroundResource(R.drawable.no_img);
}
else
{
imageLoader.displayImage(RetailerImageUrl,retailerImage,
options, new ImageLoadingListener() {
#Override
public void onLoadingComplete() {}
#Override
public void onLoadingFailed() {}
#Override
public void onLoadingStarted() {}
});
}
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT>=16)
{
if(BrandImageUrl.equals("no image")==false)
{
Drawable Branddrawable= Loadimage(BrandImageUrl);
brandImage.setBackground(Branddrawable);
}
}
else
{
if(BrandImageUrl.equals("no image")==false)
{
Drawable Branddrawable= Loadimage(BrandImageUrl);
brandImage.setBackgroundDrawable(Branddrawable);
}
}
return convertView;
}
#Override
public int getChildrenCount(int groupPosition)
{
return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition)
{
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount()
{
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent)
{
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate (R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface (null, Typeface.BOLD);
lblListHeader.setText (headerTitle);
ExpandableListView mExpandableListView = (ExpandableListView) parent;
mExpandableListView.expandGroup(groupPosition);
return convertView;
}
#Override
public boolean hasStableIds()
{
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
// Background async task
/* State/Province list background thread */
class LoadProductData extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;String response;
Context context;int GroupPos;
private JSONArray jsonarray, stateJsonArray;
public LoadProductData(Context context,int GroupPos) {
super();
this.GroupPos = GroupPos;
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(context, "","Please wait...", true, true);dialog.show();
Log.e("Adapter pre execute ", "in the pre-execute loop");
}
#Override
protected Void doInBackground(Void... params) {
try {
//Constants.listDataChild.clear();Constants.listDataHeader.clear();Constants.productListing.clear();
Log.e(TAG , "in the background-execute loop");
UserFunctions userFunctions = new UserFunctions();
String CategoryID = String.valueOf(Constants.CategoryId.get(GroupPos)); Log.e("CategoryId" , Constants.CategoryId.get(GroupPos));
JSONObject CategoryJson = userFunctions.SingleCategoryListRequest(CategoryID,user_id,stateId,countryID); // Log.i("Product Lisiting Json Array",String.valueOf(CategoryJson));
String result = CategoryJson.getString("result");
Log.i("result",result);
if(result.equals("no records found"))
{
response = "no records found";
}
else
{
response = "record found";
// SearchResult refers to the current element in the array
// "search_result"
JSONObject questionMark = CategoryJson.getJSONObject("result");
Iterator keys = questionMark.keys();
ProductListingDisplayCheck addCheck;
int i = 0;
while (keys.hasNext()) {
// Loop to get the dynamic key
String currentDynamicKey = (String) keys.next(); // Log.i("current Dynamic key",
// String.valueOf(currentDynamicKey));
ArrayList<String> BrandList = new ArrayList<String>();
// Get the value of the dynamic key
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey); // Log.i("current Dynamic Value"+String.valueOf(i),
String product_list = currentDynamicValue.getString("product_listing"); // Log.i("product_listing",String.valueOf(product_list));
addCheck = new ProductListingDisplayCheck();
addCheck.setCheckStatus(0);
checkArrayList . add(addCheck);
Log.i("checkArrayList size",String.valueOf(checkArrayList.size()));
JSONArray product_listing = currentDynamicValue.getJSONArray ("product_listing");
BrandList = Constants.listDataChild.get(currentDynamicKey); Log.i("BrandList size", String.valueOf(BrandList.size()));
BrandList.clear();
for (int ii = 0; ii < product_listing.length(); ii++)
{
JSONObject jsonobject = product_listing.getJSONObject(ii);
String JsonObjectString = String.valueOf(jsonobject);
if ( BrandList == null )
{
BrandList = new ArrayList<String>();
Constants.listDataChild.put(currentDynamicKey, BrandList);
}
BrandList.add(JsonObjectString);
}
//HashMap<String, ArrayList<String>> _listDataChild = null;
/* String keyword = "Wipes";
String alternate = ProductListingExpandableListViewActivity.demoJsonObjectTesting;
// check whether the list for keyword is present
ArrayList<String> alternateList = _listDataChild.get(keyword);
if(alternateList == null) {
alternateList = new ArrayList<String>();
_listDataChild.put(keyword, alternateList);
}
alternateList.add(ProductListingExpandableListViewActivity.demoJsonObjectTesting);
*/
Constants.PaginationPosition.set(GroupPos, "2");
Constants.listDataChild.put(Constants.listDataHeader.get(clickedPosition), BrandList);
Log.i("hash map size", String.valueOf(Constants.listDataChild.size()));
/* Update the value of position */
i++;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialog.dismiss();
if(response.equals("no records found"))
{
Toast.makeText(_context, "No Record Found.", 500).show();
}
else
{
ProductListingExpandableAdapter.this.notifyDataSetChanged();
/*Intent showSearchResult = new Intent(_context,ProductListingExpandableListViewActivity.class);
showSearchResult.putExtra("ShowSeachResult", "2");
_context.startActivity(showSearchResult);
((Activity)context).finish();
Apply our splash exit (fade out) and main entry (fade in) animation transitions.
((Activity)context). overridePendingTransition(R.anim.mainfadein, R.anim.splashfadeout);*/
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
private Drawable Loadimage(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}
catch (Exception e) {
// tv.setText("Exc="+e);
return null;
}
}
}
You can use the Expand List custom Class, the following might be helpful:
public void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
if (listItem instanceof ViewGroup)
listItem.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
try this out.it worked for me.
i solved this problem by using this link https://github.com/PaoloRotolo/ExpandableHeightListView .
package com.rtt.reeferwatch.utilities;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
public class ExpandableHeightListView extends ExpandableListView {
boolean expanded = false;
public ExpandableHeightListView(Context context) {
super(context);
}
public ExpandableHeightListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ExpandableHeightListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public boolean isExpanded() {
return expanded;
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (isExpanded()) {
int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
}
Related
Hope you can help.
I need to add a variable to a button which I make visible depending on a value which may or may not be present in the database. This is working fine.
But I now need to add the id to this button.
Please see below.
ExpandableListView.java
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
final TextView txtListChild = (TextView) convertView.findViewById(R.id.lblListItem);
//listDataChild
final Button markAsBoughtButton = convertView.findViewById(R.id.BtnToClick);
// set 'Mark as bought' button to visible
if(childText.contains("bought by")){
markAsBoughtButton.setVisibility(View.GONE);
}else{
markAsBoughtButton.setVisibility(View.VISIBLE);
}
markAsBoughtButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
View parentRow = (View) view.getParent();
ListView listView = (ListView) parentRow.getParent();
final int pos = listView.getPositionForView(parentRow);
Toast.makeText(_context, "Bought! " + " Position " + pos, Toast.LENGTH_LONG).show();
}
});
txtListChild.setText(childText);
return convertView;
}
etc.
MainActivity.java
public class MainActivity extends ProfileActivity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private ProgressDialog mprocessingdialog;
private static String url = "http://www.xxx/xxxx/xxxx/xxxx.php";
public static String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// added to include custom icon
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(ic_launcher);
mprocessingdialog = new ProgressDialog(this);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
new DownloadJason().execute();
}
/*
* Preparing the list data
*/
private class DownloadJason extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Showing Progress dialog
mprocessingdialog.setTitle("Please Wait..");
mprocessingdialog.setMessage("Loading");
mprocessingdialog.setCancelable(false);
mprocessingdialog.setIndeterminate(false);
mprocessingdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
JSONParser jp = new JSONParser();
String jsonstr = jp.makeServiceCall(url);
Log.d("Response = ", jsonstr);
if (jsonstr != null) {
// For Header title Arraylist
listDataHeader = new ArrayList<String>();
// Hashmap for child data key = header title and value = Arraylist (child data)
listDataChild = new HashMap<String, List<String>>();
try {
JSONObject jobj = new JSONObject(jsonstr);
JSONArray jarray = jobj.getJSONArray("presents_db");
for (int hk = 0; hk < jarray.length(); hk++) {
JSONObject d = jarray.getJSONObject(hk);
// Adding Header data
listDataHeader.add(d.getString("name") + "'s presents are: ");
// Adding child data for members
List<String> members = new ArrayList<String>();
JSONArray xarray = d.getJSONArray("presents_list");
for (int i = 0; i < xarray.length(); i++) {
JSONObject a = xarray.getJSONObject(i);
String id = a.getString("id");
String present = a.getString("present");
if("".equals(a.getString("bought_by"))) {
members.add(id + " " + present);
}else{
members.add(id + " " + present + "\r\n bought by: " + a.getString("bought_by"));
}
}
// Header into Child data
listDataChild.put(listDataHeader.get(hk), members);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),"Please Check internet Connection", Toast.LENGTH_SHORT).show();
}
return null;
}
Apologies for the bad coding but I am new to java and it's a steep learing curve.
Thanks for your help!
You can use setTag() and getTag()
//Set tag
button.setTag(position);
//Get Tag
new OnClickListener() {
#Override
public void onClick(View v) {
int pos = v.getTag();
//Get Tag work on view like button
}
What is the main purpose of setTag() getTag() methods of View?
I'm newbie Android Programming. I have Fragment which shows on Listview and now, i want Listview load more item when list ends. But data is not appending. I need help !
My code :
public class InfoTeacherFragment extends Fragment {
private String URL = "http://scv.udn.vn/dhdn/trdhsp/page/";
ProgressDialog pDialog;
Context mContext;
Vector<ArrayList<String>> data;
ArrayList<String> Name;
ArrayList<String> School;
ArrayList<String> Link;
ArrayList<String> Icon;
ListView lvItem;
DisplayImageOptions options;
ImageLoader imageloader;
View mFooterView;
InfoTeacher adapter;
ProgressBar loading;
int CurrentPage = 1;
int visibleThreshold = 3;
int startPage = 1;
boolean loadingMore = false;
public InfoTeacherFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_mission)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisk(true).considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565).build();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.teacherinfo_layout,
container, false);
mContext = container.getContext();
lvItem = (ListView) rootView.findViewById(R.id.lvTeacher);
lvItem.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
CurrentPage++;
customLoadMoreDataFromApi(CurrentPage);
Toast.makeText(mContext, "EndlessScrollListener",
Toast.LENGTH_SHORT).show();
}
});
imageloader = ImageLoader.getInstance();
imageloader.init(ImageLoaderConfiguration.createDefault(mContext));
if (Utils.isOnline(mContext) == true
&& Utils.KEY_CHECK_SUCCESS.equals("SUCCESS")) {
new LoadData().execute(URL + startPage);
lvItem.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
Intent intent = new Intent(mContext, NewsItemView.class);
if (Link != null) {
intent.putExtra("URL", Link.get(position));
startActivity(intent);
}
}
});
} else if (Utils.isOnline(mContext) == true
&& Utils.KEY_CHECK_SUCCESS.equals("FAIL")) {
Utils.MyToast(Utils.KEYWORK_ERROR[0], R.drawable.warning_icon,
mContext, false);
}
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
AnimateFirstDisplayListener.displayedImages.clear();
}
class LoadData extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(mContext, "", Utils.KEYWORK_ERROR[2]);
data = new Vector<ArrayList<String>>();
Name = new ArrayList<String>();
School = new ArrayList<String>();
Link = new ArrayList<String>();
Icon = new ArrayList<String>();
super.onPreExecute();
}
#Override
protected String doInBackground(String... URL) {
data = Utils.getInformationTeacher(URL[0]);
if (!(data.isEmpty())) {
return Utils.KEY_CHECK_SUCCESS;
} else {
return Utils.KEY_CHECK_FAIL;
}
}
#Override
protected void onPostExecute(String result) {
if (result.equals(Utils.KEY_CHECK_SUCCESS)) {
pDialog.dismiss();
Name = data.get(0);
School = data.get(1);
Icon = data.get(2);
Link = data.get(3);
adapter = new InfoTeacher(mContext, Name, School, Icon);
lvItem.setAdapter(adapter);
} else if (result.equals(Utils.KEY_CHECK_FAIL)) {
pDialog.dismiss();
Utils.MyToast(Utils.KEYWORK_ERROR[0], R.drawable.warning_icon,
mContext, false);
}
super.onPostExecute(result);
}
}
class InfoTeacher extends BaseAdapter {
private ArrayList<String> Icon = new ArrayList<String>();
private ArrayList<String> Name = new ArrayList<String>();
private ArrayList<String> School = new ArrayList<String>();
private LayoutInflater inflater;
ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
public InfoTeacher(Context context, ArrayList<String> Name,
ArrayList<String> School, ArrayList<String> Icon) {
this.Name = Name;
this.Icon = Icon;
this.School = School;
Collections.reverse(Name);
Collections.reverse(School);
Collections.reverse(Icon);
inflater = LayoutInflater.from(getActivity());
}
#Override
public int getCount() {
return Name.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup arg2) {
View rowView = view;
ViewHolder holder;
if (rowView == null) {
holder = new ViewHolder();
rowView = inflater
.inflate(R.layout.teacher_layout, arg2, false);
holder.Name = (TextView) rowView
.findViewById(R.id.tv_NameTeacher);
holder.School = (TextView) rowView.findViewById(R.id.tv_School);
holder.ic_naviga = (ImageView) rowView
.findViewById(R.id.ivNaviga);
holder.icon = (ImageView) rowView
.findViewById(R.id.iv_IconTeacher);
rowView.setTag(holder);
} else
holder = (ViewHolder) view.getTag();
final String mIcon = Icon.get(position);
holder.Name.setText(Name.get(position).toString());
holder.School.setText(School.get(position).toString());
ImageLoader.getInstance().displayImage(mIcon, holder.icon, options,
animateFirstListener);
return rowView;
}
}
static class ViewHolder {
ImageView icon;
TextView Name;
TextView School;
ImageView ic_naviga;
}
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);
}
}
}
}
public void customLoadMoreDataFromApi(int page) {
new LoadData().execute(URL + page);
adapter.notifyDataSetChanged();
// This method probably sends out a network request and appends new data
// items to your adapter.
// Use the offset value and add it as a parameter to your API request to
// retrieve paginated data.
// Deserialize API response and then construct new objects to append to
// the adapter
}
class LoadMoreItemsList extends
AsyncTask<Void, Void, Vector<ArrayList<String>>> {
private LoadMoreItemsList() {
loadingMore = true;
mFooterView = LayoutInflater.from(mContext).inflate(
R.layout.loading_view, null);
}
#Override
protected void onPreExecute() {
lvItem.addFooterView(mFooterView);
lvItem.setAdapter(adapter);
super.onPreExecute();
}
#Override
protected Vector<ArrayList<String>> doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Vector<ArrayList<String>> result) {
super.onPostExecute(result);
}
}
}
Function Utils.Utils.getInformationTeacher(URL[0]) :
public static Vector<ArrayList<String>> getInformationTeacher(String url) {
Vector<ArrayList<String>> data = new Vector<ArrayList<String>>();
ArrayList<String> Name = new ArrayList<String>();
ArrayList<String> School = new ArrayList<String>();
ArrayList<String> Link = new ArrayList<String>();
ArrayList<String> Icon = new ArrayList<String>();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
Document doc = Jsoup.connect(url).timeout(10 * 300).get();
Charset.forName("UTF-8");
doc.outputSettings().escapeMode(EscapeMode.xhtml);
Elements eles = doc.select("div#Thu tbody a.linkheader");
Elements elesIcon = doc.select("div#Thu img[src]");
int i = 0;
for (Element element : eles) {
i++;
String fillinfo = element.ownText();
String link = element.attr("href");
if (i % 2 == 0) {
School.add(fillinfo);
} else {
Name.add(fillinfo);
Link.add(link);
}
}
for (Element icon : elesIcon) {
String hrefIcon = icon.attr("src");
Icon.add(hrefIcon);
}
data.add(Name);
data.add(School);
data.add(Icon);
data.add(Link);
} catch (IOException e) {
return data;
}
}
return data;
}
And Finally : abstract EndlessScrollListener
package android.readnews.support;
import android.util.Log;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
public abstract class EndlessScrollListener implements OnScrollListener {
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
// The current offset index of data you have loaded
private int currentPage = 0;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 0;
// True if we are still waiting for the last set of data to load.
private boolean loading = true;
// Sets the starting page index
private int startingPageIndex = 0;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
public EndlessScrollListener(int visibleThreshold, int startPage) {
this.visibleThreshold = visibleThreshold;
this.startingPageIndex = startPage;
this.currentPage = startPage;
}
// This happens many times a second during a scroll, so be wary of the code
// you place here.
// We are given a few useful parameters to help us work out if we need to
// load some more data,
// but first we check if we are waiting for the previous load to finish.
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// If the total item count is zero and the previous isn't, assume the
// list is invalidated and should be reset back to initial state
if (totalItemCount < previousTotalItemCount) {
Log.i("abc", "ABC + totalItemCount < previousTotalItemCount");
this.currentPage = this.startingPageIndex;
this.previousTotalItemCount = totalItemCount;
if (totalItemCount == 0) {
this.loading = true;
}
}
// If it’s still loading, we check to see if the dataset count has
// changed, if so we conclude it has finished loading and update the
// current page
// number and total item count.
if (loading && (totalItemCount > previousTotalItemCount)) {
Log.i("abc", "ABC + totalItemCount > previousTotalItemCount");
loading = false;
previousTotalItemCount = totalItemCount;
currentPage++;
}
// If it isn’t currently loading, we check to see if we have breached
// the visibleThreshold and need to reload more data.
// If we do need to reload some more data, we execute onLoadMore to
// fetch the data.
if (!loading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
Log.i("abc", "ABC + !loading");
onLoadMore(currentPage + 1, totalItemCount);
loading = true;
}
}
// Defines the process for actually loading more data based on page
public abstract void onLoadMore(int page, int totalItemsCount);
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Don't take any action on changed
}
}
I want load more 7 pages
In your LoadData AsyncTask, in onPostExecute, you always re-create the adapter with new data received, so it does not append the existing data.
What you need to do is add a method to InfoTeacher adapter to append new items to your existing data, and then call that method from onPostExecute if the adapter already exists (adapter != null).
i am new here. just few months back i started to learn android , i want to create listview , like parent & child relationship, when clicking the parent value in the child value should me modified. i did. but problem is that when i clicking 1st parent it's working fine while clicking another one the all values getting refresh.
my code
//int slno = 1;
int rs;
int Pcount =1;
int finalrs;
String IP_Address, url, TableNo, itmeName;
private String ITEM_NAME = "ItemName";
private String ITEM_PRICE = "price";
int in, totalqut , totalv;
String strvalp;
//public Activity activity;
//Initialize variables
private static final String STR_CHECKED = " has Checked!";
private static final String STR_UNCHECKED = " has unChecked!";
private int ParentClickStatus=-1;
private int ChildClickStatus=-1;
private ArrayList<Parent> parents;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Resources res = this.getResources();
Drawable devider = res.getDrawable(R.drawable.line);
Intent intent = getIntent();
IP_Address = intent.getStringExtra("IP_Address");
TableNo = intent.getStringExtra("TableNo");
itmeName = intent.getStringExtra("button_text");
Log.e("log_tag"," I am in Ite List Pages ");
Log.e("log_tag"," IP Address : " +IP_Address);
Log.e("log_tag", " Table Number : " +TableNo);
Log.e("log_tag", " Manu lict clicked : " +itmeName);
url= IP_Address;
// Set ExpandableListView values
getExpandableListView().setDivider(devider);
getExpandableListView().setChildDivider(devider);
getExpandableListView().setDividerHeight(1);
getExpandableListView().setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
registerForContextMenu(getExpandableListView());
//Creating static data in arraylist
final ArrayList<Parent> dummyList = buildDummyData();
// Adding ArrayList data to ExpandableListView values
loadHosts(dummyList);
}
private ArrayList<Parent> buildDummyData()
{
Log.e("log_tag"," 1 ");
// TODO Auto-generated method stub
final ArrayList<Parent> list = new ArrayList<Parent>();
// Creating ArrayList of type parent class to store parent class objects
String result1= main_menu_list();
try
{
JSONArray jArray1 = new JSONArray(result1);
Log.e("log_tag", "JSON Array length "+jArray1.length());
for (int i = 1; i < jArray1.length(); i++)
{
//Create parent class object
final Parent parent = new Parent();
// JSON object parsing
JSONObject json_data = jArray1.getJSONObject(i);
String itemnamej = json_data.getString("product_name");
String itempricej = json_data.getString("price");
// Set values in parent class object
parent.setSlno(i+".");
parent.setItemname(itemnamej);
parent.setPrice(itempricej );
parent.setChildren(new ArrayList<Child>());
// Create Child class object
final Child child = new Child();
child.setPrice(itempricej);
child.setQut("1");
//Add Child class object to parent class object
parent.getChildren().add(child);
//Adding Parent class object to ArrayList
list.add(parent);
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
return list;
}
private String main_menu_list()
{
Log.e("log_tag"," 2 ");
// TODO Auto-generated method stub
String result1 = null;
url= url + "RMS/Sub_Manu.php";
ArrayList<NameValuePair> postParameters= new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("itmeName",itmeName));
try
{
String response1 = CustomHttpClient.executeHttpPost(url,postParameters);
result1 = response1.toString();
}
catch (Exception e)
{
Log.e("log_tag","Error in http connection!!" + e.toString());
}
return result1;
}
private void loadHosts(ArrayList<Parent> newParents)
{
// TODO Auto-generated method stub
Log.e("log_tag"," 3 ");
if (newParents == null)
return;
parents = newParents;
// Check for ExpandableListAdapter object
if (this.getExpandableListAdapter() == null)
{
//Create ExpandableListAdapter Object
final MyExpandableListAdapter mAdapter = new MyExpandableListAdapter();
// Set Adapter to ExpandableList Adapter
this.setListAdapter(mAdapter);
}
else
{
// Refresh ExpandableListView data
((MyExpandableListAdapter)getExpandableListAdapter()).notifyDataSetChanged();
}
}
static class ViewHolder {
TextView slno ;
TextView itemName ;
TextView price;
ImageView rupees;
ImageView plu ;
}
/**
* A Custom adapter to create Parent view (Used grouprow.xml) and Child View((Used childrow.xml).
*/
private class MyExpandableListAdapter extends BaseExpandableListAdapter
{
private HashMap<Integer, View> childMap = null;
private int count = 1;
private Parent parent = null;
private LayoutInflater inflater;
private ViewHolder holder = null;
private int mPreviousSelectedBtnId = -1;
private int mSelectedIndex = -1;
public MyExpandableListAdapter()
{
// Create Layout Inflator
inflater = LayoutInflater.from(ItemList.this);
childMap = new HashMap<Integer, View>();
}
// This Function used to inflate parent rows view
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parentView)
{
//int i=0;
parent = parents.get(groupPosition);
if(convertView == null)
{
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.grouprow, parentView,false);
holder.itemName = (TextView)convertView.findViewById(R.id.ItemName); // title
holder.price = (TextView)convertView.findViewById(R.id.price); // description
holder.slno = (TextView)convertView.findViewById(R.id.slno); // description
holder.rupees=(ImageView)convertView.findViewById(R.id.rupees); // thumb image
holder.plu = (ImageView) convertView.findViewById(R.id.plu);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
convertView.setId(groupPosition);
holder.plu.setId(groupPosition);
holder.itemName.setTag(ITEM_NAME);
holder.price.setTag(ITEM_PRICE);
if(parent != null)
{
holder.itemName.setText(parent.getItemname());
holder.price.setText(parent.getPrice());
holder.slno.setText(groupPosition+".");
}
holder.plu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
Toast.makeText(ItemList.this,"Plus Button is clicked!", Toast.LENGTH_SHORT).show();
mSelectedIndex = arg0.getId();
if(mPreviousSelectedBtnId == arg0.getId())
{
count++;
}
else
{
count = 2;
mPreviousSelectedBtnId = arg0.getId();
}
Log.d("Elist", arg0.getId()+" >>>. Button Clicked "+count);
Log.d("Elist", arg0.getId()+" >>>. Button Parent is "+(View)arg0.getParent());
getExpandableListView().expandGroup(arg0.getId());
View childView = getExpandableListAdapter().getChildView(arg0.getId(), 0, true, getExpandableListView().getChildAt(arg0.getId()), getExpandableListView());
if(childView != null)
{
Log.d("HASH code", "In Button Click "+childView.hashCode()+"");
TextView qty = (TextView) childView.findViewById(R.id.qut);
//************************************************
// Here i am try to get parent price value
//Remark :- for the 1st prent it's show current value when i click anothere
TextView topic = (TextView) findViewById(R.id.price);
String totalprice = topic.getText().toString();
//******************************************************
Log.e("log_tag","Total Price : " +totalprice);
Log.e("log_tag","Total Quaintity : " +qty.getText().toString());
Log.e("log_tag","Total Price Value : " +topic.getText().toString());
String val = qty.getText().toString();
if(qty != null)
{
//*****************************************************
//Here Calculating the price with quantity
qty.setText(count+" ");
in = Integer.valueOf(topic.getText().toString());
totalqut = Integer.valueOf(val);
System.out.println("Total Price after conv int :" + totalqut);
totalv= in*totalqut;
System.out.println("After value : "+ totalv);
strvalp = String.valueOf(totalv);
//***********************************************
Log.d("Elist", "Text View changes called "+ qty.getTag(R.id.qut));
qty.invalidate();
}
else
{
Log.d("Elist", "Text View Null");
}
((MyExpandableListAdapter)getExpandableListAdapter()).notifyDataSetChanged();
}
else
{
Log.d("Elist", "chilGdView View Null");
}
}});
return convertView;
}
// This Function used to inflate child rows view
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parentView)
{
final Parent parent = parents.get(groupPosition);
final Child child = parent.getChildren().get(childPosition);
// Inflate childrow.xml file for child rows
convertView = inflater.inflate(R.layout.childrow, parentView, false);
// Get childrow.xml file elements and set values
((TextView) convertView.findViewById(R.id.TotalPrice)).setText(child.getPrice());
TextView mQtyText = (TextView) convertView.findViewById(R.id.qut);
TextView s2 = (TextView) convertView.findViewById(R.id.TotalPrice);
if(mQtyText!= null)
{
if(mSelectedIndex == groupPosition)
{
mQtyText.setText(count+"");
//*******************************
//setting the total price values
s2.setText(strvalp);
//*******************************
}
else
{
mQtyText.setText("1");
}
mQtyText.setTag(R.id.qut,"TextView "+groupPosition);
}
final TextView sl = (TextView) convertView.findViewById(R.id.TotalPrice);
final TextView qut = (TextView) convertView.findViewById(R.id.qut);
ImageView image=(ImageView)convertView.findViewById(R.id.mins);
Log.d("HASH code", convertView.hashCode()+"");
final TextView sll = (TextView) findViewById(R.id.price);
int sllint = Integer.valueOf(qut.getText().toString());
image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
Toast.makeText(ItemList.this," Mins Button is clicked!", Toast.LENGTH_SHORT).show();
String quantityval = qut.getText().toString();
String quantityval2 = sll.getText().toString();
String totalprice = sl.getText().toString();
Log.i("Log_tag value of quantity ",quantityval);
Log.i("Log_tag value of totalprice ",totalprice);
Log.i("Log_tag value of quantity ",quantityval2);
int in = Integer.valueOf(sll.getText().toString());
int in2 = Integer.valueOf(sl.getText().toString());
if ((in2 != 0) && (count != 0))
{
// ***************************************
// Here modify value when clicked minus button
System.out.println("Befor value : "+in);
//in -=in;
int val = in2 - in;
System.out.println("After value : "+in);
sl.setText(String.valueOf(val));
count--;
//******************************************
//String str = (String.valueOf(in));
qut.setText(count+"");
if(in == 0)
{
Log.i("Log_ tag ","If quantit queal to 0");
sl.setText("0");
qut.setText("0");
}
}
}
});
return convertView;
}
#Override
public Object getChild(int groupPosition, int childPosition)
{
return getExpandableListView().getChildAt(groupPosition);
}
//Call when child row clicked
#Override
public long getChildId(int groupPosition, int childPosition)
{
/****** When Child row clicked then this function call *******/
if( ChildClickStatus!=childPosition)
{
ChildClickStatus = childPosition;
Toast.makeText(getApplicationContext(), "$$$Parent :"+groupPosition + "**** Child :"+childPosition , Toast.LENGTH_LONG).show();
}
return childPosition;
}
#Override
public int getChildrenCount(int groupPosition)
{
int size=0;
Log.e("log_tag"," 9 ");
if(parents.get(groupPosition).getChildren()!=null)
size = parents.get(groupPosition).getChildren().size();
return size;
}
#Override
public Object getGroup(int groupPosition)
{
Log.i("Parent", groupPosition+"= getGroup ");
return parents.get(groupPosition);
}
#Override
public int getGroupCount()
{
return parents.size();
}
//Call when parent row clicked
#Override
public long getGroupId(int groupPosition)
{
Log.i("Parent", groupPosition+"= getGroupId "+ParentClickStatus);
if(groupPosition==2 && ParentClickStatus!=groupPosition){
//Alert to user
Toast.makeText(getApplicationContext(), "Parent :"+groupPosition ,
Toast.LENGTH_LONG).show();
}
ParentClickStatus=groupPosition;
if(ParentClickStatus==0)
ParentClickStatus=-1;
return groupPosition;
}
#Override
public void notifyDataSetChanged()
{
Log.e("log_tag"," 13 ");
// Refresh List rows
super.notifyDataSetChanged();
}
#Override
public boolean isEmpty()
{
Log.e("log_tag"," 14 ");
return ((parents == null) || parents.isEmpty());
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
Log.e("log_tag"," 15 ");
return true;
}
#Override
public boolean hasStableIds()
{
Log.e("log_tag"," 16 ");
return true;
}
#Override
public boolean areAllItemsEnabled()
{
Log.e("log_tag"," 17 ");
return true;
}
}
}
My listview doesn't show exact placement of images on its individual custom adapters. I am trying to load the images using AsyncTask. Sometimes the images duplicates and I don't have any idea why. Here is my ArrayAdapter code:
public class NewsPromoAdapter extends ArrayAdapter<NewsPromosDTO> {
private final Context context;
List<NewsPromosDTO> npList;
LayoutInflater inflater;
Bitmap src;
public NewsPromoAdapter(Context context, List<NewsPromosDTO> npList) {
super(context, R.layout.news_and_promos, npList);
this.context = context;
this.npList = npList;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public static class ViewHolder {
TextView nameText;
TextView date1Text;
ImageView imageView;
ProgressBar prg;
LoadImage loadImg;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.news_and_promos, parent,
false);
holder = new ViewHolder();
holder.nameText = (TextView) convertView
.findViewById(R.id.newspromo_name);
holder.date1Text = (TextView) convertView
.findViewById(R.id.newspromo_date);
holder.imageView = (ImageView) convertView
.findViewById(R.id.newspromo_imageView);
holder.prg = (ProgressBar) convertView
.findViewById(R.id.progressBar1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
holder.loadImg.cancel(true);
}
if (!(npList.get(position).getName().equals(""))) {
holder.nameText.setVisibility(View.VISIBLE);
holder.nameText.setText(npList.get(position).getName());
} else {
holder.nameText.setVisibility(View.GONE);
}
if (!(npList.get(position).getDate().equals(""))) {
holder.date1Text.setVisibility(View.VISIBLE);
holder.date1Text.setText(npList.get(position).getDate());
} else {
holder.date1Text.setVisibility(View.GONE);
}
if (!(npList.get(position).getImageURL().equals(""))) {
holder.imageView.setVisibility(View.VISIBLE);
holder.loadImg = new LoadImage(holder.imageView, npList.get(
position).getImageURL(), holder);
holder.loadImg.execute();
} else {
holder.imageView.setVisibility(View.GONE);
holder.prg.setVisibility(View.GONE);
}
return convertView;
}
class LoadImage extends AsyncTask<Object, Void, Bitmap> {
ViewHolder viewH;
private ImageView imv;
private String url;
public LoadImage(ImageView imv, String imageURL, ViewHolder viewH) {
this.imv = imv;
this.url = imageURL;
this.viewH = viewH;
}
#Override
protected Bitmap doInBackground(Object... params) {
BitmapFromURL bmpURL = new BitmapFromURL();
src = bmpURL.getBitmapFromURL(url);
return src;
}
#Override
protected void onPostExecute(Bitmap result) {
// imv.setImageBitmap(result);
// viewH.prg.setVisibility(View.GONE);
viewH.prg.setVisibility(View.GONE);
imv.setImageBitmap(result);
}
}
}
Here is the Activity that handles the ADAPTER. I am implementing the Endless listview approach that some big sites uses. Like Facebook, Twitter, etc..New Items loaded into the listview when scrolling into the bottom. I am not sure if I did it well.
public class ListNewsPromoActivity extends Activity {
List<NewsPromosDTO> npList;
String url, user_email;
Bundle extras;
int user_points;
List<Integer> npIDs;
private ProgressDialog progressDialog;
BitmapFromURL bmpURL;
JSONArray users = null;
String TAG_ID = "id";
String TAG_NAME = "name";
String TAG_PHOTO = "photo";
String TAG_DATE = "date";
String TAG_DESC = "description";
ListView list;
NewsPromoAdapter newsAdapter;
boolean loadingMore = false;
private Runnable returnRes;
int itemsPerPage = 3;
int currentIndex = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.news_promo_listview);
list = (ListView) findViewById(R.id.mainView);
extras = getIntent().getExtras();
if (extras != null) {
user_points = extras.getInt("user_points");
user_email = extras.getString("user_email");
}
url = getString(R.string.app_url_news_promos);
npIDs = new ArrayList<Integer>();
npList = new ArrayList<NewsPromosDTO>();
View footerView = ((LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.footer, null, false);
newsAdapter = new NewsPromoAdapter(ListNewsPromoActivity.this, npList);
list.addFooterView(footerView);
list.setAdapter(newsAdapter);
list.setOnScrollListener(new OnScrollListener() {
// useless here, skip!
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
// is the bottom item visible & not loading more already ? Load
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
Thread thread = new Thread(null, getRunnable());
thread.start();
}
}
});
// Runnable to load the items
// Since we cant update our UI from a thread this Runnable takes care of
// that!
returnRes = new Runnable() {
#Override
public void run() {
// Loop thru the new items and add them to the adapter
for (NewsPromosDTO np : npList) {
System.out.println(np.getName() + " andito ako!!");
newsAdapter.add(np);
}
newsAdapter.notifyDataSetChanged();
// Done loading more.
loadingMore = false;
}
};
}
protected class loadNewsPromo extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Void... params) {
// Creating JSON Parser instance
loadingMore = true;
JSONParser jParser = new JSONParser();
JSONObject json;
if (jParser.checkServer(url)) {
try {
// Getting Array of UserNews
json = jParser.getJSONFromUrl(url);
users = json.getJSONArray(user_email);
// looping through All UserNews
for (int i = currentIndex; i < itemsPerPage; i++) {
if (itemsPerPage == i) {
// currentIndex--;
break;
} else {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
NewsPromosDTO npDTO = new NewsPromosDTO();
npDTO.setImageURL(c.getString(TAG_PHOTO));
npDTO.setId(c.getInt(TAG_ID));
npDTO.setName(c.getString(TAG_NAME));
npDTO.setDate(c.getString(TAG_DATE));
npDTO.setDescription(c.getString(TAG_DESC));
npList.add(npDTO);
currentIndex++;
}
}
} catch (JSONException e) {
e.printStackTrace();
return null;
} finally {
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) { //
// progressDialog.dismiss();
loadingMore = false;
list();
}
}
public void list() {
// add the footer before adding the adapter, else the footer will not
// load!
View footerView = ((LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.footer, null, false);
newsAdapter = new NewsPromoAdapter(ListNewsPromoActivity.this, npList);
list.addFooterView(footerView);
list.setAdapter(newsAdapter);
}
public Runnable getRunnable() {
Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
// Set flag so we cant load new items 2 at the same time
loadingMore = true;
// Reset the array that holds the new items
// Simulate a delay, delete this on a production environment!
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
// Get 15 new listitems
JSONParser jParser = new JSONParser();
JSONObject json;
npList = new ArrayList<NewsPromosDTO>();
if (jParser.checkServer(url)) {
try {
// Getting Array of Contacts
json = jParser.getJSONFromUrl(url);
users = json.getJSONArray(user_email);
// looping through All Contacts
// if (itemsPerPage > users.length() - currentIndex) {
// itemsPerPage = users.length();
// }
npList = new ArrayList<NewsPromosDTO>();
System.out.println(users.length() + " Laman ng users");
int counter = 0;
for (int i = currentIndex; i < users.length(); i++) {
if (itemsPerPage == counter) {
break;
} else {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
NewsPromosDTO npDTO = new NewsPromosDTO();
npDTO.setImageURL(c.getString(TAG_PHOTO));
npDTO.setId(c.getInt(TAG_ID));
npDTO.setName(c.getString(TAG_NAME));
npDTO.setDate(c.getString(TAG_DATE));
npDTO.setDescription(c.getString(TAG_DESC));
npList.add(npDTO);
currentIndex++;
}
counter++;
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
}
// Done! now continue on the UI thread
runOnUiThread(returnRes);
}
};
return loadMoreListItems;
}
}
I am using a baseadapter for my customize spinner with checkbox that allow the user to choose multiple values. I have an update button in my application, and I need to set the values from the database as true in the checkbox. My problem is I don't know how to do it. For example I have ["A","B","C","D"] values in my spinner, in my database I got B and D. How will i automatically check that values when I open the activity.
Here is my code that populate my customize spinner
private void initializeCustomerSegment() {
final ArrayList<String> consumerSegments = new ArrayList<String>();
List<String> consumerSegment = databaseHandler.setItemOnConsumerSeg();
consumerSegments.addAll(consumerSegment);
checkSelectedConsumerSegment = new boolean[consumerSegments.size()];
//initialize all values of list to 'unselected' initially
for (int i = 0; i < checkSelectedConsumerSegment.length; i++) {
checkSelectedConsumerSegment[i] = false;
}
final TextView tv_ConsumerSegment = (TextView) findViewById(R.DropDownList.tv_ConsumerSegment);
tv_ConsumerSegment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!expandedConsumerSegment) {
// display all selected values
String selected = "";
int flag = 0;
for (int i = 0; i < consumerSegments.size(); i++) {
if (checkSelectedConsumerSegment[i] == true) {
selected += consumerSegments.get(i);
selected += ", ";
flag = 1;
}
}
if(flag == 1) {
tv_ConsumerSegment.setText(selected);
}
expandedConsumerSegment =true;
} else {
//display shortened representation of selected values
tv_ConsumerSegment.setText(BrandListAdapter.getSelected());
expandedConsumerSegment = false;
}
}
});
//onClickListener to initiate the dropDown list
TextView tv_customerSegment = (TextView)findViewById(R.DropDownList.tv_ConsumerSegment);
tv_customerSegment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
initiatePopUpCustomerSegment(consumerSegments,tv_ConsumerSegment);
}
});
}
private void initiatePopUpCustomerSegment(ArrayList<String> customerSegments, TextView tv_CustomerSegment) {
LayoutInflater inflater = (LayoutInflater)S_10th_IReportMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get the pop-up window i.e. drop-down layout
LinearLayout layoutCustomerSegment = (LinearLayout)inflater.inflate(R.layout.pop_up_window_customersegment, (ViewGroup)findViewById(R.id.PopUpView1));
//get the view to which drop-down layout is to be anchored
RelativeLayout layout4 = (RelativeLayout)findViewById(R.id.relativeLayout4);
pwConsumerSegment = new PopupWindow(layoutCustomerSegment, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
//Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
pwConsumerSegment.setBackgroundDrawable(new BitmapDrawable());
pwConsumerSegment.setTouchable(true);
//let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
pwConsumerSegment.setOutsideTouchable(true);
pwConsumerSegment.setHeight(LayoutParams.WRAP_CONTENT);
//dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
pwConsumerSegment.setTouchInterceptor(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pwConsumerSegment.dismiss();
return true;
}
return false;
}
});
//provide the source layout for drop-down
pwConsumerSegment.setContentView(layoutCustomerSegment);
//anchor the drop-down to bottom-left corner of 'layout1'
pwConsumerSegment.showAsDropDown(layout4);
//populate the drop-down list
final ListView listCustomerSegment = (ListView) layoutCustomerSegment.findViewById(R.DropDownList.dropDownCustomerSegment);
ConsumerSegmentListAdapter adapter = new ConsumerSegmentListAdapter(this, customerSegments, tv_CustomerSegment);
listCustomerSegment.setAdapter(adapter);
}
here is my ConsumerSegmentListAdapter. The listview acts as my spinner.
public class ConsumerSegmentListAdapter extends BaseAdapter {
private ArrayList<String> mListCustomerSegment;
private LayoutInflater mInflater;
private TextView mSelectedItems;
private static int selectedCount = 0;
private static String firstSelected = "";
private ViewHolder holder;
private static String selected = ""; //shortened selected values representation
public static String getSelected() {
return selected;
}
public void setSelected(String selected) {
ConsumerSegmentListAdapter.selected = selected;
}
public ConsumerSegmentListAdapter(Context context, ArrayList<String> customerSegment,
TextView tv) {
mListCustomerSegment = new ArrayList<String>();
mListCustomerSegment.addAll(customerSegment);
mInflater = LayoutInflater.from(context);
mSelectedItems = tv;
}
#Override
public int getCount() {
return mListCustomerSegment.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.drop_down_customersegment, null);
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.DropDownList.SelectOptionCustomerSegment);
holder.chkbox = (CheckBox) convertView.findViewById(R.DropDownList.checkboxCustomerSegment);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tv.setText(mListCustomerSegment.get(position));
final int position1 = position;
//whenever the checkbox is clicked the selected values textview is updated with new selected values
holder.chkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setText(position1);
}
});
if(S_10th_IReportMain.checkSelectedConsumerSegment[position])
holder.chkbox.setChecked(true);
else
holder.chkbox.setChecked(false);
return convertView;
}
/*
* Function which updates the selected values display and information(checkSelectedConsumerSegment[])
* */
private void setText(int position1){
if (!S_10th_IReportMain.checkSelectedConsumerSegment[position1]) {
S_10th_IReportMain.checkSelectedConsumerSegment[position1] = true;
selectedCount++;
} else {
S_10th_IReportMain.checkSelectedConsumerSegment[position1] = false;
selectedCount--;
}
if (selectedCount == 0) {
mSelectedItems.setText(R.string.select_consumersegment);
} else if (selectedCount == 1) {
for (int i = 0; i < S_10th_IReportMain.checkSelectedConsumerSegment.length; i++) {
if (S_10th_IReportMain.checkSelectedConsumerSegment[i] == true) {
firstSelected = mListCustomerSegment.get(i);
break;
}
}
mSelectedItems.setText(firstSelected);
setSelected(firstSelected);
} else if (selectedCount > 1) {
for (int i = 0; i < S_10th_IReportMain.checkSelectedConsumerSegment.length; i++) {
if (S_10th_IReportMain.checkSelectedConsumerSegment[i] == true) {
firstSelected = mListCustomerSegment.get(i);
break;
}
}
mSelectedItems.setText(firstSelected + " & "+ (selectedCount - 1) + " more");
setSelected(firstSelected + " & "+ (selectedCount - 1) + " more");
}
}
private class ViewHolder {
TextView tv;
CheckBox chkbox;
}
}
I think You need to manage another storage for selected / unselected items and move it to the adapter. E.g. it can be HashSet<String>. Then code would look the following (note, that I made it compilable, because it's impossible to compile one provided in the question):
public class S_10th_IReportMain extends Activity {
boolean expandedConsumerSegment;
ConsumerSegmentListAdapter mAdapter;
private static class DatabaseHandler {
List<String> setItemOnConsumerSeg() {
return Collections.emptyList();
}
}
private static class BrandListAdapter {
static String getSelected() {
return "string";
}
}
DatabaseHandler databaseHandler = new DatabaseHandler();
private void initializeCustomerSegment() {
final ArrayList<String> consumerSegments = new ArrayList<String>();
List<String> consumerSegment = databaseHandler.setItemOnConsumerSeg();
consumerSegments.addAll(consumerSegment);
final TextView tv_ConsumerSegment = (TextView) findViewById(R.id.tv_ConsumerSegment);
tv_ConsumerSegment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!expandedConsumerSegment) {
// display all selected values
String selected = "";
int flag = 0;
for (String segment : consumerSegments) {
if (mAdapter.isChecked(segment)) {
selected += segment;
selected += ", ";
flag = 1;
}
}
if(flag == 1) {
tv_ConsumerSegment.setText(selected);
}
expandedConsumerSegment =true;
} else {
//display shortened representation of selected values
tv_ConsumerSegment.setText(BrandListAdapter.getSelected());
expandedConsumerSegment = false;
}
}
});
//onClickListener to initiate the dropDown list
TextView tv_customerSegment = (TextView)findViewById(R.id.tv_ConsumerSegment);
tv_customerSegment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
initiatePopUpCustomerSegment(consumerSegments,tv_ConsumerSegment);
}
});
}
PopupWindow pwConsumerSegment;
private void initiatePopUpCustomerSegment(ArrayList<String> customerSegments, TextView tv_CustomerSegment) {
LayoutInflater inflater = (LayoutInflater)S_10th_IReportMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get the pop-up window i.e. drop-down layout
LinearLayout layoutCustomerSegment = (LinearLayout)inflater.inflate(R.layout.pop_up_window_customersegment, (ViewGroup)findViewById(R.id.PopUpView1));
//get the view to which drop-down layout is to be anchored
RelativeLayout layout4 = (RelativeLayout)findViewById(R.id.relativeLayout4);
pwConsumerSegment = new PopupWindow(layoutCustomerSegment, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
//Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
pwConsumerSegment.setBackgroundDrawable(new BitmapDrawable());
pwConsumerSegment.setTouchable(true);
//let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
pwConsumerSegment.setOutsideTouchable(true);
pwConsumerSegment.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
pwConsumerSegment.setTouchInterceptor(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pwConsumerSegment.dismiss();
return true;
}
return false;
}
});
//provide the source layout for drop-down
pwConsumerSegment.setContentView(layoutCustomerSegment);
//anchor the drop-down to bottom-left corner of 'layout1'
pwConsumerSegment.showAsDropDown(layout4);
//populate the drop-down list
final ListView listCustomerSegment = (ListView) layoutCustomerSegment.findViewById(R.id.dropDownCustomerSegment);
ConsumerSegmentListAdapter adapter = new ConsumerSegmentListAdapter(this, customerSegments, tv_CustomerSegment);
listCustomerSegment.setAdapter(adapter);
}
public static class ConsumerSegmentListAdapter extends BaseAdapter {
private ArrayList<String> mListCustomerSegment;
private LayoutInflater mInflater;
private TextView mSelectedItems;
private static int selectedCount = 0;
private static String firstSelected = "";
private ViewHolder holder;
private static String selected = ""; //shortened selected values representation
private HashSet<String> mCheckedItems;
public static String getSelected() {
return selected;
}
public void setSelected(String selected) {
ConsumerSegmentListAdapter.selected = selected;
}
public ConsumerSegmentListAdapter(Context context, ArrayList<String> customerSegment,
TextView tv) {
mListCustomerSegment = new ArrayList<String>();
mListCustomerSegment.addAll(customerSegment);
mInflater = LayoutInflater.from(context);
mSelectedItems = tv;
}
/**
* Should be called then new data obtained from DB
*
* #param checkedItems array of strings obtained from DB
*/
public void setCheckedItems(final String[] checkedItems) {
mCheckedItems.clear();
Collections.addAll(mCheckedItems, checkedItems);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mListCustomerSegment.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.drop_down_customersegment, null);
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.id.SelectOptionCustomerSegment);
holder.chkbox = (CheckBox) convertView.findViewById(R.id.checkboxCustomerSegment);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final String text = mListCustomerSegment.get(position);
final boolean checked = isChecked(text);
holder.tv.setText(mListCustomerSegment.get(position));
//whenever the checkbox is clicked the selected values textview is updated with new selected values
holder.chkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setText(position, checked, text);
}
});
if(checked) {
holder.chkbox.setChecked(true);
} else {
holder.chkbox.setChecked(false);
}
return convertView;
}
/*
* Function which updates the selected values display and information(checkSelectedConsumerSegment[])
* */
private void setText(int position, boolean checked, String text){
if (!checked) {
mCheckedItems.add(text);
selectedCount++;
} else {
mCheckedItems.remove(text);
selectedCount--;
}
if (selectedCount == 0) {
mSelectedItems.setText(R.string.select_consumersegment);
} else if (selectedCount == 1) {
firstSelected = mCheckedItems.iterator().next();
mSelectedItems.setText(firstSelected);
setSelected(firstSelected);
} else if (selectedCount > 1) {
firstSelected = mCheckedItems.iterator().next();
mSelectedItems.setText(firstSelected + " & "+ (selectedCount - 1) + " more");
setSelected(firstSelected + " & "+ (selectedCount - 1) + " more");
}
}
/**
* #param segment to be checked
*
* #return true if the segment is checked
*/
public boolean isChecked(final String segment) {
return mCheckedItems.contains(segment);
}
private class ViewHolder {
TextView tv;
CheckBox chkbox;
}
}
}
So, then You obtain new data from database which should be checked You can just call mAdapter.setCheckedItems().
I already make it. By this:
for (int j=0; j<brands.size(); j++)
{
for(String chosenElement : Brands)
{
int index = brands.indexOf(chosenElement);
checkSelected[index] = true;
}
}
What I did is i look for the index of my chosen arraylist to my spinner's adapter and set the the checkbox index into true. That simple. Anyway thanks for the idea.