How to navigate in Tab Application in Android? with my sources classes - android

// The below Fourth is fourth tab activity in my project so inside it am having few more
other activites like MasjidsearchActivity inside on item .it is displaying as separate activity but i want with remaining tabs
package com.hands.iagd.app;
import java.util.ArrayList;
import java.util.List;
import android.R.layout;
import android.R.string;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class Fourth extends Activity {
static String[] values,Masjeed,Alaram;
String[] adjust_calender;
ListView lv1,lv2,lv3,lv4;
public static List<String> Calculation_method=new ArrayList<String>();
int index,index2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fourth);
lv1=(ListView)findViewById(R.id.lv1);
lv2=(ListView)findViewById(R.id.lv2);
lv3=(ListView)findViewById(R.id.lv3);
lv4=(ListView)findViewById(R.id.lv4);
values = new String[] {"Jafari","Karachi","ISNA","MWL","Makkah","Egypt","Custom","Tehran"};
Masjeed = new String[] {"IAGD Masjid"};
Alaram = new String[] {""};
String hijriString="Hijri Calender "+Adjust_Time.hijriAdjust;
adjust_calender= new String[]{hijriString};
lv1.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice,values));
lv1.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
index=First.index;
lv1.setItemChecked(index, true);
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
index=arg2;
First.index=arg2;
System.out.println("index " +index);
}
});
Masjeed=MasjidsearchActivity.selectedmasjid;
lv2.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,Masjeed));
lv2.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv2.setItemChecked(index2, true);
lv2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
index2=arg2;
First.index2=arg2;
System.out.println("index " +index2);
Intent masjid=new Intent(Fourth.this,MasjidsearchActivity.class);
startActivity(masjid);
}
});
lv3.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,adjust_calender));
lv3.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Adjust_Time.sahurORiftar="hijri";
Intent i=new Intent(Fourth.this,Adjust_Time.class);
startActivity(i);
}
});
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
String hijriString="Hijri Calender "+Adjust_Time.hijriAdjust;
adjust_calender= new String[]{hijriString};
lv1.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice,values));
lv1.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
index=First.index;
lv1.setItemChecked(index, true);
lv2.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice,Masjeed));
lv2.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
index2=First.index2;
lv2.setItemChecked(index2, true);
lv3.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,adjust_calender));
super.onResume();
}
}
//here is MasjidsearchActivity class
package com.hands.iagd.app;
/**
* ©2010 by androidblogger.ch
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MasjidsearchActivity extends Activity {
RadioButton rb1 ;
Button b1,btn;
EditText edittext;
ListView mainListView;
static String[] selectedmasjid=new String[] {"IAGD Masjid"};;
List<Hashtable<String,String>> list1 = new ArrayList<Hashtable<String,String>>();
int textlength = 0;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();
ArrayList<String> text_sort2 = new ArrayList<String>();
// ArrayList which contains our HashMap's with different objects
private ArrayList<HashMap<String, Object>> myList;
private ArrayList<HashMap<String, Object>> myList1;
private ArrayList<HashMap<String, Object>> filterList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.masjidlist);
b1=(Button)findViewById(R.id.button1);
btn=(Button)findViewById(R.id.btn);
btn.setOnCreateContextMenuListener(this);
//rb1=(RadioButton)findViewById(R.id.radioButton1);
/*rb1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
System.out.println( "inside radio buttons" );
}});*/
mainListView = (ListView) findViewById(R.id.main_listview);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
IAGDAPPActivity.settingCurrentTab=3;
Intent int1 = new Intent(MasjidsearchActivity.this, IAGDAPPActivity.class);
startActivity(int1);
}});
edittext = (EditText) findViewById(R.id.search_mycontact);
// Create Hash Map
myList = new ArrayList<HashMap<String, Object>>();
myList1 = new ArrayList<HashMap<String, Object>>();
filterList = new ArrayList<HashMap<String, Object>>();
edittext.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)
{
textlength = edittext.getText().length();
text_sort.clear();
image_sort.clear();
text_sort2.clear();
filterList.clear();
for (int i = 0; i < myList1.size(); i++)
{
HashMap<String,Object> maps=new HashMap<String, Object>();
maps=myList1.get(i);
String masjidName=maps.get("MosquesNames").toString();
String cityName=maps.get("MosqueCity").toString();
List<String> searchStrring = new ArrayList<String>(Arrays.asList(masjidName.split(" ")));
searchStrring.add(masjidName);
searchStrring.add(cityName);
for (String s123 : searchStrring) {
if (textlength <= s123.length())
{
if (edittext.getText().toString().
equalsIgnoreCase((String) s123.subSequence(0, textlength)))
{
filterList.add(maps);
break;
}
}
/* if (edittext.getText().toString().
equalsIgnoreCase((String) masjidName.subSequence(0, textlength)))
{
//text_sort.add(month[i]);
//image_sort.add(image[i]);
// text_sort2.add(desc[i]);
filterList.add(maps);
}*/
}
}
displayList(filterList);
mainListView = (ListView) findViewById(R.id.main_listview);
mainListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
System.out.println("****3");
}
});
// Fill data
// addDataToList();
addDBFROMCSV();
// View
mainListView = (ListView) findViewById(R.id.main_listview);
// Adapter
/* SimpleAdapter aa = new SimpleAdapter(this, myList, R.layout.row,
new String[] {"name", "address", "city", "icon"},
new int[] {R.id.txt_name, R.id.txt_town, R.id.txt_phone, R.id.img_user});
mainListView.setAdapter(aa);*/
/* SimpleAdapter aa = new SimpleAdapter(this, myList1, R.layout.row,
new String[] {"MosquesNames", "MosqueAddress", "MosqueCity","icon"},
new int[] {R.id.txt_name, R.id.txt_town, R.id.txt_phone, R.id.img_user});
mainListView.setAdapter(aa);
*/ displayList(myList1);
// Listener
mainListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mainListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get the HashMap of the clicked item
HashMap<String, Object> user = myList1.get(position);
// Get Attribute name of the HashMap
String name = (String)user.get("MosquesNames");
selectedmasjid =new String[] {name};
System.out.println("name:"+selectedmasjid.length);
// Create new Dialog
final Dialog dialog = new Dialog(MasjidsearchActivity.this);
dialog.setTitle(" " + name);
TextView txtDescription = new TextView(MasjidsearchActivity.this);
txtDescription.setPadding(10, 0, 0, 10);
txtDescription.setText("Masjid Selected");
dialog.setContentView(txtDescription);
dialog.setCanceledOnTouchOutside(true);
dialog.show();
}
});
}
public void onCreateContextMenu(ContextMenu menu, View view,ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, view, menuInfo);
CreateMenu(menu);
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
return MenuChoice(item);
}
private void CreateMenu(Menu menu)
{
MenuItem mnu1 = menu.add(0, 0, 0, "Register with us");
{
mnu1.setAlphabeticShortcut('a');
//mnu1.setIcon(R.drawable.image1);
}
MenuItem mnu2 = menu.add(0, 1, 1, "Notify about your Masjid ");
{
mnu2.setAlphabeticShortcut('b');
//mnu2.setIcon(R.drawable.image2);
}
MenuItem mnu3 = menu.add(0, 2, 2, "Cancel");
{
mnu3.setAlphabeticShortcut('c');
//mnu3.setIcon(R.drawable.image3);
}
/* MenuItem mnu4 = menu.add(0, 3, 3, "Item 4");
{
mnu4.setAlphabeticShortcut('d');
}
menu.add(0, 4,4, "Item 5");
menu.add(0, 5,5, "Item 6");
menu.add(0, 6,6, "Item 7");*/
}
private boolean MenuChoice(MenuItem item)
{
switch (item.getItemId())
{
case 0:
Intent i=new Intent(MasjidsearchActivity.this,Register.class);
startActivity(i);
//Toast.makeText(this, "You clicked on Notify",Toast.LENGTH_LONG).show();
return true;
case 1:
Intent i1=new Intent(MasjidsearchActivity.this,masjidnotify.class);
startActivity(i1);
//Toast.makeText(this, "You clicked on Register",Toast.LENGTH_LONG).show();
return true;
case 2:
//Toast.makeText(this, "You clicked on Cancel",Toast.LENGTH_LONG).show();
return true;
/*case 3:
Toast.makeText(this, "You clicked on Item 4",Toast.LENGTH_LONG).show();
return true;*/
/* case 4:
Toast.makeText(this, "You clicked on Item 5",Toast.LENGTH_LONG).show();
return true;
case 5:
Toast.makeText(this, "You clicked on Item 6",Toast.LENGTH_LONG).show();
return true;
case 6:
Toast.makeText(this, "You clicked on Item 7",Toast.LENGTH_LONG).show();
return true;*/
}
return false;
}
private void displayList(ArrayList<HashMap<String, Object>> myLists) {
SimpleAdapter aa = new SimpleAdapter(this, myLists, R.layout.row,
new String[] {"MosquesNames", "MosqueAddress", "MosqueCity","icon"},
new int[] {R.id.txt_name, R.id.txt_town, R.id.txt_phone, R.id.img_user});
mainListView.setAdapter(aa);
mainListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
private void addDBFROMCSV()
{
InputStream is = this.getResources().openRawResource
(R.raw.listofmosquesinusa);
BufferedReader reader = new BufferedReader(new InputStreamReader
(is));
try {
ArrayList< String> list=new ArrayList<String>();
String line;
while ((line = reader.readLine()) != null) {
// do something with "line"
// System.out.println("llllll"+line);
list.add(line);
}
// System.out.println("llllll"+list);
ArrayList<List<String>> arrayList=new ArrayList<List<String>>();
for(int i=0;i<list.size();i++)
{
String s1=list.get(i);
List<String> list12 = new ArrayList<String>(Arrays.asList(s1.split("123456COLUMNDEVIDER")));
// System.out.println("List1 is "+list1);
// System.out.println("List size is "+list1.size());
arrayList.add(list12);
}
ArrayList<List<String>> updatedList =new ArrayList<List<String>>();
for(int k=0;k<arrayList.size();k++)
{
List<String> l111=new ArrayList<String>();
List<String> l1=new ArrayList<String>();
l1=arrayList.get(k);
for(int j=0;j<l1.size();j++)
{
String sss1=l1.get(j);
if(sss1.length()<2)
{
l111.add(" ");
// System.out.println("Values in empty"+sss1);
}
else
{
char c1=sss1.charAt(0);
if(c1==',' )
{
sss1=sss1.substring(1);
}
c1=sss1.charAt(sss1.length()-1);
if(c1==',' )
{
sss1=sss1.substring(0,sss1.lastIndexOf(","));
}
l111.add(sss1);
//System.out.println("Values in "+sss1);
}
}
updatedList.add(l111);
}
System.out.println("updated list"+updatedList);
ArrayList<String> tblList=new ArrayList<String>();
for(int i=0;i<updatedList.size();i++)
{
List<String> oneList=updatedList.get(i);
String x1=oneList.get(0);
String x2=oneList.get(1);
String x3=oneList.get(2);
String x4=oneList.get(3);
String x5=oneList.get(4);
String x6=oneList.get(5);
String x7=oneList.get(6);
String x8=oneList.get(7);
String x9=oneList.get(8);
String x10=oneList.get(9);
// String x11=oneList.get(10);
Hashtable<String, String> hm = new Hashtable<String, String>();
hm.put("Sno", x1);
hm.put("MosquesNames", x2);
hm.put("MosqueAddress", x3);
hm.put("MosqueCity", x4);
hm.put("Mosquestate", x5);
hm.put("Mosquezip", x6);
hm.put("Mosquecountry", x7);
hm.put("Mosquephn1", x8);
hm.put("Mosquephn2", x9);
hm.put("Mosquephn3", x10);
//hm.put("Mosquephn3", x10);
// hm.put("icon", R.drawable.images);
HashMap<String, Object> map1 = new HashMap<String, Object>();
map1.put("Sno", x1);
map1.put("MosquesNames", x2);
map1.put("MosqueAddress", x3);
map1.put("MosqueCity", x4);
map1.put("Mosquestate", x5);
map1.put("Mosquezip", x6);
map1.put("Mosquecountry", x7);
map1.put("Mosquephn1", x8);
map1.put("Mosquephn2", x9);
map1.put("Mosquephn3", x10);
map1.put("icon", R.drawable.images);
myList1.add(map1);
// list1.add(hm) ;
// add=hm.get("MosquesNames")+" "+hm.get("MosqueAddress")+" "+hm.get("MosqueCity");
//tblList.add(add);
}
System.out.println("new:"+myList1);
}
catch (IOException ex) {
// handle exception
}
finally {
try {
is.close();
}
catch (IOException e) {
// handle exception
}
}
}
/**
* This method is used, to fill data into our List
*/
private void addDataToList(){
HashMap<String, Object> map1 = new HashMap<String, Object>();
map1.put("icon", R.drawable.images);
map1.put("name", "Al-Masjidul Al-Kaa'Bah");
map1.put("address", "691 Idlewild Circle - Suite H");
map1.put("city", "Birmingham, Alabama");
HashMap<String, Object> map2 = new HashMap<String, Object>();
map2.put("icon",R.drawable.images);
map2.put("name", "Al-Masjidul Al-Kaa'Bah ");
map2.put("address", "691 Idlewild Circle - Suite H");
map2.put("city", "Birmingham, Alabama");
HashMap<String, Object> map3 = new HashMap<String, Object>();
map3.put("icon", R.drawable.images);
map3.put("name", "Birmingham Islamic Society");
map3.put("address", " ");
map3.put("city", "Birmingham, Alabama");
HashMap<String, Object> map4 = new HashMap<String, Object>();
map4.put("icon", R.drawable.images);
map4.put("name", "Birmingham Mosque");
map4.put("address","1534 19th Street");
map4.put("city", "Birmingham, Alabama");
HashMap<String, Object> map5 = new HashMap<String, Object>();
map5.put("icon", R.drawable.images);
map5.put("name", "Masjid Al-Quran");
map5.put("address", " ");
map5.put("city", "Birmingham, Alabama");
myList.add(map1);
myList.add(map2);
myList.add(map3);
myList.add(map4);
myList.add(map5);
}
}

