Listview doesnot scroll in tabhost - android

In my app i have tabhost in which i am displaying list view.I cant scroll my listview and when i try to scroll color of listview changes but doesnot scroll.Here are pictures
when i try to scroll its color changes
My SearchDictionaryActivity.java is
public class SearchDictionaryActivity extends Activity{
Intent intent;
// Progress Dia//Log
private ProgressDialog pDialog;
DataHolder obj;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
private boolean enablePopup = true;
// Listview Adapter
ArrayAdapter<String> adapter;
//ArrayList<String> categories=new ArrayList<String>();
// catgories JSON url
private static String url_all_products;
// JSON Node names It should be same on srver(encodeing) and client(decoding)
private static final String TAG_SUCCESS = "success";
private static final String TAG_products = "Products";
private static final String TAG_Image = "Image";
private static final String TAG_NAME = "name";
// category JSONArray
JSONArray category = null;
// flag for Internet connection status
Boolean isInternetPresent = false;
EditText edittext;
ListView listview;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<Bitmap> image_sort = new ArrayList<Bitmap>();
String ITEMTITLE ="HasMapValue";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_dictionary);
url_all_products=getString(R.string.url_ip);
url_all_products=url_all_products+"get_list_of_name_of_products.php";
new LoadCategories().execute();
edittext = (EditText) findViewById(R.id.EditText01);
listview = (ListView) findViewById(R.id.ListView01);
}
/**
* Background Async Task to Load all catgories by making HTTP Request
* */
class LoadCategories extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
Bitmap decodedByte;
//ArrayList<HashMap<String, Object>> productsList=new ArrayList<HashMap<String,Object>>();
String[] text = new String[0];
Bitmap[] image = new Bitmap[0];
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchDictionaryActivity.this);
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting catgories JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Categorys
category = json.getJSONArray(TAG_products);
//Log.i("category ", category.toString());
//Log.i("Lengt Category"," " +category.length());
// looping through All Categories
for (int i = 0; i < category.length(); i++) {
JSONObject c = category.getJSONObject(i);
//Log.i("JSONObject ", c.toString());
// Storing each json item in variable
String name = c.getString(TAG_NAME);
String ProductImage = c.getString(TAG_Image);
//Log.i("StrineName ", name);
byte[] decodedString = Base64.decode(ProductImage, Base64.DEFAULT);
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
//HashMap<String, Object> map = new HashMap<String, Object>();
text=reallocation(text);
image=reallocation_BitMap(image);
text[i]=name.toString().toLowerCase();
image[i]=decodedByte;
}
} else {
// no products found
// Launch Add New product Activity
/*Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
//
if (pDialog.isShowing()) {
pDialog.dismiss();
// progressDialog.setCancelable(true);
}
edittext.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
int textlength = edittext.getText().length();
text_sort.clear();
image_sort.clear();
if (s.length() >= 1 && enablePopup) {
//Log.i("Length of SorttEX111"," "+ text_sort.size());
for( int i=0;i<text.length;i++)
{
if((s.toString().toLowerCase()).equalsIgnoreCase(((String) text[i].subSequence(0, textlength))))
{
text_sort.add(text[i]);
image_sort.add(image[i]);
}
}
}
listview.setAdapter(new MyCustomAdapter(text_sort, image_sort));
enablePopup = true;
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = this.getMenuInflater();
menuInflater.inflate(R.menu.item_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (((String) item.getTitle()).compareTo("About") == 0) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class DataHolder
{
String ProductName;
Bitmap Productimage;
public void setData(String ProductName,Bitmap image)
{
this.ProductName=ProductName;
this.Productimage=image;
}
public String GetProductName()
{return ProductName;}
public Bitmap Getimage()
{return Productimage;}
}
public class DataHolder1
{
String ProductName;
Bitmap Productimage;
public void setData1(String ProductName,Bitmap image)
{
this.ProductName=ProductName;
this.Productimage=image;
}
public String GetProductName1()
{return ProductName;}
public Bitmap Getimage1()
{return Productimage;}
}
class MyCustomAdapter extends BaseAdapter
{
String[] data_text;
Bitmap[] data_image;
MyCustomAdapter()
{
data_text=null;
data_image=null;
}
MyCustomAdapter(String[] text, Bitmap[] image)
{
data_text = text;
data_image = image;
}
MyCustomAdapter(ArrayList<String> text, ArrayList<Bitmap> image)
{
data_text = new String[text.size()];
data_image = new Bitmap[image.size()];
for(int i=0;i<text.size();i++)
{
data_text[i] = text.get(i);
data_image[i] = image.get(i);
}
}
public int getCount()
{
return data_text.length;
}
public String getItem(int position)
{
return null;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.search_dictionary_item, null);
}
TextView textview = (TextView) convertView.findViewById(R.id.TextView01);
ImageView imageview = (ImageView) convertView.findViewById(R.id.ImageView01);
textview.setText(data_text[position]);
imageview.setImageBitmap(data_image[position]);
return convertView;
}
}
public static String[] reallocation(String s[])
{
String t[]=new String[s.length+1];
for(int i=0; i<s.length;i++)
{
t[i]=s[i];
}
return t;
}
public static Bitmap[] reallocation_BitMap(Bitmap s[])
{
Bitmap t[]=new Bitmap[s.length+1];
for(int i=0; i<s.length;i++)
{
t[i]=s[i];
}
return t;
}
}
and search_dictionary.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:orientation="vertical"
android:background="#color/green">
<EditText
android:id="#+id/EditText01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search" >
</EditText>
<ListView
android:id="#+id/ListView01"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="50">
</ListView>

I found the answer by placing android:cacheColorHint="#00000000" in xml
<ListView
android:id="#+id/List_Of_Categories"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#00000000"
android:divider="#android:color/transparent"
android:dividerHeight="1dp"
/>

Related

customAdapter not working properly with asynchronous image download

Hey guys i am trying to create a custom listview with text and images where images are coming from a url. i am trying to display them asynchronously with my list items. but as i scroll down the list, the image in list items changes and wrong images are displayed in listitems. Below is my code snippet:
CustomList.java,
it is implimenting my base adapter
public class CustomList extends BaseAdapter {
//private ArrayList listData;
private LayoutInflater layoutInflater;
private ArrayList<ListItem> listData;
public CustomList(Context context,ArrayList<ListItem> listData)
{
//Toast.makeText(History.this,"hey",Toast.LENGTH_LONG).show();
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
Log.e("mysize",String.valueOf(listData.size()));
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView,ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
convertView = layoutInflater.inflate(R.layout.history_row,null);
holder = new ViewHolder();
holder.so = (TextView)convertView.findViewById(R.id.SO);
holder.name = (TextView)convertView.findViewById(R.id.Name);
holder.process = (ImageView)convertView.findViewById(R.id.Process);
holder.cloth = (ImageView)convertView.findViewById(R.id.Cloth);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
ListItem data = (ListItem)listData.get(position);
holder.so.setText(data.getSo());
if(data.getProcess().equals("0"))
{
holder.process.setImageResource(R.drawable.tick);
}
else
holder.process.setImageResource(android.R.drawable.ic_delete);
if(holder.cloth !=null)
{
holder.name.setText(data.getName());
Log.e("urlsss",data.getUrl()+ data.getName());
new ImageDownload(holder.cloth).execute(data.getUrl());
}
return convertView;
}
static class ViewHolder
{
TextView so;
TextView name;
ImageView process;
ImageView cloth;
}
}
ImageDownload.class for downloading images
public class ImageDownload extends AsyncTask<String,Void,Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownload(ImageView imageView)
{
imageViewReference = new WeakReference<ImageView>(imageView);
}
protected Bitmap doInBackground(String... params)
{
RequestHandler rh = new RequestHandler();
return rh.downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = imageView.getContext().getResources().getDrawable(android.R.drawable.star_on);
imageView.setImageDrawable(placeholder);
}
}
}
}
}
ListItem.java that is producing my data for each row in listView
public class ListItem {
private String so,name,process,imgUrl;
public void setSo(String so)
{
this.so = so;
}
public void setName(String name)
{
this.name = name;
}
public void setProcess(String process)
{
this.process = process;
}
public void setUrl(String url)
{
this.imgUrl = url;
}
public String getSo()
{
return so;
}
public String getName()
{
return name;
}
public String getProcess()
{
return process;
}
public String getUrl()
{
return imgUrl; }
}
This is my main activity where custom-adapter is called
public class History extends AppCompatActivity {
//url to fetch data from
public static final String URL_HISTORY = "http://192.168.1.233/vendor/history.php";
//Json tags
public static final String TAG_JSON_ARRAY="result";
public static final String TAG_SO = "SO";
public static final String TAG_NAME = "CustomerName";
public static final String TAG_DESC = "ClothDescription";
public static final String TAG_DATE = "DeliveryDate";
public static final String TAG_PRODUCT_TYPE = "ProductType";
public static final String TAG_PRODUCT_DESC = "ProductDescription";
public static final String TAG_IMAGE_URL = "ImageUrl";
public static final String TAG_PROCESS = "Process";
HashMap<String,String> data = new HashMap<>();
ArrayList<ListItem> detail_list;
ListView listView;
//key to put in hashmap
public static final String VENDOR_NAME = "Username";
//to store fetched data
String[] so;
String[] customerName;
String[] clothesDesc;
String[] delivDate;
String[] prodType;
String[] prodDesc;
String[] imgUrl;
String[] process;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
listView =(ListView)findViewById(R.id.listView);
detail_list = new ArrayList<ListItem>();
//to get vendorname
SharedPreferences sharedPref = getSharedPreferences("vendorInfo", Context.MODE_PRIVATE);
String vendor_name =sharedPref.getString("username", "");
data.put(VENDOR_NAME, vendor_name);
fetchHistory();
}
public void fetchHistory()
{
class FetchHistory extends AsyncTask<Void,Void,String>
{
ProgressDialog loading;
protected void onPreExecute()
{
super.onPreExecute();
loading = ProgressDialog.show(History.this,"Fetching...","Wait",false,false);
}
protected String doInBackground(Void...params)
{
RequestHandler rh = new RequestHandler();
String result = rh.sendPostRequest(URL_HISTORY, data);
return result;
}
protected void onPostExecute(String s)
{
super.onPostExecute(s);
loading.dismiss();
Log.e("myjson",s);
showHistory(s);
}
}
FetchHistory fh = new FetchHistory();
fh.execute();
}
public void showHistory(String json)
{
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(TAG_JSON_ARRAY);
int length = result.length();
so = new String[length];
customerName = new String[length];
clothesDesc = new String[length];
delivDate = new String[length];
prodType = new String[length];
prodDesc = new String[length];
imgUrl = new String[length];
process = new String[length];
for (int i = 0; i < result.length(); i++) {
JSONObject c = result.getJSONObject(i);
so[i] = c.getString(TAG_SO);
customerName[i] = c.getString(TAG_NAME);
clothesDesc[i] = c.getString(TAG_DESC);
delivDate[i] = c.getString(TAG_DATE);
prodType[i] = c.getString(TAG_PRODUCT_TYPE);
prodDesc[i] = c.getString(TAG_PRODUCT_DESC);
imgUrl[i] = c.getString(TAG_IMAGE_URL);
process[i] = c.getString(TAG_PROCESS);
}
}
catch(JSONException e)
{
Log.e("myexception",e.toString());
}
for(int i =0;i<customerName.length;i++)
{
//storing all value in hashmap
ListItem values = new ListItem();
values.setSo(so[i]);
values.setName(customerName[i]);
values.setUrl(imgUrl[i]);
Log.e("myurl", imgUrl[i]);
values.setProcess(process[i]);
detail_list.add(values);
}
Toast.makeText(this,"hey",Toast.LENGTH_LONG).show();
Log.e("hey", "hey00");
CustomList customList = new CustomList(this,detail_list);
listView.setAdapter(customList);
Toast.makeText(this,"you",Toast.LENGTH_LONG).show();
Log.e("you", "you00");
}
}
My layout file for each row is
<?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:orientation="vertical"
android:id="#+id/linear">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/SO"
android:layout_marginRight="10dp"
android:layout_weight="2" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/Name"
android:layout_marginRight="10dp"
android:layout_weight="2" />
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/Process"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/Cloth"
android:layout_weight="1"
android:scaleType="fitXY" />
</LinearLayout>
</LinearLayout>
This is a common mistake. Your listView recycles views, so instead of creating views for the 100 items in your listView, it just creates enough to fill up the screen.
As you scroll down, that ImageView that was used for position #1, is now the same ImageView being used for position #11, and #21, and so on...
The fix require tracking what positions are currently being displayed to the user, and only setting images for those positions, and clearing the associated imageview (or cancelling the pending download) when it falls off the screen.
You can figure out when your imageView gets reassigned because it will be called in getView again, and from there you can figure out if it has a pending download you need to cancel.
Consider using one of the existing solutions or just checking out how others have done it for a full example. https://github.com/nostra13/Android-Universal-Image-Loader

How to implement autocompletetextview with listview?

I am getting response from server and display it using listview and it works fine,now what I am trying is i added autocompletetextview to search items by name,but when i run my app it crashes and showing errors..i already ask this
Tab1Activity.java
public class Tab1Activity extends ListActivity{
private ProgressDialog pDialog;
JSONArray Product=null;
private ListView listview;
ArrayList<HashMap<String,String>> aList;
ArrayList<HashMap<String, String>> arrayTemplist;
private static String PRODUCT_URL = "";
private static final String PRODUCT_DATA="Product";
private static final String PRODUCT_ID="productid";
private static final String PRODUCT_NAME="product_name";
private static final String PRODUCT_CODE="skucode";
private static final String PRODUCT_IMAGE="product_photo";
private static final String PRODUCT_WEIGHT="weight";
private static final String PRODUCT_SALERATE="sale_rate";
//private static final String PRODUCT_LOCATION="weight";
private CustomAdapterTabone adapter;
private TextView noacpt;
private AutoCompleteTextView inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_tabone);
//noacpt=(TextView)findViewById(R.id.no_acceptedlist);
/*String strtext = getIntent().getStringExtra("id");
System.out.println("<<<<<<<< id : " + strtext);*/
final ListView listview = (ListView)findViewById(android.R.id.list);
//listview.setSelector( R.drawable.list_selector);
//listview.setSelector(R.drawable.listselector);
new LoadAlbums().execute();
aList = new ArrayList<HashMap<String, String>>();
final ListView lv = getListView();
inputSearch = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
arrayTemplist= new ArrayList<HashMap<String,String>>();
String searchString =inputSearch.getText().toString().toLowerCase();
for (int i = 0; i < aList.size(); i++)
{
String currentString =aList.get(i).get(Tab1Activity.PRODUCT_NAME);
if (currentString.toLowerCase().startsWith(searchString ))
{
arrayTemplist.add(aList.get(i));
}
}
for (int i = 0; i < arrayTemplist.size(); i++)
{
String currentstrin = arrayTemplist.get(i).get(Tab1Activity.PRODUCT_NAME);
//Toast.makeText(getApplicationContext(), currentstrin, Toast.LENGTH_LONG).show();
}
adapter=new CustomAdapterTabone(getApplicationContext(), arrayTemplist);
listview.setAdapter(adapter);
/* SimpleAdapter adapters = new SimpleAdapter(Tab1Activity.this, arrayTemplist,R.layout.list_item_tabone, new String[] { PRODUCT_NAME
}, new int[] {
R.id.txtpronameacptedlist});
lv.setAdapter(adapters);
*/
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(getApplicationContext(), AllProductDetails.class);
intent.putExtra("productid", aList.get(position).get(PRODUCT_ID));
startActivity(intent);
}
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Tab1Activity.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
// pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(PRODUCT_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
Product = jsonObj.getJSONArray(PRODUCT_DATA);
for (int i = 0; i < Product.length(); i++) {
JSONObject c = Product.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(PRODUCT_ID, c.getString(PRODUCT_ID));
map.put(PRODUCT_NAME,c.getString(PRODUCT_NAME));
map.put(PRODUCT_CODE, c.getString(PRODUCT_CODE));
map.put(PRODUCT_IMAGE, c.getString(PRODUCT_IMAGE));
map.put(PRODUCT_WEIGHT, c.getString(PRODUCT_WEIGHT));
map.put(PRODUCT_SALERATE, c.getString(PRODUCT_SALERATE)+getResources().getString(R.string.rupee));
// map.put(INTEREST_ACCEPT_LOCATION, c.getString(INTEREST_ACCEPT_LOCATION));
// adding HashList to ArrayList
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
aList = new ArrayList<HashMap<String, String>>();
aList.addAll(result);
adapter = new CustomAdapterTabone(getApplicationContext(),result);
setListAdapter(adapter);
aList.addAll(result);
adapter.notifyDataSetChanged();
}
}
CustomAdapter
public class CustomAdapterTabone extends BaseAdapter{
private Context context;
private ArrayList<HashMap<String,String>> listData;
private AQuery aQuery;
private static final String TAG_NAME="product_name";
private static final String TAG_PROFILE="skucode";
private static final String TAG_IMAGE="product_photo";
private static final String TAG_CAST="weight";
private static final String TAG_AGE="sale_rate";
// private static final String TAG_LOCATION="weight";
public CustomAdapterTabone(Context context,ArrayList<HashMap<String,String>> listData) {
this.context = context;
this.listData=listData;
aQuery = new AQuery(this.context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item_tabone, null);
holder.propic = (ImageView) convertView.findViewById(R.id.propicaccept);
holder.txtproname = (TextView) convertView.findViewById(R.id.txtpronameacptedlist);
holder.txtproid = (TextView) convertView.findViewById(R.id.txtproidacptedlist);
holder.txtprofilecast = (TextView) convertView.findViewById(R.id.txtprofilecastacptedlist);
holder.txtprofileage = (TextView) convertView.findViewById(R.id.txtprofileageacptedlist);
// holder.txtprofileplace = (TextView) convertView.findViewById(R.id.txtprofileplaceacptedlist);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtproname.setText(listData.get(position).get(TAG_NAME));
holder.txtproid.setText(listData.get(position).get(TAG_PROFILE));
holder.txtprofilecast.setText(listData.get(position).get(TAG_CAST));
holder.txtprofileage.setText(listData.get(position).get(TAG_AGE));
//holder.txtprofileplace.setText(listData.get(position).get(TAG_LOCATION));
aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);
// image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
return convertView;
}
class ViewHolder{
ImageView propic;
TextView txtproname;
TextView txtproid;
TextView txtprofilecast;
TextView txtprofileage;
TextView txtprofileplace;
}
}
First create a custom adapter implements filterable:
public class MyFilterableAdapter extends BaseAdapter implements Filterable {
private Context context;
private List<String> items;
private List<String> filteredItems;
private ItemFilter mFilter = new ItemFilter();
public MyFilterableAdapter(Context context, List<String> items) {
//super(context, R.layout.your_row, items);
this.context = context;
this.items = items;
this.filteredItems = items;
}
#Override
public int getCount() {
return filteredItems.size();
}
#Override
public Object getItem(int position) {
return filteredItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_search_merchant, parent, false);
viewHolder = new ViewHolder();
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
String location = filteredItems.get(position);
if (!location.isEmpty() || viewHolder != null) {
viewHolder.tvTitle.setText(location);
}
return convertView;
}
public static class ViewHolder {
TextView tvTitle;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
int count = items.size();
final List<String> tempItems = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
if (items.get(i).toLowerCase().contains(filterString)) {
tempItems.add(items.get(i));
}
}
results.values = tempItems;
results.count = tempItems.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredItems = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
public Filter getFilter() {
return mFilter;
}
}
And than create a textwatcher
public class MyTextWatcher implements TextWatcher {
private MyCustomAdapter lAdapter;
public MyTextWatcher(MyCustomAdapter lAdapter) {
this.lAdapter = lAdapter;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
lAdapter.getFilter().filter(s.toString().toLowerCase());
}
}
And finally add your TextWatcher to your Search Edit Text:
final MyCustomAdapter lAdapter = new MyCustomAdapter(context, items);
EditText etSearch = (EditText) view.findViewById(R.id.et_search);
etSearch.addTextChangedListener(new SearchTextWatcher(lAdapter));
I hope this'll help you.

