-2

Edit: this answer is not suitable for me , i need more answer according to my condition, Thanks

How to search with custom listview when I call list view I don't pass array with it. Now I want to perform search on Name and mobile number, please help how could I achieve it? name and mobile number have check box , if name checkbox is select then search name if mobile number checkbox is checked then search mobile number

public class AndroidJSONParsingActivity extends ListActivity {

// JSON Node names
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ID = "id";
private static final String TAG_PHONE_MOBILE = "mobile";
EditText search;
int textlength=0;
ListView lv;
 ArrayList<String> text_sort = new ArrayList<String>();
 ArrayList<Integer> image_sort = new ArrayList<Integer>();
 ListViewAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    //access the controls 
    showList();
    CheckBox Name = (CheckBox) findViewById(R.id.checkBox1);
    CheckBox Mobile = (CheckBox) findViewById(R.id.checkBox2);

    if(Name.isChecked()==true){
        //search on name
    }
    if(Mobile.isChecked()==true){
        //search on mobile
    }
    Button addnew = (Button) findViewById(R.id.btnAddNew);
    // selecting single ListView item
            lv = getListView();
    addnew.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(getApplicationContext(), Insrt.class);
            startActivity(intent);
        }
    });
    search = (EditText)findViewById(R.id.etSearch);
    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) {

            adapter.getFilter().filter(s);
            adapter.notifyDataSetChanged();
        }
        });


}



private void showList() {
    // TODO Auto-generated method stub
    ListAdapter adapter = new ListViewAdapter(this);
    setListAdapter(adapter);



    // Launching new screen on Selecting Single ListItem
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long ids) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
            String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
            String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
            String id = ((TextView) view.findViewById(R.id.id)).getText().toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_EMAIL, cost);
            in.putExtra(TAG_PHONE_MOBILE, description);
            in.putExtra(TAG_ID, id);
            startActivity(in);

        }
    });
}





}

now i want to perform search on NAME and mobile number, please help how i did it?, please help

 public class ListViewAdapter extends ArrayAdapter {
private Filter filter;

public ListViewAdapter(Context context, int textViewResourceId) {
    super(context, textViewResourceId);
    // TODO Auto-generated constructor stub
}
@Override
public Filter getFilter()
{
    if (filter == null)
        filter = new PkmnNameFilter();

    return filter;
}
// url to make request
private static String url = "https://abc.net/api/api/employees/";
// JSON Node names
ArrayList<String> TAG_ID= new ArrayList<String>();
ArrayList<String> TAG_NAME= new ArrayList<String>();
ArrayList<String> TAG_EMAIL= new ArrayList<String>();
ArrayList<String> TAG_PHONE_MOBILE= new ArrayList<String>();
static Context context;
JSONArray employee = null;
String id,name,email,mobile;
ArrayList<Integer> close =new ArrayList<Integer>();
private Activity activity;
ViewHolder view;

//constructor
    public ListViewAdapter(Activity activity) 
    {
    super(context, 0);
    this.activity = activity;

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);



    try {
        // Getting Array of Employee
        employee = json.getJSONArray("Employee");

        // looping through All Employee
        for(int i = 0; i < employee.length(); i++)
        {
        JSONObject c = employee.getJSONObject(i);

            // Storing each json item in variable
            id = String.valueOf(c.getInt("Id"));
            name = c.getString("Name");
            email = c.getString("Email");
            mobile = c.getString("Mobile");

            //adding all get values into array
            if(name!="null"&&mobile!="null"){
            TAG_NAME.add(name);
            TAG_ID.add(id);
            TAG_EMAIL.add(email);
            TAG_PHONE_MOBILE.add(mobile);
            close.add(R.drawable.close);
            }


        }
    } catch (JSONException e) {
        e.printStackTrace();
    }



}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return TAG_NAME.size();
}

@Override
public Object getItem(int paramInt) {
    // TODO Auto-generated method stub
    return TAG_NAME.size();
}

@Override
public long getItemId(int paramInt) {
    // TODO Auto-generated method stub
    return 0;
}

public static class ViewHolder {
    public ImageView deleteButtonImg;
    public TextView name,email,mobile,id;



}

