0

リストビューに対してフィルター検索を行っています。リストビュー コードは正常に実行されています。edittext オブジェクトを置いて、フィルタ検索を行います。どうすればこれを作ることができますか? 私のコードは以下のとおりです。

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;

}

}

これらのコードの onTextChanged メソッドには何を書く必要がありますか? 調べましたが、このクラスのコードは見つかりませんでした。または私は編集しませんでした。

4

2 に答える 2

0

以下のコードで試してみてください。

you must integrate this line .. where you are setting adapter .

listView.setAdapter(new MyAddapter(this));

                    array_sort.clear();
                    array_sort.addAll(Service_Listitems); 

次に、以下の行を使用します。

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

                    }
                });;

編集

ArrayList<CoordItem> Service_Listitems= new ArrayList<CoordItem>();  

private ArrayList<Object> array_sort = new ArrayList<Object>();  

または、以下のように使用することもできます

   private ArrayList<CoordItem> array_sort = new ArrayList<CoordItem>();  
于 2013-04-02T09:14:13.003 に答える
0

リストビューで検索するには、こちらのリンクを確認してください。

AndroidでEditTextを入力するときにListViewデータをフィルタリングするにはどうすればよいですか

カスタム検索を行いたい場合は、以下のコードを使用できます

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>

主な活動

 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 クラス - すべてのデータをハッシュマップに保持します

 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());

 }
}
于 2013-04-02T09:16:30.657 に答える