adding data to existing listview

I have created listview using the following code
public class homeScreen extends Activity{
ArrayList<SingleRow> list;
boolean flag = false;
String space = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
final Context c = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.homescreen);
//putting actual values in array
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
int[] images = {R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i = 0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
final ListView list1 = (ListView)findViewById(R.id.spacelist);
final MySimpleAdapter adapter = new MySimpleAdapter(this,list);
list1.setAdapter(adapter);
space = getIntent().getStringExtra("spaceName");
if(null! = space){
adapter.addView(space);
}
list1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
if((titles[position]).equalsIgnoreCase("My Ideas")){
Intent i = new Intent(homeScreen.this, privateSpaceList.class);
startActivity(i);
} else if((titles[position]).equalsIgnoreCase("Create New Space")){
Intent i = new Intent(homeScreen.this, createNewSpace.class);
startActivity(i);
}
}
});
}
}
Row class:
class SingleRow{
String title;
int image;
public SingleRow(String title,int image) {
this.title = title;
this.image = image;
}
}
Adapter:
class MySimpleAdapter extends BaseAdapter{
ArrayList<SingleRow> list;
private Context context;
public MySimpleAdapter(Context c,ArrayList<SingleRow> list) {
this.context = c;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public void addView(String space) {
int rows = this.getCount();
list.add(rows, new SingleRow(space,R.drawable.ic_launcher));
notifyDataSetChanged();
}
#Override
public View getView(int i, View view, ViewGroup viewgroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row,viewgroup,false);
TextView title = (TextView)row.findViewById(R.id.label);
ImageView image = (ImageView)row.findViewById(R.id.imageView);
SingleRow temp = list.get(i);
title.setText(temp.title);
image.setImageResource(temp.image);
return row;
}
}
code for create new space
public class createNewSpace extends Activity{
Button add;
TextView sname,pname;
ListView plist;
int success;
Jparser jsonParser = new Jparser();
JSONObject json;
private ProgressDialog pDialog;
ArrayList<String> usersList;
ArrayList<String> spaceUsers;
private static String url_users = "http://10.0.2.2/phpdata/getting_allusers.php";
private static String url_create_space = "http://10.0.2.2/phpdata/create_space.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERS = "users";
private static final String TAG_UNAME = "firstName";
// products JSONArray
JSONArray users = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.createnewspace);
sname=(TextView)findViewById(R.id.spaceName);
pname=(TextView)findViewById(R.id.participents);
plist=(ListView)findViewById(R.id.participantlist);
add=(Button)findViewById(R.id.button1);
// Hashmap for ListView
usersList= new ArrayList<String>();
spaceUsers=new ArrayList<String>();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new getAllUsers().execute();
}
});
plist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String users[]=usersList.toArray(new String[usersList.size()]);
Toast.makeText(getApplicationContext(), "User "+users[arg2]+ " added to space "+sname.getText(), Toast.LENGTH_SHORT).show();
spaceUsers.add(users[arg2]);
}
});
// Loading users in Background Thread
}
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menuspace, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return MenuChoice(item);
}
private boolean MenuChoice(MenuItem item)
{
switch(item.getItemId())
{
case R.id.create:
new createSpace().execute();
return true;
}
return false;
}
class createSpace extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
for(int i=0;i<spaceUsers.size();i++)
{
String sname1 = sname.getText().toString();
String uname = spaceUsers.get(i);
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sname", sname1));
params.add(new BasicNameValuePair("uname", uname));
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_create_space,
"POST", params);
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully inserted user details
Intent is = new Intent(getApplicationContext(), homeScreen.class);
is.putExtra("spaceName", sname1);
startActivity(is);
// closing this screen
finish();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
}
}
class getAllUsers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON Object
json = jsonParser.makeHttpRequest(url_users,"GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// getting value of success tag
try {
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
if (success == 1) {
// Getting Array of users
try{
JSONArray users=json.getJSONArray(TAG_USERS);
// looping through All Products
for (int i = 0; i < users.length(); i++) {
Log.d("check", "success");
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_UNAME);
Log.d("name....",name);
// adding HashList to ArrayList
usersList.add(name);
}
} catch(JSONException e)
{
e.printStackTrace();
}
}
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
plist.setAdapter(new ArrayAdapter<String>(createNewSpace.this,android.R.layout.simple_list_item_1,usersList));
}
});
}
}
}
Now I want to add Item to this existing list.
I am taking data from another activity using intent.
Now one item get added.but next time that get replaced.
Please Help.
Thank you in advance.
You should move the creation of the data outside of the adapter:
list=new ArrayList<SingleRow>();
//putting actual values in array
Resources res=c.getResources();
String[] titles=res.getStringArray(R.array.titles);
int[] images={R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i=0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
Pass the list variable to the adapter and store a reference to it there. Then you can just update the data in the list variable, and call notifyDataSetChanged() on your adapter.
Edit: It seems you want to store the space values, and then retrieve them in the HomeScreen activity later. If I understand the flow of your app correctly, then the createNewSpace class should store the space in SharedPreferences. Then in the HomeScreen activity you should retrieve those from the SharedPreferences, and show them.
You can add data to the adapter and call notifyDataSetChanged().Alternatively, You can create a new adapter and listView.setAdapter(adapter) that adapter.

Android search in Listview using baseadapter

I try to add search list form City list using my base adapter but it doesn't work. I want to search City in cities list. Here's My code.
My CitySerach :
private ProgressDialog pDialog;
EditText inputSearch;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// Hashmap for ListView
ArrayList<HashMap<String, String>> CitiesLI = new ArrayList<HashMap<String, String>>();
// url to make request
private static String url_cityli = "http://10.0.2.2/Myweb/ecities.php";
// JSON Keys
public static final String TAG_CITEMS_LI = "cities_li";
public static final String TAG_CID_LI = "city_id";
public static final String TAG_CNAME_LI = "city_name";
public static final String TAG_CIMG_LI = "image";
JSONArray cities_li = null;
ListView list;
CitySearchAdapter adapter;
private CitySearch activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tt);
CitiesLI = new ArrayList<HashMap<String, String>>();
new Activity().execute();
activity = this;
list = (ListView) findViewById(R.id.city_list);
//list click to details view of the place
list.setOnItemClickListener(new OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String cid_li = ((TextView) view.findViewById(R.id.cid_li)).getText().toString();
Intent i = new Intent(getApplicationContext(),
//Tab.class);
CityInfoActivity.class);
// Starting new intent
i.putExtra(TAG_CID_LI, cid_li);
startActivity(i);
//startActivityForResult(i, 100);
}
});
}
public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {
adapter = new CitySearchAdapter(activity, daftar);
list.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class Activity extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CitySearch.this);
pDialog.setMessage("Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONArray json = jParser.makeHttpRequest(url_cityli, "GET",
params);
Log.d("All Products: ", json.toString());
// looping through All data
try {
cities_li = json;
for (int i = 0; i < cities_li.length(); i++) {
JSONObject c = cities_li.getJSONObject(i);
// Storing each json item in variable
String city_id = c.getString(TAG_CID_LI);
String city_name =c.getString(TAG_CNAME_LI);
String image = c.getString(TAG_CIMG_LI);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
//JSON Object
map.put(TAG_CID_LI, city_id);
map.put(TAG_CNAME_LI,city_name);
map.put(TAG_CIMG_LI, image);
// adding HashList to ArrayList
CitiesLI.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
SetListViewAdapter(CitiesLI);
//
// Enabling Search Filter
CitySearchAdapter adapter;
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Listview name of the class
CitySearch.this.adapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
});
}
}
}
Here my CitylistAdapter :
public class CitySearchAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public CitySearchAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.te, null);
TextView city_id = (TextView) vi.findViewById(R.id.cid_li);
TextView image = (TextView) vi.findViewById(R.id.cimg_li);
TextView city_name = (TextView) vi.findViewById(R.id.cname);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.cimage);
HashMap<String, String> city_li = new HashMap<String, String>();
city_li = data.get(position);
city_id.setText(city_li.get(CityActivity.TAG_CID_LI));
image.setText(city_li.get(CityActivity.TAG_CIMG_LI));
city_name.setText(city_li.get(CityActivity.TAG_CNAME_LI));
imageLoader.DisplayImage(city_li.get(CityActivity.TAG_CIMG_LI),thumb_image);
return vi;
}
public Object getFilter() {
// TODO Auto-generated method stub
return null;
}
}
Pleace Help me.
Thanks all