@Override
public View getView(final int paramInt, View paramView, final ViewGroup paramViewGroup) {
    // TODO Auto-generated method stub

    LayoutInflater inflator = activity.getLayoutInflater();
    if (paramView == null) {
        view = new ViewHolder();
        paramView = inflator.inflate(R.layout.list_item, null);

        view.name = (TextView) paramView.findViewById(R.id.name);
        view.email = (TextView) paramView.findViewById(R.id.email);
        view.mobile = (TextView) paramView.findViewById(R.id.mobile);
        view.id = (TextView) paramView.findViewById(R.id.id);
        view.deleteButtonImg = (ImageView) paramView.findViewById(R.id.ibclose);
        paramView.setTag(view);


    } else {
        view = (ViewHolder) paramView.getTag();
    }

    view.name.setText(TAG_NAME.get(paramInt));
    view.email.setText(TAG_EMAIL.get(paramInt));
    view.mobile.setText(TAG_PHONE_MOBILE.get(paramInt));
    view.deleteButtonImg.setImageResource(close.get(paramInt));
    view.id.setText(TAG_ID.get(paramInt));
    view.name.setFocusableInTouchMode(false);
    view.name.setFocusable(false);
    view.deleteButtonImg.setFocusableInTouchMode(false);
    view.deleteButtonImg.setFocusable(false);
    view.deleteButtonImg.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            DefaultHttpClient client = new DefaultHttpClient();
            SchemeRegistry registry = new SchemeRegistry();
            SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
            socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            registry.register(new Scheme("https", socketFactory, 443));
            SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
                        HttpDelete httpDelete = new HttpDelete("https://abc.net/api/api/employees/"+TAG_ID.get(paramInt));

                        httpDelete.setHeader("content-type", "application/json");
                        JSONObject data = new JSONObject();

                        try {
                            data.put("Id", TAG_ID.get(paramInt));

                        /*StringEntity entity = new StringEntity(data.toString());
                        httpPost.setEntity(entity);*/

                        HttpResponse response = httpClient.execute(httpDelete);
                        String responseString = EntityUtils.toString(response.getEntity());
                        //int workoutId = responseJSON.getInt("id");
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (ClientProtocolException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                         TAG_NAME.remove(paramInt);
                         TAG_EMAIL.remove(paramInt);
                         TAG_PHONE_MOBILE.remove(paramInt);
                         TAG_ID.remove(paramInt);
                         close.remove(paramInt);

            notifyDataSetChanged();

        }
    });

    return paramView;
}
private class PkmnNameFilter extends Filter
{

@Override
protected FilterResults performFiltering(CharSequence constraint) {
    FilterResults results = new FilterResults();
    // We implement here the filter logic
    if (constraint == null || constraint.length() == 0) {
        // No filter implemented we return all the list
        results.values = TAG_NAME;
        results.count = TAG_NAME.size();
    }
    else {
        // We perform filtering operation
        List<Object> nPlanetList = new ArrayList<Object>(TAG_NAME);

        for (Object p : TAG_NAME) {
            if (((Scheme) p).getName().toUpperCase().startsWith(constraint.toString().toUpperCase()))
                nPlanetList.add(p);
        }

        results.values = nPlanetList;
        results.count = nPlanetList.size();

    }
    return results;
}
  @Override
  protected void publishResults(CharSequence constraint, FilterResults results) {
       final ArrayList<String> localItems = (ArrayList<String>) results.values;
          notifyDataSetChanged();
          clear();
          for (Iterator<String> iterator = localItems.iterator(); iterator
                  .hasNext();) {
              String gi = (String) iterator.next();
              add(gi);
          }
  }
}

}

I searched on google but I didn't understand how to implement in this ?

2 Answers2

1

You need to pass the string that is being typed in editext to your filter

youradapter.getFilter().filter(s);
youradapter.notifyDataSetChanged();