Related

Issues with Filtering listview with edittext

Hello I'm working on an app which has an edittext to search for items on the listview. If the user types a letter in the edittext the listview is getting filtered perfectlty.Have used Adapter also.Now i have following issues:
1)when i m clearing letters edittext my listview is not getting Updated..
2) if i enter wrong letter or letter which does not corrorsponds to any item of a listview the listview is getting clear.
Have gone thorugh exmaples in SO
Android filter listview custom adapter
And googled also for same problem but not getting solved it..Plz anybody help me..
Here is my code:
package com.AAAAA.AAAAA;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.AdapterView.OnItemClickListener;
import com.AAAAA.adapter.UpdateSingleItemViewActivity;
import com.AAAAA.adapter.UpdatesAdapterList;
import com.AAAAA.local.database.DBController;
import com.AAAAA.AAAAA.AAAAA.constant.Constant;
import com.AAAAA.AAAAA.AAAAA.utils.Utility;
public class Cardiology_updates extends Activity implements OnClickListener,
OnRefreshListener {
EditText et ;
private Context appContext;
// ProgressDialog mProgressDialog;
private Dialog dialog;
private boolean isFinish = false;
String result = "";
JSONObject jsonobject;
JSONArray jsonArray;
ArrayList<HashMap<String, String>> UpdatesHmList;
public static ArrayList<HashMap<String, String>> FinalLocalDataList;
ArrayList<HashMap<String, String>> LocalDataList;
DBController controller = new DBController(this);
HashMap<String, String> queryValues;
ListView list;
UpdatesAdapterList adapter;
public static String UpdateID = "UpdateID";
public static String UpdateTitle = "Title";
/*
* public static String UpdateDescription = "Description"; public static
* String POPULATION = "UpdateDate"; public static String UpdateImage =
* "Photo";
*/
public static String UpdateDescription = "Description";
public static String POPULATION = "Title";
public static String UpdateImage = "Complete_imagePath";
public static String Complete_imagePath;
public static String Title;
public static String Description;
SwipeRefreshLayout swipeLayout;
private ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cardiology_updates);
// controller.deleteAllJsonData();
appContext = this;
animationView();
initComponent();
}
private void animationView() {
// TODO Auto-generated method stub
progressbar = (ProgressBar) findViewById(R.id.loading);
}
private void initComponent() {
// TODO Auto-generated method stub
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
dialog = new Dialog(appContext);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.alert_dialog);
((Button) findViewById(R.id.Button01)).setOnClickListener(this);
((Button) dialog.findViewById(R.id.btnOk)).setOnClickListener(this);
new GetUpdatesInfo().execute();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.Button01) {
finish();
// finishActivity() ;
} else if (v.getId() == R.id.btnOk) {
dialog.dismiss();
if (isFinish) {
this.finish();
}
}
}
public class GetUpdatesInfo extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
if (progressbar.getVisibility() != View.VISIBLE) {
progressbar.setVisibility(View.VISIBLE);
}
}
#Override
protected String doInBackground(String... params) {
// Create an array
UpdatesHmList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
String url = null;
url = Constant.serverUrl + "/GetUpdateList";
result = Utility.postParamsAndfindJSON(url);
Log.e("result doInBackground", "" + result);
if (!(result == null)) {
try {
controller.deleteAllJsonData();
// Locate the array name in JSON
jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonArray.getJSONObject(i);
// Retrive JSON Objects
map.put("UpdateID", jsonobject.getString("UpdateID"));
map.put("Title", jsonobject.getString("Title"));
String Upadates_Photo = jsonobject.optString("Photo")
.toString();
String Complete_imagePath = Constant.prifixserverUrl
+ Upadates_Photo;
String Title = jsonobject.getString("Title").toString();
String Description = jsonobject
.getString("Description").toString();
String noHtml = Description.replaceAll("<[^>]*>", "");
String parseResponse = noHtml.replaceAll(" ", "");
map.put("Photo", Complete_imagePath);
map.put("Description", Description);
map.put("UpdateDate",
jsonobject.getString("UpdateDate"));
Log.e("UpdateID ",
" "
+ jsonobject.getString("UpdateID")
.toString());
Log.e("Title ", " "
+ jsonobject.getString("Title").toString());
Log.e("Complete_imagePath ",
" " + Complete_imagePath.toString());
Log.e("Description ", " " + parseResponse);
Log.e("UpdateDate ",
" "
+ jsonobject.getString("UpdateDate")
.toString());
queryValues = new HashMap<String, String>();
queryValues.put("Complete_imagePath",
Complete_imagePath);
queryValues.put("Title", Title);
queryValues.put("Description", Description);
controller.insertAllJsonData(queryValues);
// Set the JSON Objects into the array
UpdatesHmList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
// Locate the listview in listview_main.xml
if (progressbar.getVisibility() == View.VISIBLE) {
progressbar.setVisibility(View.GONE);
}
/*
* if (result == null) { //mProgressDialog.dismiss();
* localalldata();
*
* }
*/
localalldata();
/*
* list = (ListView) findViewById(R.id.list_Upadates); // Pass the
* results into ListViewAdapter.java adapter = new
* UpdatesAdapterList(Cardiology_updates.this, FinalLocalDataList);
* // Set the adapter to the ListView list.setAdapter(adapter);
*/
// Close the progressdialog
// mProgressDialog.dismiss();
}
}
#Override
public void onRefresh() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getSomeData();
// localalldata();
swipeLayout.setRefreshing(false);
}
}, 5000);
}
protected void getSomeData() {
// TODO Auto-generated method stub
// localalldata();
new GetUpdatesInfo().execute();
adapter.notifyDataSetChanged();
/*
* if (LocalDataList == null) { Log.e("LocalDataList inside if ",
* "LocalDataList inside if "); new GetUpdatesInfo().execute();
*
* } else { // adapter.imageLoader.clearCache();
* Log.e("LocalDataList else ", "LocalDataList else ");
*
* adapter.notifyDataSetChanged(); }
*/
}
private void localalldata() {
// TODO Auto-generated method stub
LocalDataList = controller.getAllJsonData();
FinalLocalDataList = new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> hashMap : LocalDataList) {
System.out.println(hashMap.keySet());
HashMap<String, String> map = new HashMap<String, String>();
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
Complete_imagePath = hashMap.get("Complete_imagePath");
Title = hashMap.get("Title");
Description = hashMap.get("Description");
map.put("Complete_imagePath", Complete_imagePath);
map.put("Title", Title);
map.put("Description", Description);
Log.v("All Json CodiateUpdate Title", "" + Complete_imagePath);
Log.v("All Json CodiateUpdate Title", "" + Title);
}
FinalLocalDataList.add(map);
}
list = (ListView) findViewById(R.id.list_Upadates);
// Pass the results into ListViewAdapter.java
adapter = new UpdatesAdapterList(Cardiology_updates.this,
FinalLocalDataList);
// Set the adapter to the ListView
list.setTextFilterEnabled(true);
list.setAdapter(adapter);
// adapter.notifyDataSetChanged();
et = (EditText) findViewById(R.id.search);
// Capture Text in EditText
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
adapter.filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
//String text = et.getText().toString().toLowerCase(Locale.getDefault());
//adapter.getFilter().filter(arg0);
}
});
}
}
Here is my Adapter:
package com.AAAA.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.AAAA.AAAA.Cardiology_updates;
import com.AAAA.AAAA.R;
import com.AAAA.imageloader.ImageLoader;
public class UpdatesAdapterList extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
//HashMap<String, String> resultp = new HashMap<String, String>();
private ArrayList<HashMap<String,String>> filterData;
public UpdatesAdapterList(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context.getApplicationContext());
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.data);
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
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.listview_updateitem, null);
holder.UpdateTitle = (TextView) convertView.findViewById(R.id.txtUpdatetitle);
holder.UpdateImage = (ImageView) convertView.findViewById(R.id.list_UpdateImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.UpdateTitle.setText(filterData.get(position).get(Cardiology_updates.UpdateTitle));
imageLoader.DisplayImage(filterData.get(position).get(Cardiology_updates.UpdateImage), holder.UpdateImage);
// Capture ListView item click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
//resultp = data.get(position);
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", filterData.get(position).get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", filterData.get(position).get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",filterData.get(position).get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", filterData.get(position).get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
}); return convertView;
}
class ViewHolder{
TextView UpdateTitle;
ImageView UpdateImage;
}
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(data);
}else{
for (HashMap<String,String> row: data) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
}
Activity opens on cliking listview items:
package com.AAAAA.adapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import com.AAAAA.AAAAA.Cardiology_updates;
import com.AAAAA.AAAAA.R;
public class UpdateSingleItemViewActivity extends Activity {
int position;
String UpdateTile;
String UpdateDescription;
String population;
String UpdateImage;
//String position;
ViewPager viewPager;
PagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_update_single_item_view);
Log.e("UpdateSingleItemViewActivity class",
"UpdateSingleItemViewActivity class");
/*
* WebView webview = new WebView(this); setContentView(webview);
*/
Button btnback = (Button) findViewById(R.id.Button01);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
//WebView webview = (WebView) findViewById(R.id.webview);
Intent i = getIntent();
// Get the result of rank
UpdateTile = i.getStringExtra("UpdateTile");
// Get the result of country
UpdateDescription = i.getStringExtra("UpdateDescription");
// Get the result of population
population = i.getStringExtra("population");
// Get the result of flag
UpdateImage = i.getStringExtra("UpdateImage");
//i.putExtra("POSITION_KEY", position);
position = i.getExtras().getInt("position");
//webview.loadData(UpdateDescription, "text/html", null);
viewPager = (ViewPager) findViewById(R.id.viewpager_layout);
// Pass results to ViewPagerAdapter Class
adapter = new ViewPagerAdapter(UpdateSingleItemViewActivity.this, Cardiology_updates.FinalLocalDataList);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
}
}
its Corrosponding adapter:
package com.AAAAA.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import com.AAAAA.AAAAA.Cardiology_updates;
import com.AAAAA.AAAAA.R;
import com.AAAAA.imageloader.ImageLoader;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;
public class ViewPagerAdapter extends PagerAdapter {
String UpdateTile;
String UpdateDescription;
//String population;
String UpdateImage;
String position;
LayoutInflater inflater;
Context context;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
//HashMap<String, String> resultp = new HashMap<String, String>();
ArrayList<HashMap<String,String>> filterData;
public ViewPagerAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.data);
}
#Override
public int getCount() {
return filterData.size();
}
public Object getItem(int position) {
return filterData.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
WebView webview;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
//resultp =data.get(position);
webview=(WebView)itemView.findViewById(R.id.webview1);
//webview.setText(webview[position]);
webview.loadData(filterData.get(position).get(Cardiology_updates.UpdateDescription), "text/html", null);
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((LinearLayout) object);
}
}
When used custom adapter always try to implement ViewHolder design pattern for ListView performance and use custom filter function instead Filterable implementation :
Custom filter funcation required two array list one is filterable data list and another one is for orignal data list :
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(orignalData);
}else{
for (HashMap<String,String> row: orignalData) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
Example :
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
adapter.filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
}
});
public class UpdatesAdapterList extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String,String>> filterData;
private ArrayList<HashMap<String,String>> orignalData;
public ImageLoader imageLoader;
public UpdatesAdapterList(Context context,ArrayList<HashMap<String, String>> orignalData) {
this.context = context;
this.orignalData = orignalData;
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.orignalData);
imageLoader = new ImageLoader(this.context);
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
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.listview_updateitem, null);
holder.UpdateTitle = (TextView) convertView.findViewById(R.id.txtUpdatetitle);
holder.UpdateImage = (ImageView) convertView.findViewById(R.id.list_UpdateImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.UpdateTitle.setText(filterData.get(position).get(Cardiology_updates.UpdateTitle));
imageLoader.DisplayImage(filterData.get(position).get(Cardiology_updates.UpdateImage), holder.UpdateImage);
// Capture ListView item click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", filterData.get(position).get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", filterData.get(position).get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",filterData.get(position).get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", filterData.get(position).get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
});
return convertView;
}
class ViewHolder{
TextView UpdateTitle;
ImageView UpdateImage;
}
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(orignalData);
}else{
for (HashMap<String,String> row: orignalData) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
}

