This is my homepage.xml - where list view is placed:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:orientation="vertical"
tools:context="com.andapps.azaz.e_recommender.HomePage">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Category:"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
/>
<Spinner
android:id="#+id/spcategorieshomepage"
android:layout_width="match_parent"
android:layout_height="35sp"
android:layout_marginRight="14sp"
android:spinnerMode="dropdown"
android:textColor="#color/textColor"
>
</Spinner>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/llhome"
android:gravity="center"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp">
<ListView
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
</LinearLayout>
</LinearLayout>
And also my customlist.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product ID:"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
android:id="#+id/tvproductid"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product Name:"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
android:id="#+id/tvproductname"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product Rating:"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
/>
<RatingBar
android:id="#+id/ratingBar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:max="5"
android:numStars="5" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
android:id="#+id/tvproductdesc"
/>
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:id="#+id/imageView"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
/>
</LinearLayout>
My homepage.java contains code which is using AsyncTask to consume REST API and fill arrays of data and send it to customAdapter.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
lv=(ListView) findViewById(R.id.listView);
Bundle emailbundle=getIntent().getExtras();
email=emailbundle.get("email").toString();
initializer();
addingItemstoSpinner();
}
protected void onPostExecute(String result) {
try {
jsonArray = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
len= jsonArray.length();
pdLoading.dismiss();
if (len != 0) {
try {
String [] productIDListArr= new String[len];
String [] productNameListArr= new String[len];
String [] productDescListArr= new String[len];
String [] productImagesArr= new String[len];
String [] productStarsArr= new String[len];
for (int i=0;i<len;i++)
{
objectInArray = jsonArray.getJSONObject(i);
productIDListArr[i]=(objectInArray.getString("productId"));
productNameListArr[i]=(objectInArray.getString("productName"));
productDescListArr[i]=(objectInArray.getString("stars"));
productImagesArr[i]=(objectInArray.getString("productId"));
productStarsArr[i]=(objectInArray.getString("stars")+" out of 5");
if(i==len-1)
{
createdAt=objectInArray.getString("createdAt");
}
}
lv.setAdapter(new CustomAdapter(HomePage.this, productIDListArr,productNameListArr,productDescListArr,productImagesArr,productStarsArr,email));
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Server is down please try again later", Toast.LENGTH_LONG).show();
}
My customAdapter.java is
package com.andapps.azaz.e_recommender;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
/**
* Created by M.Azaz on 30-Mar-17.
*/
public class CustomAdapter extends BaseAdapter {
String [] productIDListArr,productNameListArr,productDescListArr,productImagesArr,productStarsArr;
Context context;
String email;
private static LayoutInflater inflater=null;
public CustomAdapter(HomePage homePage, String[] productIDList, String[] productNameList, String[] productDescList, String[] productImages, String[] productStars,String emailMain) {
// TODO Auto-generated constructor stub
productIDListArr=productIDList;
productNameListArr=productNameList;
productDescListArr=productDescList;
productImagesArr=productImages;
productStarsArr=productStars;
context=homePage;
email=emailMain;
inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return productIDListArr.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return productIDListArr[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tvproductname, tvproductid, tvproductdesc;
ImageView imageView;
RatingBar ratingBar;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.activity_custom_list, null);
holder.tvproductname=(TextView) rowView.findViewById(R.id.tvproductname);
holder.tvproductid=(TextView) rowView.findViewById(R.id.tvproductid);
holder.tvproductdesc=(TextView) rowView.findViewById(R.id.tvproductdesc);
holder.imageView=(ImageView) rowView.findViewById(R.id.imageView);
holder.ratingBar=(RatingBar) rowView.findViewById(R.id.ratingBar);
holder.tvproductname.setText(productNameListArr[position]);
holder.tvproductid.setText(productIDListArr[position]);
holder.tvproductdesc.setText(productDescListArr[position]);
holder.ratingBar.setRating(Integer.parseInt(productStarsArr[position]));
Picasso.with(context).load(context.getString(R.string.imageip) + productImagesArr[position]+".jpg").into(holder.imageView);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+productIDListArr[position], Toast.LENGTH_LONG).show();
Intent intent = new Intent("com.andapps.azaz.e_recommender.RATINGS");
intent.putExtra("tag",productIDListArr[position]);
intent.putExtra("email", email);
context.startActivity(intent);
}
});
return rowView;
}
}
But when I run the code, it actually calls customAdapter.java but right after calling getCount() from customAdapter Its not calling getView and the application terminates.
One more thing... how can I update more items into existing list?
You app may crash in getCount method when productIDListArr is null. So add if condition in your getCount method before returning count.
For example :
public int getCount(){
if(productIDListArr==null){
return 0;
}else{
return productIDListArr.length;
}
}
Tips : Create a class for holding your response data and pass the list of that model class to the adapter and each time when there is any change in your data update that list and call notify method of adapter.
For example :
Class Item{
public String productIDListArr;
public String productNameListArr;
public String productDescListArr;
public String productImagesArr;
public String productStarsArr;
}
ArrayList<Item> items=new ArrayList<Item>();
for (int i=0;i<len;i++)
{
objectInArray = jsonArray.getJSONObject(i);
Item item=new Item();
item.productIDListArr=(objectInArray.getString("productId"));
.......
}
CustomAdapter extend BaseAdapter{
ArrayList<Item> items;
public CustomAdapter(ArrayList<Item> items){
this.items=items;
}
public int getCount(){
return items==null?0:items.size()
}
Related
How i can filter data using textview in Listview , data are from PHP using JSON Parser. I searched already from the net but i don't get their point because they are using array of string while Im using parsed data from php. Thanks for those who will help.
This is the code
productlist.java
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class productlist extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
private EditText et;
int textlength = 0;
private static final String URl = "http://192.168.254.101/productlist.php";
private static final String TAG_POSTS = "message";
private static final String TAG_BRAND = "Brand";
private static final String TAG_CATEGORY = "Category";
private static final String TAG_DESCRIPTION = "Description";
private static final String TAG_CODE = "Code";
private static final String TAG_QUANTITY = "Quantity";
private static final String TAG_UNIT = "Unit";
private static final String TAG_UNITPRICE = "Unitprice";
private JSONArray mComments = null;
//manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productlist);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadComments().execute();
}
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(URl);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
//gets the content of each tag
String brand = c.getString(TAG_BRAND);
String category = c.getString(TAG_CATEGORY);
String description = c.getString(TAG_DESCRIPTION);
String code = c.getString(TAG_CODE);
String quantity = c.getString(TAG_QUANTITY);
String unit = c.getString(TAG_UNIT);
String unitprice = c.getString(TAG_UNITPRICE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_BRAND, brand);
map.put(TAG_CATEGORY, category);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_CODE, code);
map.put(TAG_QUANTITY, quantity);
map.put(TAG_UNIT, unit);
map.put(TAG_UNITPRICE, unitprice);
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[] { TAG_BRAND, TAG_CATEGORY,
TAG_DESCRIPTION, TAG_CODE, TAG_QUANTITY, TAG_UNIT, TAG_UNITPRICE}, new int[]{ R.id.Brand, R.id.Category,
R.id.Description, R.id.Code, R.id.Quantity, R.id.Unit, R.id.Price });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(productlist.this);
pDialog.setMessage("Loading Products...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
productlist.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff" >
<LinearLayout
android:id="#+id/top_layover"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/EditText01"
android:layout_gravity="center_horizontal"
android:hint="Search.." />
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/bottom_layover"
android:layout_below="#+id/top_layover"
android:background="#fff"
android:divider="#android:color/transparent"
android:scrollbars="none" />
<LinearLayout
android:id="#+id/bottom_layover"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:orientation="horizontal"
android:weightSum="2" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
singlepost.xml
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#f0f0f0"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="5dp"
android:background="#ffffff">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:text="Brand: ">
</TextView>
<TextView
android:id="#+id/Brand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:text="Category: " >
</TextView>
<TextView
android:id="#+id/Category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:text="Description: " >
</TextView>
<TextView
android:id="#+id/Description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:text="Code: " >
</TextView>
<TextView
android:id="#+id/Code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:text="Quantity: ">
</TextView>
<TextView
android:id="#+id/Quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:text="Unit: " >
</TextView>
<TextView
android:id="#+id/Unit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:text="Price: " >
</TextView>
<TextView
android:id="#+id/Price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" >
</TextView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
produclist.php
<?php
try{
$handler= new PDO('mysql:host=localhost;dbname=account','root','');
$handler->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(Exception $e){
echo $e->getMessage();
die();
}
$query =$handler->query( "Select * from tblproducts");
$records= array();
$records =$query->fetchAll(PDO::FETCH_ASSOC);
$json["message"]=$records;
echo json_encode($json);
?>
Please use below code which you will get idea and customize as your need
class CustomAdpter extends BaseAdapter implements Filterable{
LayoutInflater inflater = null;
Activity activity;
ItemFilter itemfilter = new ItemFilter();
public CustomAdpter(Activity a) {
this.activity = a;
inflater = LayoutInflater.from(a);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listBillingSearch.size();
//return 3;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listBillingSearch.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View view1, ViewGroup parent) {
ViewHolder holder;
if (view1 == null) {
view1 = inflater.inflate(R.layout.adpter_billing, null);
holder = new ViewHolder();
holder.txtBillingListCompanyName = (TextView) view1.findViewById(R.id.txtBillingListCompanyName);
holder.txtBillingListInvoice = (TextView) view1.findViewById(R.id.txtBillingListInvoice);
holder.txtBillingListStartDate = (TextView) view1.findViewById(R.id.txtBillingListStartDate);
holder.txtBillingListEndDate = (TextView) view1.findViewById(R.id.txtBillingListEndDate);
holder.txtBillingListVoiceCalls = (TextView) view1.findViewById(R.id.txtBillingListVoiceCalls);
holder.txtBillingListSMS = (TextView) view1.findViewById(R.id.txtBillingListSMS);
holder.txtBillingListDataPlan = (TextView) view1.findViewById(R.id.txtBillingListDataPlan);
view1.setTag(holder);
}else{
holder = (ViewHolder) view1.getTag();
}
holder.txtBillingListCompanyName.setText(listBillingSearch.get(position).getStrCompanyName());
holder.txtBillingListInvoice.setText(listBillingSearch.get(position).getStrInvoice());
holder.txtBillingListStartDate.setText(listBillingSearch.get(position).getStrStartDate());
holder.txtBillingListEndDate.setText(listBillingSearch.get(position).getStrEndDate());
holder.txtBillingListVoiceCalls.setText(listBillingSearch.get(position).getStrVoiceCall());
holder.txtBillingListSMS.setText(listBillingSearch.get(position).getStrSMS());
holder.txtBillingListDataPlan.setText(" "+listBillingSearch.get(position).getStrDataPlan());
return view1;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return itemfilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<Billing> list = listBilling;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
ArrayList<Billing> filterdata = new ArrayList<Billing>();
if(constraint.equals(null) || constraint.equals("")){
//filterdata = listBilling;
results.values = listBilling;
results.count = listBilling.size();
}else{
// listBillingSearch.clear();
for (int i = 0; i < count; i++) {
filterableString = list.get(i).getStrCompanyName();
if (filterableString.toLowerCase().startsWith(filterString)) {
filterdata.add(listBilling.get(i));
}
}
results.values = filterdata;
results.count = filterdata.size();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
//if(results.count > 0)
listBillingSearch = (ArrayList<Billing>) results.values;
notifyDataSetChanged();
}
}
}
public static class ViewHolder {
TextView txtBillingListCompanyName;
TextView txtBillingListInvoice ;
TextView txtBillingListStartDate;
TextView txtBillingListEndDate;
TextView txtBillingListVoiceCalls;
TextView txtBillingListSMS;
TextView txtBillingListDataPlan;
}
I hope it will help you.
Let me know if you find any issue.
i have an android application that retrieve data from sqlite database and display these data in a listView that extend a BaseAdapter.
in this app i have images in the drawable folder and i have in the sqlite a field that contain name of these images.
my question is how to retrieve these data and display it in a listView ??
i read this tutorial :(http://www.androidhub4you.com/2012/09/hello-friends-today-i-am-going-to-share.html).
my question is there any other way to do this ??
i will appreciate any help .
row_list_match_schedulle.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Group"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/txtDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Date"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textName1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignParentLeft="true"
android:text="name1" />
<TextView
android:id="#+id/textName2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView2"
android:layout_alignParentRight="true"
android:text="Name2" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textLocation"
android:layout_toRightOf="#+id/textName1"
android:adjustViewBounds="true"
android:maxHeight="40dp"
android:maxWidth="40dp"
android:scaleType="fitCenter"
android:src="#drawable/algeria_flag" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imageView1"
android:layout_toLeftOf="#+id/textName2"
android:adjustViewBounds="true"
android:maxHeight="40dp"
android:maxWidth="40dp"
android:scaleType="fitCenter"
android:src="#drawable/algeria_flag" />
<TextView
android:id="#+id/textLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textGroup"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="Location" />
</RelativeLayout>
ItemDetails.java
package com.devleb.expandablelistdemo3;
public class ItemDetails {
String stad_name;
String team1;
String team2;
String match_date;
String flags1;
String flags2;
String group;
public String getStad_name() {
return stad_name;
}
public void setStad_name(String stad_name) {
this.stad_name = stad_name;
}
public String getTeam1() {
return team1;
}
public void setTeam1(String team1) {
this.team1 = team1;
}
public String getTeam2() {
return team2;
}
public void setTeam2(String team2) {
this.team2 = team2;
}
public String getMatch_date() {
return match_date;
}
public void setMatch_date(String match_date) {
this.match_date = match_date;
}
public String getFlags1() {
return flags1;
}
public void setFlags1(String flags1) {
this.flags1 = flags1;
}
public String getFlags2() {
return flags2;
}
public void setFlags2(String flags2) {
this.flags2 = flags2;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
}
this is what i wrote until now in the BaseAdapter
CustomAdapterMatchSchedule.java
package com.devleb.expandablelistdemo3;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class CustomAdapterMatchSchedule extends BaseAdapter {
LayoutInflater layoutInflater;
ArrayList<ItemDetails> itemdetailList;
Context context;
public CustomAdapterMatchSchedule(Context c, ArrayList<ItemDetails> listOfItem){
this.context = c;
itemdetailList = listOfItem;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemdetailList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemdetailList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
ItemDetails itemListDetails = itemdetailList.get(position);
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_list_match_schedule, null);
}
//Stad_name
TextView txtStadName = (TextView)convertView.findViewById(R.id.textLocation);
txtStadName.setText(itemListDetails.getStad_name());
//team1
TextView txtTeam1 = (TextView)convertView.findViewById(R.id.textName1);
txtTeam1.setText(itemListDetails.getTeam1());
//team2
TextView txtTeam2 = (TextView)convertView.findViewById(R.id.textName2);
txtTeam2.setText(itemListDetails.getTeam2());
//flag1
TextView txtflag1 = (TextView)convertView.findViewById(R.id.imageView1);
txtflag1.setText(itemListDetails.getTeam1());
//flag2
return null;
}
}
This is the most appropriate way,especially because each listview row contains a lot of items.If you want to get the items on a clicked row it becomes a walk in the pack,less than 10 lines of code.As far as am concerned,its the best way. Don't get worried,its also what i use.
In my application, I have grid view and I wrote a listener to get position of clicked item in the grid view. I tried many ways to solve it but it is noting working.I'm looking solutions or help I have checked everything but i'm not able to clear it.I don't know where I have done mistake. anyone help me out with is.
rowitems xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:background="#drawable/customborder"
android:gravity="center_vertical"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
<ImageView
android:id="#+id/product_img"
android:layout_width="350dp"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:src="#drawable/ic_launcher"
android:focusable="false"
android:focusableInTouchMode="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_weight="0.5"
android:background="#D7D7D7" >
<TextView
android:id="#+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="37dp"
android:text="#string/pname"
android:textAppearance="?android:attr/textAppearanceMedium"
android:focusable="false"
android:focusableInTouchMode="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="75dp" >
<Button
android:id="#+id/product_decribe_cart"
style="?android:attr/buttonStyleSmall"
android:layout_width="75dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="46dp"
android:background="#D41A37"
android:text="#string/cart"
android:textColor="#android:color/white"
android:textSize="8dp"
android:focusable="false"
android:focusableInTouchMode="false"/>
<TextView
android:id="#+id/product_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="40dp"
android:text="#string/rate"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#D41A37"
android:focusable="false"
android:focusableInTouchMode="false"/>
</RelativeLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="262dp"
android:layout_height="113dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="10dp"
android:background="#drawable/customborder" >
<TextView
android:id="#+id/product_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:text="Product details"
android:textAppearance="?android:attr/textAppearanceMedium"
android:focusable="false"
android:focusableInTouchMode="false"/>
</RelativeLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ProductActivity extends Activity
{
JSONArray results;
JSONObject jobj;
CustomProdAdapter adapter1;
ArrayList<String> a1,a2,a3,a4;
ArrayList<String> pname=new ArrayList<String>();
ArrayList<String> productdescription=new ArrayList<String>();
ArrayList<String> pimage=new ArrayList<String>();
ArrayList<String> pprice=new ArrayList<String>();
Button add;
String pid;
GridView gView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.product_activity);
a1=new ArrayList<String>();
a2=new ArrayList<String>();
a3=new ArrayList<String>();
a4=new ArrayList<String>();
Intent in=getIntent();
pid=in.getStringExtra("Dialoog");
System.out.println("productid"+pid);
gView = (GridView)findViewById(R.id.pa_grid);
/* gView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
System.out.println("inside listener");
}
});*/
new Producttask().execute();
}
private class Producttask extends AsyncTask<String, String, JSONObject>
{
private ProgressDialog pDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(ProductActivity.this);
pDialog.setMessage("Loading Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args)
{
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("my link");
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
System.out.println("---------------return product list json------------"+json);
pDialog.dismiss();
try
{
jobj=json.getJSONObject("response");
// Getting Array of Contacts
results = jobj.getJSONArray("obejects");
System.out.println("In product Activity after JSON");
// looping through All Contacts
for(int i = 0; i < results.length(); i++)
{
JSONObject c = results.getJSONObject(i);
pname.add(c.getString("product_name"));
pimage.add(c.getString("product_image"));
pprice.add(c.getString("product_price"));
productdescription.add(c.getString("Description"));
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter1 = new CustomProdAdapter(getApplicationContext(), R.layout.product_describe, pname, pimage,productdescription,pprice);
gView.setAdapter(adapter1);
gView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
System.out.println("outside on click"+position);
}
});
/*gv=(GridView)findViewById(R.id.product_decribe_cart);
gv.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(ProductActivity.this,product_details.class);
startActivity(i);
}
});
*/ }
}
}
Grid view listner set in oncreate method
new Producttask().execute();
gView = (GridView)findViewById(R.id.pa_grid);
gView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
System.out.println("outside on click"+position);
}
});
Or set you click listener on row , like that
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
View row=convertView;
ViewHolder vh;
if(row==null)
{
row=inflater.inflate(R.layout.custom_product_activity, parent, false);
vh=new ViewHolder();
vh.pname=(TextView)row.findViewById(R.id.product_name);
vh.image1=(ImageView) row.findViewById(R.id.imageView1);
row.setTag(vh);
}
else
{
vh = (ViewHolder) row.getTag();
row=convertView;
}
vh.pname.setText(c_pname.get(position));
iloader.DisplayImage(c_pimage.get(position), vh.image1);
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
System.out.println("outside on click"+"position");
}
});
return row;
}
I have a model class. Now from my activity i want to set the values in model class & show them in gridview using my custom adapter. After that i need to store the object in a variable(class type) from gridview's onItemClick. I have done the below codes. But its not working. Where did i go wrong?
activity_country.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".CountryActivity" >
<TextView
android:id="#+id/nTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="21dp"
android:layout_marginTop="26dp"
android:text="Name" />
<TextView
android:id="#+id/aTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/nTextView"
android:layout_below="#+id/nTextView"
android:layout_marginTop="24dp"
android:text="About" />
<EditText
android:id="#+id/CountryNameEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/nTextView"
android:layout_alignBottom="#+id/nTextView"
android:layout_marginLeft="48dp"
android:layout_toRightOf="#+id/nTextView"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/CountryAboutEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/CountryNameEditText"
android:layout_alignTop="#+id/aTextView"
android:ems="10" />
<Button
android:id="#+id/saveCountryButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/CountryAboutEditText"
android:layout_below="#+id/CountryAboutEditText"
android:layout_marginLeft="16dp"
android:layout_marginTop="22dp"
android:text="Save"
android:onClick="saveCountry"
/>
<GridView
android:id="#+id/countryGridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/saveCountryButton"
android:layout_centerHorizontal="true"
android:numColumns="2">
</GridView>
</RelativeLayout>
CountryActivity.java
public class CountryActivity extends Activity
{
ArrayList<Country> countries = new ArrayList<Country>();
Country aCountry;
EditText CountryNameTxtBox;
EditText CountryAboutTxtBox;
GridView countrygGridView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country);
// Show the Up button in the action bar.
setupActionBar();
CountryNameTxtBox = (EditText)findViewById(R.id.CountryNameEditText);
CountryAboutTxtBox = (EditText)findViewById(R.id.CountryAboutEditText);
countrygGridView = (GridView)findViewById(R.id.countryGridView);
}
public void saveCountry(View view)
{
String txtName = CountryNameTxtBox.getText().toString();
String txtAbout = CountryAboutTxtBox.getText().toString();
showGrid();
}
public void showGrid()
{
/*
ArrayAdapter<Country> adapter = new ArrayAdapter<Country>(this,android.R.layout.simple_list_item_1, countries);
countrygGridView.setAdapter(adapter);
*/
countrygGridView.setAdapter(new myAdapter(this,countries));
countrygGridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View v,int position, long id)
{
for(Country mCountry: countries)
{
if(countries.contains(aCountry))
{
Toast.makeText(CountryActivity.this,countries.get(position).getName(), 2000).show();
}
}
}
});
}
countrygrid.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/label1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:layout_marginTop="15sp"
android:textSize="15sp" >
</TextView>
<TextView
android:id="#+id/label2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:layout_marginTop="15sp"
android:textSize="15sp" >
</TextView>
</LinearLayout>
myAdapter.java
public class myAdapter extends BaseAdapter
{
Context mycontext;
ArrayList<Country> countries;
public myAdapter(Context c, ArrayList<Country> obj)
{
this.mycontext=c;
this.countries = obj;
}
public int getCount() {
// TODO Auto-generated method stub
return countries.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return countries.get(arg0);
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertview, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if(convertview==null)
{
gridView =new View(mycontext);
gridView =inflater.inflate(R.layout.countrygrid, null);
TextView txtvw1 = (TextView) gridView.findViewById(R.id.label1);
txtvw1.setText(countries.get(position).getName());
TextView txtvw2 = (TextView) gridView.findViewById(R.id.label2);
txtvw2.setText(countries.get(position).getAbout());
}
else
{
gridView = (View) convertview;
}
return gridView;
}
}
*Its showing error in countryActivity.java- when i am trying to set the adapter inside showGrid() *
countrygGridView.setAdapter(new myAdapter(this,countries));
public class myAdapter
{
does not extend anything
It should be
public class myAdapter extends BaseAdapter //orArrayAdapter
{
If you still have a problem post the stacktrace for further help
Hi onListItemClick for listview is not working. Here i am fetching datas from SQLite using AsyncTask and displaying it in a list view. And i wants to do some actions when a list in a listview has clicked. But the click is not happening. I had tried a lot for this. Please help me.
Here is my code
package com.applexus.app.mobilesalesorder;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import com.applexus.app.library.sql.SqlConnector;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class SoldToPartiesList extends ListActivity {
private ArrayList<String> data = new ArrayList<String>();
private ArrayList<String> idk = new ArrayList<String>();
private ArrayList<String> name1 = new ArrayList<String>();
private ArrayList<String> inco1 = new ArrayList<String>();
private ArrayList<String> email = new ArrayList<String>();
private ArrayList<String> tel = new ArrayList<String>();
private ArrayList<String> vwerk = new ArrayList<String>();
private SharedPreferences prefs;
private String prefNamesalesorgid = "salesorgid";
private String prefNamedistchnlid = "distchnlid";
private String prefNamedivid = "divid";
private String prefName = "mso";
private TextView titlename;
private static class ViewHolder {
TextView tvlist;
TextView tvlistsmall;
}
private class EfficientAdapter extends BaseAdapter {
private Context context;
LayoutInflater inflater;
public EfficientAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
final int place = position;
if (convertView == null) {
convertView = inflater.inflate(R.layout.listso, null);
holder = new ViewHolder();
holder.tvlist = (TextView) convertView
.findViewById(R.id.textViewlist);
holder.tvlistsmall = (TextView) convertView
.findViewById(R.id.textView1);
convertView.setTag(holder);
//
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvlist.setText(idk.get(position));
holder.tvlistsmall.setText(data.get(position));
return convertView;
}
}
Map<String, String> map = new TreeMap<String, String>();
SqlConnector con;
String salorg;
String distch;
String division;
Context co = this;
Boolean searchable=false;
TextView tvmc;
TextView tvmn;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.materiallist);
titlename = (TextView) findViewById(R.id.textViewtitle);
titlename.setText(R.string.soldtoparties);
tvmc=(TextView)findViewById(R.id.textViewmc);
tvmn=(TextView)findViewById(R.id.textViewmn);
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
salorg = (prefs.getString(prefNamesalesorgid, ""));
distch = (prefs.getString(prefNamedistchnlid, ""));
division=(prefs.getString(prefNamedivid, ""));
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { null });
// ListView lv=(ListView)findViewById(android.R.id.list);
// lv.setOnItemSelectedListener(new )
}
EditText es;
LinearLayout ls;
LinearLayout mc;
LinearLayout mn;
Boolean searchFlag = false;
String search;
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
es = (EditText) findViewById(R.id.editTextSearch);
ls = (LinearLayout) findViewById(R.id.linearLayoutsearch);
}
private class DownloadWebPageTasksearch extends
AsyncTask<String, Void, String> {
Cursor c;
ProgressBar pb;
#Override
protected String doInBackground(String... urls) {
con = new SqlConnector(co);
try {
if (searchFlag) {
c = con.select("select Kunnr,Name,Name1,Inco1,Vwerk,SmtpAddr,Telf1 from tb_soldtoparties where salesorg='"
+ salorg + "' and channel='" + distch + "' and Name like '%"+search+"%' and division='"+division+"';");
} else {
c = con.select("select Kunnr,Name,Name1,Inco1,Vwerk,SmtpAddr,Telf1 from tb_soldtoparties where salesorg='"
+ salorg + "' and channel='" + distch + "' and Kunnr like '%"+search+"%' and division='"+division+"';");
}
} catch (Exception e) {
e.printStackTrace();
}
int in = c.getCount();
c.moveToFirst();
for (int i = 0; i < in; i++) {
idk.add(c.getString(0));
data.add(c.getString(1));
name1.add(c.getString(2));
inco1.add(c.getString(3));
vwerk.add(c.getString(4));
email.add(c.getString(5));
tel.add(c.getString(6));
c.moveToNext();
}
return null;
}
#Override
protected void onPostExecute(String result) {
setListAdapter(new EfficientAdapter(SoldToPartiesList.this));
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
searchable=true;
con.close();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
idk.clear();
data.clear();
name1.clear();
inco1.clear();
vwerk.clear();
email.clear();
tel.clear();
setListAdapter(new EfficientAdapter(SoldToPartiesList.this));
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.VISIBLE);
searchable=false;
}
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
Cursor c;
ProgressBar pb;
#Override
protected String doInBackground(String... urls) {
con = new SqlConnector(co);
try {
c = con.select("select Kunnr,Name,Name1,Inco1,Vwerk,SmtpAddr,Telf1 from tb_soldtoparties where salesorg='"
+ salorg + "' and channel='" + distch + "' and division='"+division+"';");
} catch (Exception e) {
e.printStackTrace();
}
int in = c.getCount();
c.moveToFirst();
Log.d("size", "" + in + "");
for (int i = 0; i < in; i++) {
idk.add(c.getString(0));
data.add(c.getString(1));
name1.add(c.getString(2));
inco1.add(c.getString(3));
vwerk.add(c.getString(4));
email.add(c.getString(5));
tel.add(c.getString(6));
c.moveToNext();
}
return null;
}
#Override
protected void onPostExecute(String result) {
setListAdapter(new EfficientAdapter(SoldToPartiesList.this));
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
searchable=true;
con.close();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
idk.clear();
data.clear();
name1.clear();
inco1.clear();
vwerk.clear();
email.clear();
tel.clear();
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.VISIBLE);
searchable=false;
}
}
// class ClickOnList implements OnItemClickListener
// {
// #Override
// public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
// long arg3) {
// Log.d("ListView", "Position"+arg2);
//
// }
//
// }
// public OnItemClickListener theListListener = new OnItemClickListener() {
//
// public void onItemClick(android.widget.AdapterView<?> parent, View v, int position, long id) {
// Log.d("position",position+"");
// } };
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
int place=position;
Log.d("position",position+"");
}
}
And Layout code is materiallist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/bluebg"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/bar1"
android:gravity="center_vertical"
android:minHeight="50dp"
android:orientation="horizontal" >
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_margin="5dp"
android:layout_weight="1"
android:gravity="center_vertical|left" >
<TextView
android:id="#+id/textViewtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:shadowColor="#000000"
android:shadowDx="1"
android:shadowDy="1"
android:shadowRadius="1.5"
android:text="#string/materials"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_margin="5dp"
android:gravity="center" >
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/linearLayout4"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center" >
<EditText
android:id="#+id/editTextSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:hint="#string/search"
android:imeOptions="actionDone"
android:inputType="textUri" >
</EditText>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayoutsearch"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center" android:clickable="true">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:src="#drawable/search" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout6"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout7"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/listbg2" >
<LinearLayout
android:id="#+id/linearLayoutmc"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/lbg1"
android:gravity="center" >
<TextView
android:id="#+id/textViewmc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Code"
android:textColor="#color/black" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayoutmn"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/lbg2"
android:gravity="center" >
<TextView
android:id="#+id/textViewmn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Name"
android:textColor="#color/black" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout10"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#color/offwhite" >
</ListView>
</LinearLayout>
</LinearLayout>
And listso3.xml is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/lbg"
android:orientation="vertical"
>
<TextView
android:id="#+id/textViewNamelist3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/black"
android:focusable="false"/>
<TextView
android:id="#+id/textViewKunn2list3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/black"
android:focusable="false"/>
</LinearLayout>
Add below code to your TextView in the XML
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
and try again.
Another simple solution: add android:descendantFocusability="blocksDescendants" to the root viewgroup.
You should add android:focusable="false" for ListView row items to make ListView Clikable. Because the views in the row of ListView gain the focus so ListView is not focusable. So, in your case you can add android:focusable="false" to the TextViews of your ListView row.
I had the same symptoms, and it drove me crazy for a while. Adding android:focusable="false" for the list items as suggested above fixed the problem for me.
But the real issue was that I had set android:textIsSelectable="true" for my list items (in response to a Warning generated by Eclipse); setting android:textIsSelectable="false" fixed the problem for me, and I did not need the android:focusable="false" option at all.
The workaround I found avoid the
AdapterView.OnItemClickListener mMessageClickedHandler=new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
};
on the ListView, but exploit the Adapter constructor that takes a Context as parameter:
myCustomAdapter=new MyCustomAdapter(ActivityName.this,...)
Passing ActivityName.this is possible to cast the Context in the adapter's class as ActivityName in a safe way and use its methods working like callbacks:
((ActivityName)context).activityMethod()
Given that the getView() method of the Adapter class has a position parameter, is possible to pass this value to the activityMethod(int position) in order to know which list item has been pressed into the Activity where the ListView is.
Another solution.
if you have many child-control,and its to trouble to add android:focusable="false" to every child-control,you can add android:descendantFocusability="blocksDescendants" to its parent-control.try it.
I struggled with this for a while - none of the provided solutions worked for me. In the end I found that having a call to getListView() in my onViewCreated() method did the trick, although I have no idea why. This is for a Fragment rather than an Activity; not sure if this makes any difference.
public class NewsListFragment extends ListFragment {
private ListView listView;
...
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
newsListView = getListView();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// this now works as expected
}
}
I was also struggling with this issue and none of the suggested solutions worked. My problem was that I did an override for onViewCreated but didn't call super.onViewCreated(view, savedInstanceState);. Hopefully this will help someone else so they don't spend hours trying to figure out what's going on.
I struggled as I by mistake put android:inputType="textCapWords" with the textbox after removing it it is fixed
Only the line below worked for me:
android:descendantFocusability="blocksDescendants"
The whole list_view_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<!--android:focusableInTouchMode="false"-->
<!--android:focusable="false"-->
<!--android:clickable="false"-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:descendantFocusability="blocksDescendants"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/checkBox_list_view_checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/checkBox_list_view_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The above is to be used in getView like:
convertView=LayoutInflater.from(getContext())
.inflate(R.layout.list_view_item, parent, false);
`