Android 如何在listview中设置json解析数据,然后在其中添加搜索功能

Android 如何在listview中设置json解析数据,然后在其中添加搜索功能,android,android-4.0-ice-cream-sandwich,Android,Android 4.0 Ice Cream Sandwich,我是android新手,希望在listview中解析json数据,然后在功能上添加搜索,但我不知道如何添加搜索 Java类是: 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 f

我是android新手,希望在listview中解析json数据,然后在功能上添加搜索,但我不知道如何添加搜索

Java类是:

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

}

}
公共类AndroidJSONParsingActivity扩展了ListActivity{
//发出请求的url
专用静态字符串url=”http://10.0.2.2/quick/punk.php";
//JSON节点名称
私有静态最终字符串标记_CUSTOMER=“CUSTOMER”;
私有静态最终字符串TAG\u CUSTOMER\u CODE=“CUSTOMER\u CODE”;
私有静态最终字符串TAG\u CUSTOMER\u NAME=“CUSTOMER\u NAME”;
私有静态最终字符串TAG\u CUSTOMER\u MOBILE=“CUSTOMER\u MOBILE”;
私有静态最终字符串TAG\u CUSTOMER\u ADDRESS=“CUSTOMER\u ADDRESS”;
//联系JSONArray
JSONArray客户=null;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//ListView的Hashmap
ArrayList contactList=新建ArrayList();
//创建JSON解析器实例
JSONParser jParser=新的JSONParser();
//从URL获取JSON字符串
JSONObject json=jParser.getJSONFromUrl(url);
试一试{
//获取联系人数组
Customer=json.getJSONArray(TAG_Customer);
//通过所有触点循环
对于(int i=0;ivalue
地图放置(标签、客户代码、客户代码);
地图放置(标签、客户名称、客户名称);
地图放置(标记客户移动,客户移动);
地图放置(标记客户地址、客户地址);
//将哈希列表添加到ArrayList
联系人列表。添加(地图);
}
}捕获(JSONException e){
e、 printStackTrace();
}
/**
*将解析的JSON数据更新到ListView中
* */
ListAdapter=新的SimpleAdapter(此,contactList,
R.layout.list_项目,
新字符串[]{TAG_CUSTOMER_CODE,TAG_CUSTOMER_NAME,TAG_CUSTOMER_MOBILE,TAG_CUSTOMER_ADDRESS},新int[]{
R.id.code、R.id.name、R.id.mobile、R.id.address});
setListAdapter(适配器);
}
}
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"/>


我想要的是,当用户在文本框中键入某个内容时,应该在列表中的数据中搜索该内容。有谁能告诉我如何实现它吗?

使用自定义列表适配器在listview中显示项目。在顶部显示编辑文本。 用于自定义列表视图

用于搜索listview。

用于自定义搜索 . 我建议您使用带有过滤器的自定义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>

修改,以便在for循环中添加json数据。我已在此处设置了搜索条件“客户id”。您可以根据需要更改此条件。这段代码经过测试,可以正常工作。希望有人能给出更好的代码。希望这能对您有所帮助。

当我们将json数据解析到listview中时,我们会将列表视图的id设置为(android:id=“@android:id/list”)……但要从列表中搜索,我需要列表的id,比如(lv=(listview)findviewbyid(R.id.(*))代替star,我需要listview id。要在listview上搜索,您只需根据edittext中输入的内容比较/过滤listview数据。根据用户在edittext中的输入在listview中显示新数据。如果listview显示的是名称列表,则在用户在edittext中键入时获取数据,并将其与listview数据进行比较,并将更改和显示项通知适配器。我的要求是获取列表id。“@android:id/list”如何解决此问题。为什么要使用列表id进行搜索?Listview显示适配器提供的数据。您所要做的就是基于搜索提供数据,并通知适配器数据已更改。
   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;
}
}
  <?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>
   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());




    }
}