Override getFilter() and performFiltering(params) in your adapter class

  @Override
  public Filter getFilter() {
   return new Filter() {
        @Override
       protected void publishResults(CharSequence constraint, FilterResults results)                  {
           if (results != null && results.count >= 0) {
              //set reeulst
           } else {
               // set original values
           }

           notifyDataSetInvalidated();
       }



      @Override
       protected FilterResults performFiltering(CharSequence constraint) {
           FilterResults result = new FilterResults();
           if (!TextUtils.isEmpty(constraint)) {
                  ArrayList<type> foundItems = new ArrayList<type>();
                       //do something
                       //filter resutls 
                 }

               result.count = foundItems.size();//search results found return count
               result.values = foundItems;// return values

           else
           {
               result.count=-1;// no search results found
           }
              return  result;
      } 

Edit:

  public class MainActivity extends Activity {
EditText search;
ListView lv;
CustomAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv=(ListView) findViewById(R.id.lv);
    adapter = new CustomAdapter(this,0);
    search = (EditText)findViewById(R.id.editText1);
    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) {

            adapter.getFilter().filter(s);
            adapter.notifyDataSetChanged();

        }
        });


}

  class CustomAdapter extends ArrayAdapter
  {
public CustomAdapter(Context context, int textViewResourceId) {
    super(context, textViewResourceId);
    // TODO Auto-generated constructor stub
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    return super.getView(position, convertView, parent);
}

@Override
public Filter getFilter() {
    // TODO Auto-generated method stub
    return super.getFilter();
}   
    }
    }

activity_main.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity" >

 <EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:ems="10" />

 <ListView
    android:id="@+id/lv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/editText1" >

  </ListView>  
  </RelativeLayout>

Edit :

Heres's the link of the working code

Search in ListView with EditText

I don't know if someone will code for you. But if you try you should be able to make changes to implement the same in your code..

enter image description here

enter image description here

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • there don't have getFilter option –  Apr 12 '13 at 07:04
  • you need to extend arrayadapter than baseadapter. http://developer.android.com/reference/android/widget/ArrayAdapter.html. ArrayAdapter a concrete BaseAdapter that is backed by an array of arbitrary objects. Check the link in the answer above. – Raghunandan Apr 12 '13 at 07:05
  • show what you have implemented along with logcat by editing your question. The sample in the link works and i have tested it on my device – Raghunandan Apr 12 '13 at 07:42
  • please join this chat http://chat.stackoverflow.com/rooms/24164/discussion-between-rohit-and-tushar –  Apr 12 '13 at 07:53
  • m too close , please see this http://stackoverflow.com/questions/6492214/custom-filtering-arrayadapter-in-listview, but in this have 2 lists in my case what i do please give hint –  Apr 12 '13 at 10:21
  • now i have started bounty on my question, if u can give answer then please give, otherwise its ur choice @Raghunandan –  Apr 15 '13 at 10:04
  • 1
    its not about choice. I have given a working code that you can implement. you should modify according to your needs. If someone can give a working code by modifying yours they will be doing your job. – Raghunandan Apr 15 '13 at 10:15
  • i have implemented but not responding –  Apr 15 '13 at 10:36
  • i have totally implemented this http://www.mysamplecode.com/2012/07/android-listview-custom-layout-filter.html , but this is not working, i have taken new project for this that is also not working –  Apr 15 '13 at 10:37
  • What is the exact problem for which you want the solution? Just saying it is not working won't help. Find out what problem you are facing post the same. – Raghunandan Apr 15 '13 at 11:43
1

Rohit - Sorry, but at a glance, I see a number of potential problems. Without time to build and run your code, I can only guess about your specific requirements. I'll address the first two opportunities for re-factoring. My gut thinks you'll find the answer in the process.

First, you are calling a method called, "showList()" before your activity has initialized. (In my opinion, you should be calling this method later. For example, in onResume.)

Then you are creating local reference variables which will not be in scope after onCreate runs (which occurs one and only one time per instance).

BTW, I find this sort of problem much easier to solve when inline class definitions (e.g. new View.OnClickListener) resolve to a proper, named class and/or instances of the class are member variables. If such changes might create memory management issues, you can optimize after your program is working as a user would expect.

Good luck!

-Brandon

Brandon
  • 401
  • 3
  • 8