如何设置在ListView JSON解析数据,然后添加搜索功能在里面 [英] how to set json parsed data in a listview and then adding search functionality in it

查看:239
本文介绍了如何设置在ListView JSON解析数据,然后添加搜索功能在里面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Andr​​oid和要分析在ListView JSON数据,然后添加搜索功能吧,但我不知道如何添加搜索,
该javaa类

i am new to android and want to parse json data in a listview and then adding search functionally to it,but i dont know how to add search,
The javaa class is

public class AndroidJSONParsingActivity extends ListActivity {


// url to make request
private static String url = "http://10.0.2.2/quick/punk.php";

// JSON Node names
private static final String TAG_CUSTOMER = "Customer";
private static final String TAG_CUSTOMER_CODE = "customer_code";
private static final String TAG_CUSTOMER_NAME = "customer_name";
private static final String TAG_CUSTOMER_MOBILE = "customer_mobile";
private static final String TAG_CUSTOMER_ADDRESS = "customer_address";

// contacts JSONArray
JSONArray Customer = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

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

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

    try {
        // Getting Array of Contacts
        Customer = json.getJSONArray(TAG_CUSTOMER);

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

            // Storing each json item in variable
            String customer_code = c.getString(TAG_CUSTOMER_CODE);
            String customer_name = c.getString(TAG_CUSTOMER_NAME);
            String customer_mobile = c.getString(TAG_CUSTOMER_MOBILE);
            String customer_address = c.getString(TAG_CUSTOMER_ADDRESS);




            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_CUSTOMER_CODE, customer_code);
            map.put(TAG_CUSTOMER_NAME, customer_name);
            map.put(TAG_CUSTOMER_MOBILE, customer_mobile);
            map.put(TAG_CUSTOMER_ADDRESS, customer_address);


            // adding HashList to ArrayList
            contactList.add(map);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }


    /**
     * Updating parsed JSON data into ListView
     * */
    ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.list_item,
            new String[] { TAG_CUSTOMER_CODE, TAG_CUSTOMER_NAME,TAG_CUSTOMER_MOBILE,TAG_CUSTOMER_ADDRESS}, new int[] {
                    R.id.code, R.id.name,R.id.mobile,R.id.address});

    setListAdapter(adapter);

}

}

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"/>
<!-- Main ListView 
     Always give id value as list(@android:id/list)
-->

<Button
    android:id="@+id/button1"
    android:layout_width="50dip"
    android:layout_height="wrap_content"
    android:text="+" />

<ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

我要的是,当用户在文本框中东西,它应该被搜索的数据是存在的列表中。任何一个可以告诉我如何实现它?

What I want is that when user types something in the textbox, it should be searched in the data that is there in the list. Can any one tell me how to implement it?

推荐答案

使用自定义列表适配器来显示在列表视图项。显示在顶部的EDITTEXT。 对于自定义列表视图的http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/.

Use a Custom List adapter to display items in listview. Display a editText on the top. For custom Listview http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/.

有关搜索列表视图。 <一href="http://stackoverflow.com/questions/1645209/how-can-i-filter-listview-data-when-typing-on-edittext-in-android/13172848#13172848">How我可以过滤的ListView数据的EditText android的打字的时候。

For searching listview. How can I filter ListView data when typing on EditText in android.

有关自定义搜索 <一href="http://stackoverflow.com/questions/6383943/implement-search-on-a-custom-listview/13110015#13110015">implement搜索自定义列表视图。我建议你​​去搜索上的自定义列表视图与过滤器。

For custom search implement search on a custom listview. I suggest you to go with search on custom listview with filters.

修改

activity_main.xml

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>

MainActivity类

MainActivity Class

   public class MainActivity extends Activity {
 ArrayList<NewData> mTemp=new ArrayList<NewData>();
 ArrayList<NewData> mPostingData=new ArrayList<NewData>();
 ArrayList< NewData> mOri = new ArrayList<NewData>();

    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);
         search.addTextChangedListener(new TextWatcher() {

             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) {   
            mPostingData = mPpst;//contains class items data.
        }

     @Override
     public Filter 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();
             }



            @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到自定义列表适配器膨胀

list.xml to be inflated in custom list adapter

  <?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讲座保存所有数据的HashMap

NewData Class- Holds all data in hashmap

   public class NewData {
public static final String TAG_CUSTOMER_CODE = "customer_code";
public static final String TAG_CUSTOMER_NAME = "customer_name";
public static final String TAG_CUSTOMER_MOBILE = "customer_mobile";
public static final String TAG_CUSTOMER_ADDRESS = "customer_address";

   Hashtable newDatacus=new Hashtable();

    public NewData()
    {

        newDatacus.put(NewData.TAG_CUSTOMER_CODE,new String());
        newDatacus.put(NewData.TAG_CUSTOMER_ADDRESS,new String());
        newDatacus.put(NewData.TAG_CUSTOMER_NAME,new String());
        newDatacus.put(NewData.TAG_CUSTOMER_MOBILE,new String());
        newDatacus.put(NewData.TAG_CUSTOMER_ADDRESS,new String());




    }
}

修改,以便您在添加JSON数据的循环。我已经在这里搜索条件的客户ID。您可以根据自己的需要改变这一点。这code测试和它的作品。希望有人能提供更好的code。希望这可以帮助你。

Modify so that you add your json data in the for loop. I have made search criteria here customer id. You can change this according to your needs. This code is tested and it works. Hope someone can give a better code. Hope this helps you.

这篇关于如何设置在ListView JSON解析数据,然后添加搜索功能在里面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