how to implement search functionality in Gridview in android

In my application I have search tab which display images with their name in grid view and now I want to implement search functionality. I have been searching in google for past two days but I didn't get any solution. Any idea or tutorial 0r how can I achieve this?
Anyone help me with this.
Thanks in advance.
mainactivity
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.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import com.example.diceapp.R;
public class SearchActivity extends Activity
{
JSONArray results;
JSONObject jobj;
SearchCustomAdapter adapter1;
ImageButton ib;
ArrayList<String> a1,a2,a3,a4;
ArrayList<String> name=new ArrayList<String>();
ArrayList<String> description=new ArrayList<String>();
ArrayList<String> image=new ArrayList<String>();
ArrayList<String> price=new ArrayList<String>();
Button add;
String pid;
GridView gView;
EditText src;
int textlength = 0;
ArrayList<String> p_name = new ArrayList<String>();
ArrayList<String> p_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
a1=new ArrayList<String>();
a2=new ArrayList<String>();
a3=new ArrayList<String>();
a4=new ArrayList<String>();
src=(EditText)findViewById(R.id.srcetxt);
/*src.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
SearchActivity.this.adapter1.getFilter().filter(cs);
}
#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
}
});*/
new Searchtask().execute();
gView = (GridView)findViewById(R.id.gridView1);
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);
}
});
ib=(ImageButton)findViewById(R.id.imageButton1);
}
private class Searchtask extends AsyncTask<String, String, JSONObject>
{
private ProgressDialog pDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(SearchActivity.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("http:link.php");
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
System.out.println("---------------return name 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);
name.add(c.getString("name"));
image.add(c.getString("image"));
price.add(c.getString("price"));
description.add(c.getString("Description"));
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter1 = new SearchCustomAdapter(getApplicationContext(), R.layout.gridlistimg, name, image,description,price);
gView.setAdapter(adapter1);
}
}
}
baseadapter class
package com.example.diceapp.search;
import java.util.ArrayList;
import android.content.Context;
import android.content.Intent;
import android.sax.StartElementListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.example.diceapp.AAAMainActivity;
import com.example.diceapp.R;
import com.example.diceapp.category.ImageLoader;
public class SearchCustomAdapter extends BaseAdapter
{
Context context;
LayoutInflater inflater;
ArrayList<String> aaaa1,bbbb1,cccc1;
ArrayList<String> c_pname;
ArrayList<String> c_pimage;
ArrayList<String> c_pprice;
ArrayList<String> c_pdescription;
String[] data_text;
String[] data_image;
ImageLoader iloader;
public SearchCustomAdapter(Context c, int productDescribe,ArrayList<String> pname, ArrayList<String> pimage,
ArrayList<String> productdescription, ArrayList<String> pprice)
{
// TODO Auto-generated constructor stub
this.context=c;
this.c_pname=pname;
this.c_pprice=pprice;
this.c_pdescription=productdescription;
this.c_pimage=pimage;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
iloader= new ImageLoader(context.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return c_pname.size();
//return data_text.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int pos) {
// TODO Auto-generated method stub
//return c_pname.indexOf(getItem(pos));//arg0;
return pos;
}
#Override
public View getView(final 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_search_activity, parent, false);
vh=new ViewHolder();
vh.pname=(TextView)row.findViewById(R.id.product_name);
vh.pprice=(TextView)row.findViewById(R.id.textView2);
vh.image1=(ImageView) row.findViewById(R.id.imageView1);
vh.btn=(Button)row.findViewById(R.id.p_custom_tv);
/*row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
System.out.println("outside on click"+position);
ArrayList<String> sendingary=new ArrayList<String>();
sendingary.add(c_pname.get(position));
sendingary.add(c_pprice.get(position));
sendingary.add(c_pimage.get(position));
sendingary.add(c_pdescription.get(position));
Intent cp=new Intent(context.getApplicationContext(),product_details.class);
cp.putStringArrayListExtra("aryvalue", sendingary);
cp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(cp);
}
});*/
row.setTag(vh);
}
else
{
vh = (ViewHolder) row.getTag();
row=convertView;
}
vh.pname.setText(c_pname.get(position));
vh.pprice.setText("KD "+c_pprice.get(position));
iloader.DisplayImage(c_pimage.get(position), vh.image1);
return row;
}
public static class ViewHolder
{
TextView pname,pprice;
ImageView image1;
Button btn;
}
public SearchCustomAdapter getFilter() {
// TODO Auto-generated method stub
return null;
}
}
If you use ArrayAdapter as your gridview's adapter, you can override getFilter() method and return your own Filter, which is able to filter items according to entered text. See e.g. this link to learn how to work with Filter. Good luck. :-)
Hi I just edit your code please replace and check it
SearchActivity.java
import java.util.ArrayList;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
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.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
public class SearchActivity extends Activity {
JSONArray results;
JSONObject jobj;
SearchCustomAdapter adapter1;
ImageButton ib;
ArrayList<String> a1, a2, a3, a4;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> description = new ArrayList<String>();
ArrayList<String> image = new ArrayList<String>();
ArrayList<String> price = new ArrayList<String>();
Button add;
String pid;
GridView gView;
EditText src;
int textlength = 0;
ArrayList<String> p_name = new ArrayList<String>();
ArrayList<String> p_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
a1 = new ArrayList<String>();
a2 = new ArrayList<String>();
a3 = new ArrayList<String>();
a4 = new ArrayList<String>();
src = (EditText) findViewById(R.id.srcetxt);
src.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
if (src.getText().toString().trim().length() > 0) {
applySearch(src.getText().toString().trim());
} else {
adapter1.setC_pname(name);
adapter1.setC_pdescription(description);
adapter1.setC_pimage(image);
adapter1.setC_pprice(price);
adapter1.notifyDataSetChanged();
}
}
});
new Searchtask().execute();
gView = (GridView) findViewById(R.id.gridView1);
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);
}
});
ib = (ImageButton) findViewById(R.id.imageButton1);
}
private class Searchtask extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchActivity.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("http:link.php");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
System.out.println("---------------return name 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);
name.add(c.getString("name"));
image.add(c.getString("image"));
price.add(c.getString("price"));
description.add(c.getString("Description"));
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter1 = new SearchCustomAdapter(getApplicationContext(), R.layout.gridlistimg, name, image, description, price);
gView.setAdapter(adapter1);
}
}
private void applySearch(String searchStr) {
ArrayList<String> searchname = new ArrayList<String>();
ArrayList<String> searchdescription = new ArrayList<String>();
ArrayList<String> searchimage = new ArrayList<String>();
ArrayList<String> searchprice = new ArrayList<String>();
for (int i = 0; i < name.size(); i++) {
if (name.get(i).contains(searchStr)) {
searchname.add(name.get(i));
searchdescription.add(description.get(i));
searchimage.add(image.get(i));
searchprice.add(price.get(i));
}
}
adapter1.setC_pname(searchname);
adapter1.setC_pdescription(searchdescription);
adapter1.setC_pimage(searchimage);
adapter1.setC_pprice(searchprice);
adapter1.notifyDataSetChanged();
}
}
SearchCustomAdapter.java
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.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class SearchCustomAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<String> aaaa1, bbbb1, cccc1;
ArrayList<String> c_pname;
ArrayList<String> c_pprice;
ArrayList<String> c_pdescription;
ArrayList<String> c_pimage;
public void setC_pname(ArrayList<String> c_pname) {
this.c_pname = c_pname;
}
public void setC_pimage(ArrayList<String> c_pimage) {
this.c_pimage = c_pimage;
}
public void setC_pprice(ArrayList<String> c_pprice) {
this.c_pprice = c_pprice;
}
public void setC_pdescription(ArrayList<String> c_pdescription) {
this.c_pdescription = c_pdescription;
}
String[] data_text;
String[] data_image;
ImageLoader iloader;
public SearchCustomAdapter(Context c, int productDescribe, ArrayList<String> pname, ArrayList<String> pimage, ArrayList<String> productdescription, ArrayList<String> pprice) {
// TODO Auto-generated constructor stub
this.context = c;
this.c_pname = pname;
this.c_pprice = pprice;
this.c_pdescription = productdescription;
this.c_pimage = pimage;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
iloader = new ImageLoader(context.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return c_pname.size();
// return data_text.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int pos) {
// TODO Auto-generated method stub
// return c_pname.indexOf(getItem(pos));//arg0;
return pos;
}
#Override
public View getView(final 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_search_activity, parent, false);
vh = new ViewHolder();
vh.pname = (TextView) row.findViewById(R.id.product_name);
vh.pprice = (TextView) row.findViewById(R.id.textView2);
vh.image1 = (ImageView) row.findViewById(R.id.imageView1);
vh.btn = (Button) row.findViewById(R.id.p_custom_tv);
/*
* row.setOnClickListener(new OnClickListener() {
*
* #Override public void onClick(View arg0) {
*
* System.out.println("outside on click"+position);
*
*
* ArrayList<String> sendingary=new ArrayList<String>();
*
* sendingary.add(c_pname.get(position));
*
* sendingary.add(c_pprice.get(position));
*
* sendingary.add(c_pimage.get(position));
*
* sendingary.add(c_pdescription.get(position));
*
* Intent cp=new
* Intent(context.getApplicationContext(),product_details.class);
*
* cp.putStringArrayListExtra("aryvalue", sendingary);
*
* cp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
*
* context.startActivity(cp);
*
* } });
*/
row.setTag(vh);
} else {
vh = (ViewHolder) row.getTag();
row = convertView;
}
vh.pname.setText(c_pname.get(position));
vh.pprice.setText("KD " + c_pprice.get(position));
iloader.DisplayImage(c_pimage.get(position), vh.image1);
return row;
}
public static class ViewHolder {
TextView pname, pprice;
ImageView image1;
Button btn;
}
}

