Android expandableListView add variable to a button - android

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?

Related

Show the Elements from ArrayList of map ,in list form in Android

I have a A data stored in ArrayList< HashMap< String, String> > retrieved from JSON
in the form (i.e.)
[{price: =1685 name: =Monographie Der Gattung Pezomachus (Grv.) by Arnold F. Rster}]
And I need to show the all map elements into list form in Android.
I've tried many ways but I'm unable to do it .
Also help me to know about the layouts to use in it
EDITED:
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(myarr_list);
setListAdapter(adapter);
And in the MySimpleArrayAdapter Class, in Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl) {
LayoutInflator inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
The control does not proceed after this,
MySimpleArrayAdapter Class
public class MySimpleArrayAdapter extends BaseAdapter{
ArrayList<HashMap<String, String>> ProductList = new ArrayList<HashMap<String, String>>();
LayoutInflater inflater;
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
//Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl) {
this.ProductList = pl;
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
View myview = convertView;
if (convertView == null) {
myview = inflater.inflate(R.layout.show_search_result, null);
}
TextView price = (TextView) myview.findViewById(R.id.price);
TextView name = (TextView) myview.findViewById(R.id.name);
HashMap<String, String> pl = new HashMap<String, String>();
pl = ProductList.get(position);
//Setting
price.setText(pl.get("price"));
name.setText(pl.get("name"));
return myview;
}
}
I am editing here a onPostExecute class from SearchResultsTask extended by AsyncTask
protected void onPostExecute(JSONObject json) {
if (json != null && json.length() > 0) {
try {
JSONArray json_results = (JSONArray)(json.get("results"));
String parsedResult = "";
System.out.println("-> Size ="+ json_results.length());
for(int i = 0; i < json_results.length(); i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject json_i = json_results.getJSONObject(i);
map.put("name: ",json_i.getString("name") + "\n");
map.put("price: ",json_i.getString("price") + "\n");
arr_list.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println("-> Size =====arr_llist ="+ arr_list.size());
// CustomListAdapter adapter = new CustomListAdapter (arr_list);
//final StableArrayAdapter adapter = new StableArrayAdapter(this, R.id.result, arr_list);
// listview.setAdapter(adapter);
MyListActivity obj1 = new MyListActivity();
Bundle icicle = null;
obj1.onCreate(icicle);
}
public class MyListActivity extends Activity {
public void onCreate(Bundle icicle) {
// System.out.println("In my list Activity");
// super.onCreate(icicle);
//populate list
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this,arr_list);
// System.out.println("in 2");
adapter.getView(0, listview, listview);
listview.setAdapter(adapter);
}
}
#Override
public int getCount() {
return ProductList.size() ;
}
//Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl, Context c) {
this.ProductList = pl;
inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
getSystemService() is method of context, you are calling it on instance of adapter.

Expandablelistview adapter from phpmyadmin

I'd like to make expandable listview in android of product's list which grouped by the category. I'm using phpmyadmin as my database. How can I show the child based on their categories?
I am using JSONParser & Php code here.
Category 1
- Product A
- Product B
Category 2
- Product C
- Product D
This is the php code for show the header (category)
<?php
include("koneksi.php");
$q = mysql_query('select * from kategori_barang');
$v = '{"info" : [';
while($r=mysql_fetch_array($q))
{
$ob = array("<br>","<b>","</b>");
if(strlen($v)<12)
{
$v .= '{"id_kat" : "'.$r['id_kat'].'", "kat_barang" : "'.$r['kat_barang'].'"}';
}
else
{
$v .= '{"id_kat" : "'.$r['id_kat'].'", "kat_barang" : "'.$r['kat_barang'].'"}';
}
}
$v .= ']}';
echo $v;
?>
Here is my database
`product_id` int(4) NOT NULL AUTO_INCREMENT,
`cat_id` int(4) NOT NULL DEFAULT '0',
`subcat_id` int(4) NOT NULL DEFAULT '0',
`product_name` varchar(50) NOT NULL DEFAULT '',
`product_price` int(8) NOT NULL DEFAULT '0',
`product_weight` int(4) NOT NULL DEFAULT '0',
`product_weight_unit` varchar(10) NOT NULL DEFAULT '',
`product_price_unit` varchar(10) NOT NULL DEFAULT '',
`product_image` varchar(250) DEFAULT NULL,
`product_in_stock` int(8) DEFAULT NULL,
Here is my adapter
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 childPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
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);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblItem);
txtListChild.setText(childText);
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() {
// TODO Auto-generated method stub
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return 0;
}
#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 lblHeader = (TextView) convertView
.findViewById(R.id.lblHeader);
lblHeader.setTypeface(null, Typeface.BOLD);
lblHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isChildSelectable(int arg0, int arg1) {
// TODO Auto-generated method stub
return true;
}
and here is my mainactivity
public class MainActivity extends Activity {
String link_url = "";
String [] str=null;
public static final String AR_ID_KAT = "id_kat";
public static final String AR_KAT_BARANG = "kat_barang";
JSONArray str_login = null;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<HashMap<String, String>> daftar_buku = new ArrayList<HashMap<String, String>>();
ProgressDialog mProgressDialog;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
ArrayList<HashMap<String, String>> arraylist;
HashMap<String, List<String>> listDataChild;
String id_kat, kat_barang;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
return false;
}
});
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Sharani Designs");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
/*arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
jsonobject = JSONParser
.getJSONfromURL("http://api.androidhive.info/contacts/");
*/
JSONParser jParser = new JSONParser();
link_url = "http://10.0.2.2/login/test_kat.php";
JSONObject json = jParser.AmbilJson(link_url);
try {
str_login = json.getJSONArray("info");
for (int i = 0; i < str_login.length(); i++) {
JSONObject ar = str_login.getJSONObject(i);
String id = ar.getString(AR_ID_KAT);
String isb = ar.getString(AR_KAT_BARANG);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(AR_ID_KAT, id);
map.put(AR_KAT_BARANG, isb);
daftar_buku.add(map);
}
}
catch (JSONException e) {
e.printStackTrace();
}
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
mProgressDialog.dismiss();
}
}