filter search in android

I am making a filter search to my listview. My listview code is executing well. I put an edittext object and I will make the filter search. How can i make this? My codes are below.
package com.nexum.imageloadingromjson;
public class MainActivity extends Activity {
private ListView list;
private MyAdapter adapter;
private final String parsingUrl = "someurl";
private String tag_coord = "Coord";
private String tag_lat = "Lat";// Double
private String tag_lon = "Lon";// Double
private String tag_image = "Image";
private String tag_InIzmir = "InIzmir";// Boolean
private String tag_name = "Name";
private ImageLoader imageLoader;
private EditText filteredittext;
private ProgressDialog pDialog;
private static int clickedItemPosition = -1;
private final int REQUEST_CODE_DETAIL = 1;
ArrayList<CoordItem> items;
ArrayList<CoordItem> filterlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
items = new ArrayList<CoordItem>();
filterlist = new ArrayList<CoordItem>();
adapter = new MyAdapter(this, R.layout.list_item, items);
list = (ListView) findViewById(R.id.exampList);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
filteredittext = (EditText)findViewById(R.id.filtersearchedittext);
filteredittext.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
viewitems.clear();
String search = filteredittext.getText().toString();
for (int i = 0; i < items.size(); i++) {
if(items.get(i).name.equals(search)){
viewitems.add(items.get(i));
adapter.notifyDataSetChanged();
}
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
pDialog = new ProgressDialog(this);
pDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
pDialog.setMessage("Veriler alınıyor...");
new ListViewLoad().execute();
list.setOnItemClickListener(new OnItemClickListener() {
#SuppressLint("ShowToast")
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
/*
* String bulunma = ""; if (items.get(position).inIzmir) {
* bulunma+="İzmir de bulundu."; }else{
* bulunma+="İzmir de bulunmadı."; } String
* s="Name:"+items.get(position).name+"\nInIzmir:"+bulunma;
* Toast.makeText(getApplicationContext(), s,
* Toast.LENGTH_LONG).show();
*/
clickedItemPosition = position;
Intent myIntent = new Intent(MainActivity.this,
DetailActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable(
"parcelable_key",
new CoordItem(items.get(position).name, items
.get(position).img, items.get(position).lat,
items.get(position).lon,
items.get(position).inIzmir));
myIntent.putExtras(bundle);
// Güncelleme olayı burada baÅŸlıyor
// startActivityForResult(myIntent, REQUEST_CODE_DETAIL);
startActivityForResult(myIntent, REQUEST_CODE_DETAIL);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_DETAIL && resultCode == RESULT_OK
&& data != null) {
CoordItem coorditem = new CoordItem(data.getStringExtra("name"),
items.get(clickedItemPosition).img, Double.parseDouble(data
.getStringExtra("lat")), Double.parseDouble(data
.getStringExtra("lon")),
items.get(clickedItemPosition).inIzmir);
items.set(clickedItemPosition, coorditem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Guncelleme yapıldı.",
Toast.LENGTH_SHORT).show();
}
}
private class ListViewLoad extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String json = getStringFromURL(parsingUrl);
try {
final JSONArray jArray = new JSONArray(json);
for (int i = 0; i < jArray.length(); i++) {
JSONObject c = jArray.getJSONObject(i);
JSONObject coord = c.getJSONObject(tag_coord);
double lat = coord.getDouble(tag_lat);
double lon = coord.getDouble(tag_lon);
String image = c.getString(tag_image);
boolean InIzmir = c.getBoolean(tag_InIzmir);
String name = c.getString(tag_name);
CoordItem item = new CoordItem(name, image, lat, lon,
InIzmir);
items.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter.notifyDataSetChanged();
pDialog.dismiss();
}
}
private class MyAdapter extends ArrayAdapter<CoordItem> {
private LayoutInflater inflater;
public MyAdapter(Context context, int textViewResourceId,
ArrayList<CoordItem> objects) {
super(context, textViewResourceId, objects);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
if (items != null)
return items.size();
else
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewholder = null;
if (convertView == null) {
viewholder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item, parent,
false);
viewholder.listItemImage = (ImageView) convertView
.findViewById(R.id.listItemImage);
viewholder.listItemName = (TextView) convertView
.findViewById(R.id.listItemName);
viewholder.listItemInIzmir = (TextView) convertView
.findViewById(R.id.listItemInIzmir);
viewholder.listItemLatitude = (TextView) convertView
.findViewById(R.id.listItemLatitude);
viewholder.listItemLongitude = (TextView) convertView
.findViewById(R.id.listItemLongitude);
convertView.setTag(viewholder);
} else {
viewholder = (ViewHolder) convertView.getTag();
}
viewholder.listItemName.setText(items.get(position).name);
if (items.get(position).inIzmir) {
viewholder.listItemInIzmir.setText("Izmirde.");
} else {
viewholder.listItemInIzmir.setText("Izmirde degil.");
}
DisplayImageOptions options = new DisplayImageOptions.Builder().delayBeforeLoading(1000).build();
imageLoader.displayImage(items.get(position).img,viewholder.listItemImage,options);
return convertView;
}
public Drawable getDrawableFromUrl(URL url) {
try {
InputStream is = (InputStream) url.getContent();
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (Exception e) {
return null;
}
}
}
static class ViewHolder {
ImageView listItemImage;
TextView listItemName, listItemInIzmir, listItemLatitude,
listItemLongitude;
}
public String getStringFromURL(String url) {
// Making HTTP request
String json = "";
InputStream is = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// return JSON String
return json;
}
}
What must i write to onTextChanged method in these codes? I researched but I didn't find codes for this class. Or I did not edit.
For searching on listview check the link here.
How can I filter ListView data when typing on EditText in android
If you want make custom search you can use the code below
Activity_main.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:orientation="vertical">
<EditText
android:id="#+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Main Activity
public class MainActivity extends Activity {
ArrayList<NewData> mTemp=new ArrayList<NewData>(); //temporary list for search data
ArrayList<NewData> mPostingData=new ArrayList<NewData>(); //data to post in listview
ArrayList< NewData> mOri = new ArrayList<NewData>() ;//original data
// You can have two arraylist instead of three. 1. for original values 2. one for search result.
Myadapter ma;
EditText search;
NewData nd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i = 0; i < 20; i++)
{
// Add your Json Parsed Data here
// each item from json add it to hash map in NewData class. Arraylist of 0 contains jsondata of customer1
nd=new NewData();
nd.newDatacus.put(NewData.TAG_CUSTOMER_CODE, "i"+i);
nd.newDatacus.put(NewData.TAG_CUSTOMER_NAME, "a"+i);
nd.newDatacus.put(NewData.TAG_CUSTOMER_MOBILE, "number");
nd.newDatacus.put(NewData.TAG_CUSTOMER_ADDRESS, "address");
mOri.add(nd);
}
ma= new Myadapter(MainActivity.this);
mPostingData=mOri;
mTemp=mOri;
ListView lv= (ListView) findViewById(R.id.list);
lv.setAdapter(ma);
search= (EditText) findViewById(R.id.search); //editext
search.addTextChangedListener(new TextWatcher() { //supply edittext value to filter
public void onTextChanged(CharSequence s, int start, int before, int count) {
ma.getFilter().filter(s);
ma.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
class Myadapter extends ArrayAdapter
{
LayoutInflater mInflater;
public void setData(ArrayList<NewData> mPpst) { //function to set data based on search result
mPostingData = mPpst;//contains class items data.
}
#Override
public Filter getFilter() { //implement getFilter
return new Filter() {
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count >= 0) {
setData((ArrayList<NewData>) results.values);//if results of search is null set the searched results data
} else {
setData(mOri);// set original values
}
notifyDataSetInvalidated();//refresh listview
}
//this performs filtering data.//check if data matches whats typed in editext
//add it to list if found. return list (founditems)
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if (!TextUtils.isEmpty(constraint)) {
constraint = constraint.toString().toLowerCase();
ArrayList<NewData> foundItems = new ArrayList<NewData>();
if(mTemp!=null)
{
for(int i=0;i<mTemp.size();i++)
{
if (mTemp.get(i).newDatacus.get(NewData.TAG_CUSTOMER_CODE).toString().contains(constraint)) {
System.out.println("My datas"+mTemp.get(i).newDatacus.get(NewData.TAG_CUSTOMER_CODE).toString());
foundItems.add(mTemp.get(i));
}
else
{
}
}
}
result.count = foundItems.size();//search results found return count
result.values = foundItems;// return values
}
else
{
result.count=-1;// no search results found
}
return result;
}
};
}
public Myadapter(Context context) {
super(context, 0);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mPostingData.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 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(mOri == null ){
return null;
}
// When convertView is not null, we can reuse it directly, there is no need
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list, null);
convertView.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.t1=(TextView) convertView.findViewById(R.id.textView1);
holder.t2 = (TextView) convertView.findViewById(R.id.textView2);
holder.t3 = (TextView) convertView.findViewById(R.id.textView3);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
holder.t1.setText(mPostingData.get(position).newDatacus.get(NewData.TAG_CUSTOMER_CODE).toString());
holder.t2.setText(mPostingData.get(position).newDatacus.get(NewData.TAG_CUSTOMER_NAME).toString());
holder.t3.setText(mPostingData.get(position).newDatacus.get(NewData.TAG_CUSTOMER_MOBILE).toString());
return convertView;
}
}
class ViewHolder
{
TextView t1,t2,t3;
}
}
list.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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:text="TextView" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:text="TextView" />
</LinearLayout>
NewData Class- Holds all data in hashmap
public class NewData {
public static final String TAG_CUSTOMER_CODE = "customer_code";
public static final String TAG_CUSTOMER_NAME = "customer_name";
public static final String TAG_CUSTOMER_MOBILE = "customer_mobile";
public static final String TAG_CUSTOMER_ADDRESS = "customer_address";
Hashtable newDatacus=new Hashtable();
public NewData()
{
newDatacus.put(NewData.TAG_CUSTOMER_CODE,new String());
newDatacus.put(NewData.TAG_CUSTOMER_ADDRESS,new String());
newDatacus.put(NewData.TAG_CUSTOMER_NAME,new String());
newDatacus.put(NewData.TAG_CUSTOMER_MOBILE,new String());
newDatacus.put(NewData.TAG_CUSTOMER_ADDRESS,new String());
}
}
Please try with the below code.
you must integrate this line .. where you are setting adapter .
listView.setAdapter(new MyAddapter(this));
array_sort.clear();
array_sort.addAll(Service_Listitems);
then use below lines.
edittext_search.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
public void onTextChanged(CharSequence s, int start, int before, int count){
try {
Service_Listitems.clear();// Clear your arraylist initially
for (int i = 0; i < array_sort.size(); i++) {
if (array_sort.get(i) instanceof yourServiceSetterGetterClass) {
yourServiceSetterGetterClass cp1 = (yourServiceSetterGetterClass)array_sort.get(i);
String strOrig = "";
if (cp1.getFirstName() == null) {
strOrig = "";
} else {
strOrig = cp1.getFirstName().toUpperCase().trim();
}
String str = edittext_search.getText().toString().toUpperCase().trim();
if (strOrig.startsWith(str)) { Service_Listitems.add(cp1);
}
}
}
listView.setAdapter(new MyAddapter(this));
} catch (Exception e) {
e.printStackTrace();
}
}
});;
EDIT
ArrayList<CoordItem> Service_Listitems= new ArrayList<CoordItem>();
private ArrayList<Object> array_sort = new ArrayList<Object>();
or you can use like below also
private ArrayList<CoordItem> array_sort = new ArrayList<CoordItem>();

Categories

Resources