How to Filter data Date wise Location wiase in Given Example within same List

package com.nous.demoexample;
import static com.nous.demoexample.Constant.EIGTH_COLUMN;
import static com.nous.demoexample.Constant.FIFTH_COLUMN;
import static com.nous.demoexample.Constant.FIRST_COLUMN;
import static com.nous.demoexample.Constant.FOURTH_COLUMN;
import static com.nous.demoexample.Constant.SECOND_COLUMN;
import static com.nous.demoexample.Constant.SEVENTH_COLUMN;
import static com.nous.demoexample.Constant.SIXTH_COLUMN;
import static com.nous.demoexample.Constant.THIRD_COLUMN;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import com.paresh.demoexample.R;
public class MultiColumnActivity extends Activity implements OnClickListener {
private ArrayList<HashMap<String, String>> list;
Button filterButton;
Context context = this;
ListView lview;
// GridView lview;
final CharSequence[] items = { "Select all", " Date ", " Locationto",
" Client Name ", " Product code ", "Product Description",
"Location from", "Quantity", "Pallets" };
protected ArrayList<CharSequence> selectedInterests = new ArrayList<CharSequence>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
// lview = (GridView) findViewById(R.id.listview);
lview = (ListView) findViewById(R.id.listview);
filterButton = (Button) findViewById(R.id.filterbutton);
filterButton.setOnClickListener(this);
populateList();
listviewAdapter adapter = new listviewAdapter(this, list);
lview.setAdapter(adapter);
int lm = lview.getCount();
System.out.println(lm);
}
private void populateList() {
list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> temp = new HashMap<String, String>();
temp.put(FIRST_COLUMN, "DATE");
temp.put(SECOND_COLUMN, "LOCATION TO");
temp.put(THIRD_COLUMN, "CLIENT NAME");
temp.put(FOURTH_COLUMN, "PRODUCT CODE");
temp.put(FIFTH_COLUMN, "PRODUCT DESCRIPTION");
temp.put(SIXTH_COLUMN, "LOCATION FROM");
temp.put(SEVENTH_COLUMN, "QUANTITY");
temp.put(EIGTH_COLUMN, "PALLETS");
list.add(temp);
HashMap<String, String> temp1 = new HashMap<String, String>();
temp1.put(FIRST_COLUMN, "7 / 2 / 2013");
temp1.put(SECOND_COLUMN, "SW00-000");
temp1.put(THIRD_COLUMN, "Mercury Direct");
temp1.put(FOURTH_COLUMN, "MERCUR-A5WW2013-491-000-000-Loose");
temp1.put(FIFTH_COLUMN, "A5 WORLDWIDE HOLS 13 C");
temp1.put(SIXTH_COLUMN, "Warehouse");
temp1.put(SEVENTH_COLUMN, " 5000");
temp1.put(EIGTH_COLUMN, "1");
list.add(temp1);
HashMap<String, String> temp2 = new HashMap<String, String>();
temp2.put(FIRST_COLUMN, "7 / 2 / 2013");
temp2.put(SECOND_COLUMN, "DAH22A");
temp2.put(THIRD_COLUMN, "Hurtigruten Ltd");
temp2.put(FOURTH_COLUMN, "HURTI-NORWY13-000-000-000-10");
temp2.put(FIFTH_COLUMN, "NORWAY 2013");
temp2.put(SIXTH_COLUMN, "ShrinkWrap");
temp2.put(SEVENTH_COLUMN, " 4000");
temp2.put(EIGTH_COLUMN, "1");
list.add(temp2);
HashMap<String, String> temp3 = new HashMap<String, String>();
temp3.put(FIRST_COLUMN, "7 / 2 / 2013");
temp3.put(SECOND_COLUMN, "DAH22A/02");
temp3.put(THIRD_COLUMN, "Hurtigruten Ltd");
temp3.put(FOURTH_COLUMN, "HURTI-NORWY13-000-000-000-10");
temp3.put(FIFTH_COLUMN, "NORWAY 2013");
temp3.put(SIXTH_COLUMN, "ShrinkWrap");
temp3.put(SEVENTH_COLUMN, " 4000");
temp3.put(EIGTH_COLUMN, "1");
list.add(temp3);
HashMap<String, String> temp4 = new HashMap<String, String>();
temp4.put(FIRST_COLUMN, "7 / 2 / 2013");
temp4.put(SECOND_COLUMN, "DAH22A/02");
temp4.put(THIRD_COLUMN, "Hurtigruten Ltd");
temp4.put(FOURTH_COLUMN, "HURTI-NORWY13-000-000-000-10");
temp4.put(FIFTH_COLUMN, "NORWAY 2013");
temp4.put(SIXTH_COLUMN, "ShrinkWrap");
temp4.put(SEVENTH_COLUMN, " 4000");
temp4.put(EIGTH_COLUMN, "1");
list.add(temp4);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.filterbutton: {
showDialog();
break;
}
default:
break;
}
}
private void showDialog() {
// arraylist to keep the selected items
final ArrayList seletedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select The Fields");
/*
* boolean[] checkedInterests = new boolean[items.length]; int count =
* items.length;
*
* for (int i = 0; i < count; i++) { checkedInterests[i] =
* selectedInterests .contains(items[i]);
*
* }
*/
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
// indexSelected contains the index of item (of which
// checkbox checked)
#Override
public void onClick(DialogInterface dialog,
int indexSelected, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the
// selected items
// write your code when user checked the checkbox
seletedItems.add(indexSelected);
selectedInterests.add(items[indexSelected]); // by
// anup
} else if (seletedItems.contains(indexSelected)) {
// Else, if the item is already in the array, remove
// it
// write your code when user Uchecked the checkbox
seletedItems.remove(Integer.valueOf(indexSelected));
}
onChangeSelectedSelection();
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Your code when user clicked on OK
// You can write the code to save the selected item here
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Your code when user clicked on Cancel
}
});
AlertDialog dialog = builder.create();
dialog = builder.create();// AlertDialog dialog; create like this
// outside onClick
dialog.show();
}
protected void onChangeSelectedSelection() {
StringBuilder stringBuilder = new StringBuilder();
for (CharSequence selection : selectedInterests)
stringBuilder.append(selection + ",");
// filterButton.setText(stringBuilder.toString());
String input = selectedInterests.toString();
System.out.println(input);
if (input.contains("Date")) {
//here i want to display Date Only Listview
}
if(input.contains("Locationto")){
// here i want to display location to only in same list
}
}
}
Constant.java
package com.nous.demoexample;
public class Constant {
public static final String FIRST_COLUMN = "First";
public static final String SECOND_COLUMN = "Second";
public static final String THIRD_COLUMN = "Third";
public static final String FOURTH_COLUMN = "Fourth";
public static final String FIFTH_COLUMN = "Fifth";
public static final String SIXTH_COLUMN = "Sixth";
public static final String SEVENTH_COLUMN = "Seventh";
public static final String EIGTH_COLUMN = "Eighth";
}
listvieadapter.java
package com.nous.demoexample;
import static com.nous.demoexample.Constant.FIRST_COLUMN;
import static com.nous.demoexample.Constant.FOURTH_COLUMN;
import static com.nous.demoexample.Constant.SECOND_COLUMN;
import static com.nous.demoexample.Constant.THIRD_COLUMN;
import static com.nous.demoexample.Constant.FIFTH_COLUMN;
import static com.nous.demoexample.Constant.SIXTH_COLUMN;
import static com.nous.demoexample.Constant.SEVENTH_COLUMN;
import static com.nous.demoexample.Constant.EIGTH_COLUMN;
import java.util.ArrayList;
import java.util.HashMap;
import com.paresh.demoexample.R;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class listviewAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> list;
Activity activity;
public listviewAdapter(Activity activity,
ArrayList<HashMap<String, String>> list) {
super();
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
TextView txtFourth, txtFifth, txtSixth, txtSeventh, txtEigth;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_row, null);
holder = new ViewHolder();
holder.txtFirst = (TextView) convertView
.findViewById(R.id.FirstText);
holder.txtSecond = (TextView) convertView
.findViewById(R.id.SecondText);
holder.txtThird = (TextView) convertView
.findViewById(R.id.ThirdText);
holder.txtFourth = (TextView) convertView
.findViewById(R.id.FourthText);
holder.txtFifth = (TextView) convertView
.findViewById(R.id.FifthText);
holder.txtSixth = (TextView) convertView
.findViewById(R.id.SixthText);
holder.txtSeventh = (TextView) convertView
.findViewById(R.id.SeventhText);
holder.txtEigth = (TextView) convertView
.findViewById(R.id.EigthText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> map = list.get(position);
holder.txtFirst.setText(map.get(FIRST_COLUMN));
holder.txtSe
cond.setText(map.get(SECOND_COLUMN));
holder.txtThird.setText(map.get(THIRD_COLUMN));
holder.txtFourth.setText(map.get(FOURTH_COLUMN));
holder.txtFifth.setText(map.get(FIFTH_COLUMN));
holder.txtSixth.setText(map.get(SIXTH_COLUMN));
holder.txtSeventh.setText(map.get(SEVENTH_COLUMN));
holder.txtEigth.setText(map.get(EIGTH_COLUMN));
return convertView;
}
}
I am able to display all data date wise location wise and ....together But i want to Filter data -date wise location means if we check in location wise then it should Print location Only if filter date wise it should display date ..in list please help i have tired much But unable to do this....i have create check Box for select option date wise filter , location wise filter so please check my code if u want i can send complete code .
If you are using EditText to search then you have to write your own filter method..here is an example Custom ListView Search .
you have to change filter method something like this.
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (WorldPopulation wp : arraylist) {
if(isDate)
{
if (wp.getDate().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlist.add(wp);
}
}else{
if(wp.getLocation().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlist.add(wp);
}
}
}
}
notifyDataSetChanged();
}