Custom ExpandableListview which contain another expand button in child

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;
}
}

Restarting Asynctask in fragment after using replace transaction

I am using AsyncTask in my fragment for loading a list of data by Json. After clicking each list items this list fragment is replaced by details fragment containing details information. Then in new fragment (details fragment) user presses back button. Then again list fragment starts.
The problem is that Asynctask reloads again to fetch list items. I don't want this. I want to show previously loaded list. Here is the code:
public class MainList extends Fragment {
public MainList(){}
ArrayList<Country> countryList = new ArrayList<Country>();
Country country;
Button btnLoadMore;
ListView listView;
JSONParser jsonParser = new JSONParser();
public static String received_id;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
int current_page = 0;
int last_item;
int total_items = 32;
boolean continue_loading = true;
boolean loadingMore = false;
View footerView;
public ImageLoader_Json imageLoader;
int currentPosition = 0;
MyCustomAdapter dataAdapter = null;
private static String url_all_products_LoadMore = "http://www.hitel.ir/FarsiPlanet/Apps.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_RATE = "rate";
private static final String TAG_RATINGCOUNT = "ratingcount";
private static final String TAG_SHORT_DESCRIPTION = "short_description";
// products JSONArray
JSONArray products = null;
String Category;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.items_list, container, false);
Category = getArguments().getString("category");
footerView= ((LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_footer, null,false);
listView = (ListView) rootView.findViewById(R.id.listView1);
listView.addFooterView(footerView);
imageLoader = new ImageLoader_Json(getActivity().getApplicationContext());
displayListView();
return rootView;
}
private void displayListView() {
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(getActivity(),
R.layout.country_info, countryList);
listView.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if((lastInScreen == totalItemCount) && !(loadingMore)){
new loadMoreListView().execute();
}
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
Bundle data = new Bundle();
data.putString(TAG_PID, pid);
data.putString("TAG_Category", Category);
Fragment fragment = new Details_Restaurant();
FragmentManager fm = getFragmentManager();
fragment.setArguments(data);
fm.beginTransaction().replace(R.id.frame_container, fragment).addToBackStack("f_02").commit();
}
});
listView.setAdapter(dataAdapter);
listView.setSelectionFromTop(currentPosition, 0);
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> countryList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
}
private class ViewHolder {
TextView code;
TextView name;
RatingBar rate;
TextView ratingcount;
TextView short_description;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.ratingcount = (TextView) convertView.findViewById(R.id.ratingCount);
holder.short_description = (TextView) convertView.findViewById(R.id.short_description);
holder.rate = (RatingBar) convertView.findViewById(R.id.ratingBar1);
holder.code = (TextView) convertView.findViewById(R.id.pid);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Country country = countryList.get(position);
holder.name.setText(country.getName());
holder.ratingcount.setText(country.getRatingCount());
holder.short_description.setText(country.getShort_description());
holder.rate.setRating(country.getRate());
holder.code.setText(country.getCode());
return convertView;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
class loadMoreListView extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("درحال دريافت اطلاعات...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show(); */
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
String firts_item = Integer.toString(current_page*10);
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", firts_item));
params.add(new BasicNameValuePair("category", Category));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_all_products_LoadMore, "GET", params);
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
Float rate = (float) c.getInt(TAG_RATE);
String ratingcount = c.getString(TAG_RATINGCOUNT);
String short_description = c.getString(TAG_SHORT_DESCRIPTION);
country = new Country(id,name,rate,ratingcount,short_description,"","");
countryList.add(country);
}
}
else{
continue_loading = false;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
current_page += 1;
if (continue_loading) {
currentPosition = listView.getFirstVisiblePosition();
dataAdapter.notifyDataSetChanged();
displayListView();
loadingMore = false;
} else {
listView.removeFooterView(footerView);
}
}
}
}
Here you need to include #Override before calling onScrollStateChanged and onScroll
listView.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if((lastInScreen == totalItemCount) && !(loadingMore)){
new loadMoreListView().execute();
}
}
});
when you perform the replace() action on the fragment, you are removing the list fragment , thus when tapping back, you are replacing the details fragment with your listfragment which invokes onCreateView() as part of the fragments lifecycle.
I would try to either keep a static booelan set to true when the asynctask's onPostExecute() ends, so the next time the list fragment's onCreateView() will be invoked , you would check the value of the flag and if set to true will not execute the task, but just set the adapter with the old static data.