Adapter ListView item click event

Is this ok to do?
#Override
protected void onPostExecute(final ChannelPair p) {
HiddenChannelsListAdapter adapter = new HiddenChannelsListAdapter(p.ctx, p.channelList);
p.lv.setAdapter(adapter);
p.lv.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Log.i("CLICKED ON LV ITEM", "YEA");
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
Its not actually triggering the event I think. At least no item is Selected?
UPDATE
So I removed the stuff from the asyncTask and added it to a new Thread, so now its all in the same file. But still, I cannot get the clicks from the items
package com.example.tvrplayer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class ChannelsDialogPreference extends DialogPreference {
public static Context ctx;
// Activity activity;
public ChannelsDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
this.ctx = context;
}
#Override
protected View onCreateDialogView() {
// Set loading spinner
// Start looking for channels
// When complete, show channels
LayoutInflater inflater = ((SettingsActivity) ctx).getLayoutInflater();
final View vw = inflater.inflate(R.layout.channel_content_view, null);
// Do this in a new Thread
Thread thread = new Thread()
{
#Override
public void run() {
try {
final JSONArray channels;
String username = null;
String linkid = null;
final String apiurl = "http://192.168.2.136:8080";
final String channelID = null;
final DatabaseHandler db = new DatabaseHandler(ctx);
List<User> users = db.getAllUsers();
for (User cn : users) {
linkid = cn.getLinkID();
username = cn.getUserName();
}
db.close();
final ArrayList< HashMap < String, String > > channelList = new ArrayList < HashMap < String, String > > ();
try {
if ( channelID != null ) {
channels = Json.getJson(apiurl + "/rest/channel/"+ linkid +"/"+ username + "/" + channelID, "GET");
Log.i("CHANNELS", channels.toString());
for (int i=0; i < channels.length(); i++) {
JSONObject json_data = channels.getJSONObject(i);
String name = json_data.getString("Name");
String channelid = json_data.getString("ChannelID");
HashMap<String, String> channelObject = new HashMap<String, String>();
// if ( json_data.getString("ParentPath") == "" ) {
channelObject.put("id", channelid);
channelObject.put("name", name);
channelList.add(channelObject);
// }
}
} else {
channels = Json.getJson(apiurl + "/rest/channel/"+ linkid +"/"+ username, "GET");
Log.i("CHANNELS", channels.toString());
for (int i=0; i < channels.length(); i++) {
JSONObject json_data = channels.getJSONObject(i);
String name = json_data.getString("Name");
String channelid = json_data.getString("ChannelID");
HashMap<String, String> channelObject = new HashMap<String, String>();
Log.i("CHANNEL LEN", ""+ json_data.getString("ParentID").length());
if ( json_data.getString("ParentID").length() < 32 ) {
channelObject.put("id", channelid);
channelObject.put("name", name);
channelList.add(channelObject);
}
}
}
((Activity)ctx).runOnUiThread(new Runnable() {
public void run() {
HiddenChannelsListAdapter adapter = new HiddenChannelsListAdapter(ctx, channelList);
ListView lv = (ListView) vw.findViewById(R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
Log.i("CLICKED ON LV ITEM", "YEA");
}
});
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
return vw;
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
persistBoolean(positiveResult);
}
#Override
public void onClick (DialogInterface dialog, int which)
{
super.onClick(dialog, which);
//
Log.v("which", Integer.toString(which));
//
if(which == -1) { //Clear all
// new ChannelHandler().execute(apiurl, username, linkid, vw, ctx, channelID);
}
}
}
This part is where the clicks are bound:
((Activity)ctx).runOnUiThread(new Runnable() {
public void run() {
HiddenChannelsListAdapter adapter = new HiddenChannelsListAdapter(ctx, channelList);
ListView lv = (ListView) vw.findViewById(R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
Log.i("CLICKED ON LV ITEM", "YEA");
}
});
}
});
This causes a change on UIthread which should not be called from the background thread. Remeber never to update or notifychange() a listView from the backgound thread

Android, ListView Searching/Filter -> Duplicate entries

AS the title explains, I'm having trouble with filtering/searching my listview. When I try to search for lets say "A", the listView displays A-31 two times, A-32 two times and so on. Does anyone have an idea why this occurs?
package hpliu.grupp2;
import android.content.Intent;
import android.os.Bundle;
import android.os.Debug;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TableRow;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.ListActivity;
import android.app.Activity;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class SearchRoomActivity extends ListActivity {
private EditText filterText = null;
SimpleAdapter menu = null;
ListView lv = null;
static final String[] AHalls = new String[] { "A-31", "A-32", "A-33",
"A-34", "A-35", "A-36", "A-37" };
String[] from = new String[] { "roomName", "buildingName" };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_room);
createCampusList("Campus Valla, Linköping",
createHashMap(AHalls, "A Huset"));
// filterText = (EditText) findViewById(R.id.search_box);
// filterText.addTextChangedListener(filterTextWatcher);
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
menu.getFilter().filter(s);
}
};
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
try {
#SuppressWarnings("unchecked")
HashMap<String, String> toHash = (HashMap<String, String>) this
.getListAdapter().getItem(position); // {text1 = "A-31",
// text2 = "Herp"};
Toast.makeText(
this,
"Searching for... " + " "
+ toHash.get("roomName").toString(),
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<HashMap<String, String>> createHashMap(String[] Halls,
String Building) {
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < Halls.length; i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(from[0], Halls[i]);
map.put(from[1], Building);
fillMaps.add(map);
}
return fillMaps;
}
public List<HashMap<String, String>> createHashMap(String[] Halls,
String[] Buildings) {
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < Halls.length; i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(from[0], Halls[i]);
map.put(from[1], Buildings[i]);
fillMaps.add(map);
}
return fillMaps;
}
public void createCampusList(String campusHeader,
List<HashMap<String, String>> fillMaps) {
int[] to = new int[] { R.id.roomName, R.id.buildingName };
menu = new SimpleAdapter(this, fillMaps, R.layout.list_item, from, to);
setListAdapter(menu);
lv = getListView();
lv.setTextFilterEnabled(true);
}
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
}
If you filter an adapter that has two strings in each item the filter will pass through the adapter twice. This is why you have multiples. If you had three strings in each you could possibly get three duplicate items.
One solution I found online was to create a custom SimpleAdapter and check for duplicates before populating your ListView.
My custom listview faced the same problem.
The superclass of listview doesn't know that you've changed the size when you have filtered. This means getCount() will return the original size of the array, which is understandably larger than your filtered array. So you must override getCount() function to return the size of filtered array, not the original array. After that, duplicated items gone.
#Override
public int getCount() {
return filter_array.size();
}
#Override
public Object getItem(int position) {
return filter_array.get(position);
}

Categories

Resources