How to start a new activity form ListView and give it multiple parameters

Below is my code which displays data in listview which is parses from json.
I want to start new activity when the user clicks on any item in the list.
I followed this url http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ and this is the json file http://api.androidhive.info/contacts/
How to start a new activity when a user clicks on any item in listview and pass the remaining json values as parameters?
Now my listview shows only names but i want to pass the remaining items, such as email, gender & mobile to the other activity.
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
public class NewsRowAdapter extends ArrayAdapter<Item> {
private Activity activity;
private List<Item> items;
private Item objBean;
private int row;
Context context;
public NewsRowAdapter(Activity act, int resource, List<Item> arrayList) {
super(act, resource, arrayList);
this.activity = act;
this.row = resource;
this.items = arrayList;
}
#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 ((items == null) || ((position + 1) > items.size()))
return view;
objBean = items.get(position);
holder.tvName = (TextView) view.findViewById(R.id.txtText);
if (holder.tvName != null && null != objBean.getName()
&& objBean.getName().trim().length() > 0) {
holder.tvName.setText(Html.fromHtml(objBean.getName()));
Intent intent=new Intent(context,TodayLunch.class);
intent.putExtra("name", Html.fromHtml(objBean.getName()));
context.startService(intent);
}
return view;
}
public class ViewHolder {
public TextView tvName, tvCity, tvBDate, tvGender, tvAge;
}
}
package com.schoollunchapp;
public class SeletecDayofweek extends Activity implements OnItemClickListener {
private static final String rssFeed = "http://192.168.2.100/jsonparsing.txt";
private static final String ARRAY_NAME = "student";
private static final String ID = "id";
private static final String NAME = "name";
private static final String CITY = "dish";
private static final String GENDER = "Gender";
private static final String AGE = "age";
private static final String BIRTH_DATE = "birthdate";
ListView listMainMenu;
List<Item> arrayOfList;
//MainMenuAdapter mma;
NewsRowAdapter objAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectdayofweek);
listMainMenu = (ListView) findViewById(R.id.listMainMenu2);
listMainMenu.setOnItemClickListener(this);
arrayOfList = new ArrayList<Item>();
if (URLUtils.isNetworkAvailable(SeletecDayofweek.this)) {
new MyTask().execute(rssFeed);
} else {
showToast("No Network Connection!!!");
}
}
// My AsyncTask start...
class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SeletecDayofweek.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return URLUtils.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("No data found from web!!!");
SeletecDayofweek.this.finish();
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray =
mainJson.getJSONArray(ARRAY_NAME);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objJson =
jsonArray.getJSONObject(i);
Item objItem = new Item();
objItem.setId(objJson.getInt(ID));
objItem.setName(objJson.getString(NAME));
objItem.setCity(objJson.getString(CITY));
objItem.setGender(objJson.getString(GENDER));
objItem.setAge(objJson.getInt(AGE));
objItem.setBirthdate(objJson.getString(BIRTH_DATE));
arrayOfList.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// showDeleteDialog(position);
}
public void setAdapterToListview() {
objAdapter = new NewsRowAdapter(SeletecDayofweek.this,
R.layout.main_menu_item,
arrayOfList);
listMainMenu.setAdapter(objAdapter);
}
public void showToast(String msg) {
Toast.makeText(SeletecDayofweek.this, msg, Toast.LENGTH_LONG).show();
}
}
create array list like this
public ArrayList<String> Id = new ArrayList<String>();
public ArrayList<String> Name = new ArrayList<String>();
public ArrayList<String> Gender= new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objJson = jsonArray.getJSONObject(i);
// here you can get id,name,city...
Id.add(objJson.getInt("id"));
Name.add(objJson.getString("name"));
Gender.add(objJson.getString("Gender"));
//You need to use this code in the class where you have the view ,
// list item click
List_View.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(this, abc.class);
// here arg2 is argument of onitemclick method
// this will pick the same item from array list that is clicked on list view
i.putExtra("key_name" , Id.get(arg2));
i.putExtra("key_name" , Name.get(arg2));
i.putExtra("key_name" , Gender.get(arg2));
startActivity(i);
}
});
can see this also
http://www.ezzylearning.com/tutorial.aspx?tid=1351248
and
http://www.bogotobogo.com/Android/android6ListViewSpinnerGridViewGallery.php
You start an activty with startActivity(intent);
You set the OnClickListner on your ListView which is not included in your code so Im implying:
OnItemClickListener listener = new OnItemClickListener (){
#Override
onItemClick(AdapterView<?> parent, View view, int position, long id){
String name = ((TextView) view.findViewById(R.id.txtText)).getText();
Intent intent = new Intent(context,WhatEverYouWant.class);
intent.putExtra("name",name);
startActivity(intent);
}
}
ListView listView = getView().findViewById(R.id.listview);
listView.setOnItemClickListener (listener);
I thing you shold put objJson.getString(NAME); after onItemClick...... to take the clicked item string name not other item

Categories

Resources