实施搜索筛选器从服务器中检索的JSON数据 [英] implementing search filter for data from server retrieved as JSON

查看:124
本文介绍了实施搜索筛选器从服务器中检索的JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从服务器中检索的JSON数据执行搜索过滤器
我所指向什么


  1. LINK1

  2. 链接2

我是什么能够做到

我能够通过添加一些数据给它进行搜索过滤器时,我认为简单的数组

ListOfContacts.java

 公共类ListOfContacts延伸活动{
    //声明变量
    的JSONObject的JSONObject;
    JSONArray jsonarray;
    ListView控件列表视图;
    ListViewAdapter适配器;
    ProgressDialog mProgressDialog;
    ArrayList的<&HashMap的LT;字符串,字符串>> ArrayList的;
    静态字符串NAME =等级;
    静态串旗=标志;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        //从listview_main.xml视图
        的setContentView(R.layout.listview_main);
        //定位listview_main.xml列表视图
        列表视图=(ListView控件)findViewById(R.id.listview);        //执行DownloadJSON的AsyncTask
        新DownloadJSON()执行();
    }    // DownloadJSON的AsyncTask
    私有类DownloadJSON扩展的AsyncTask<太虚,太虚,太虚> {        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            //创建一个progressdialog
            mProgressDialog =新ProgressDialog(ListOfContacts.this);
            //设置progressdialog称号
            //mProgressDialog.setTitle(\"Fetching信息);
            //设置progressdialog消息
            mProgressDialog.setMessage(正在加载...);
            mProgressDialog.setIndeterminate(假);
            //显示progressdialog
            mProgressDialog.show();
        }        @覆盖
        保护无效doInBackground(虚空...... PARAMS){
            //创建一个数组
            ArrayList的=新的ArrayList<&HashMap的LT;字符串,字符串>>();
            //从给定的URL地址JSON对象
            的JSONObject = JSONfunctions.getJSONfromURL(http://54.218.73.244:7004/DescriptionSortedPrice/);            尝试{
                //找到在JSON数组名
                jsonarray = jsonobject.getJSONArray(餐馆);                的for(int i = 0; I< jsonarray.length();我++){
                    HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
                    的JSONObject = jsonarray.getJSONObject(ⅰ);
                    // Retrive JSON对象
                    map.put(ListOfContacts.NAME,jsonobject.getString(PERSON_NAME));
                    map.put(ListOfContacts.FLAGhttp://54.218.73.244:7004/\"+jsonobject.getString(\"Image_Name));                    //设置JSON对象到数组
                    arraylist.add(地图);
                }
            }赶上(JSONException E){
                Log.e(错误,e.getMessage());
                e.printStackTrace();
            }
            返回null;
        }        @覆盖
        保护无效onPostExecute(无效参数){
            //将结果传递到ListViewAdapter.java
            适配器=新ListViewAdapter(ListOfContacts.this,ArrayList的);
            //适配器设置到ListView
            listview.setAdapter(适配器);
            //关闭progressdialog
            mProgressDialog.dismiss();
        }
    }
}


listview_main.xml

 <?XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:方向=垂直>    <! - Editext搜索 - >
    < EditText上机器人:ID =@ + ID / inputSearch
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:提示=搜索此处
        安卓的inputType =textVisiblePassword/>    < ListView控件
        机器人:ID =@ + ID /列表视图
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT>
    < /&的ListView GT;< / LinearLayout中>


ListViewAdapter.java

 公共类ListViewAdapter延伸BaseAdapter {    //声明变量
    上下文语境;
    LayoutInflater吹气;
    ArrayList的<&HashMap的LT;字符串,字符串>>数据;
    ImageLoader的ImageLoader的;
    HashMap的<字符串,字符串> resultp =新的HashMap<字符串,字符串>();    公共ListViewAdapter(上下文的背景下,
            ArrayList的<&HashMap的LT;字符串,字符串>>数组列表){
        this.context =背景;
        数据=数组列表;
        ImageLoader的=新ImageLoader的(上下文);
    }    @覆盖
    公众诠释的getCount(){
        返回data.size();
    }    @覆盖
    公共对象的getItem(INT位置){
        返回null;
    }    @覆盖
    众长getItemId(INT位置){
        返回0;
    }    公共查看getView(最终诠释的立场,观点convertView,父母的ViewGroup){
        //声明变量
        TextView的名称;
        ImageView的标志;        吹气=(LayoutInflater)上下文
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);        查看ItemView控件= inflater.inflate(R.layout.listview_item,父母,假);
        //获取位置
        resultp = data.get(位置);        //定位listview_item.xml的TextViews
        名字=(TextView中)itemView.findViewById(R.id.RestaurantNameID);
        标志=(ImageView的)itemView.findViewById(R.id.flag);        name.setText(resultp.get(MainActivity.NAME));
        imageLoader.DisplayImage(resultp.get(MainActivity.FLAG),旗);
        //捕获ListView项点击        返回ItemView控件;
    }
}


ImageLoader.java

 公共类ImageLoader的{    的MemoryCache的MemoryCache =新的MemoryCache();
    FileCache fileCache;
    私人地图< ImageView的,字符串> imageViews =集合
            .synchronizedMap(新的WeakHashMap< ImageView的,字符串>());
    ExecutorService的ExecutorService的;
    //处理程序,以显示在UI线程图片
    处理程序处理程序=新的处理程序();    公共ImageLoader的(上下文的背景下){
        fileCache =新FileCache(背景);
        ExecutorService的= Executors.newFixedThreadPool(5);
    }    最终诠释stub_id = R.drawable.ic_launcher;    公共无效DisplayImage(字符串URL,ImageView的ImageView的){
        imageViews.put(ImageView的,URL);
        位图位图= memoryCache.get(URL);
        如果(位图!= NULL)
            imageView.setImageBitmap(位图);
        其他{
            queuePhoto(URL,ImageView的);
            imageView.setImageResource(stub_id);
        }
    }    私人无效queuePhoto(字符串URL,ImageView的ImageView的){
        PhotoToLoad P =新PhotoToLoad(URL,ImageView的);
        executorService.submit(新PhotosLoader(P));
    }    私人位图getBitmap(字符串URL){
        文件F = fileCache.getFile(URL);        位图B =去codeFILE(F);
        如果(B!= NULL)
            返回b;        从网上下载//图片
        尝试{
            位图位图= NULL;
            URL =图片网址新的URL(网址);
            HttpURLConnection的康恩=(HttpURLConnection类)图片网址
                    .openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(真);
            InputStream为= conn.getInputStream();
            OutputStream的OS =新的FileOutputStream(F);
            Utils.CopyStream(是,OS);
            os.close();
            conn.disconnect();
            位=去codeFILE(F);
            返回位图;
        }赶上(Throwable的前){
            ex.printStackTrace();
            如果(前的instanceof的OutOfMemoryError)
                memoryCache.clear();
            返回null;
        }
    }    //德$ C $连拍影像的鳞它来减少内存消耗
    私人位图德codeFILE(文件f){
        尝试{
            //德code图像尺寸
            BitmapFactory.Options O =新BitmapFactory.Options();
            o.inJustDe codeBounds = TRUE;
            的FileInputStream流1 =新的FileInputStream(F);
            BitmapFactory.de codeStream(STREAM1,空,O);
            stream1.close();            //找到正确的比例值。它应该是2的幂。
            //推荐大小512
            最终诠释REQUIRED_SIZE = 70;
            INT width_tmp = o.outWidth,height_tmp = o.outHeight;
            int标= 1;
            而(真){
                如果(width_tmp / 2'; REQUIRED_SIZE
                        || height_tmp / 2'; REQUIRED_SIZE)
                    打破;
                width_tmp / = 2;
                height_tmp / = 2;
                规模* = 2;
            }            //德code。与inSampleSize
            BitmapFactory.Options O2 =新BitmapFactory.Options();
            o2.inSampleSize =规模;
            流2的FileInputStream =新的FileInputStream(F);
            位图位图= BitmapFactory.de codeStream(流2,空,O2);
            stream2.close();
            返回位图;
        }赶上(FileNotFoundException异常五){
        }赶上(IOException异常五){
            e.printStackTrace();
        }
        返回null;
    }    //任务队列
    私有类PhotoToLoad {
        公共字符串的URL;
        公共ImageView的ImageView的;        公共PhotoToLoad(字符串U,ImageView的我){
            URL = U;
            ImageView的= I;
        }
    }    类PhotosLoader实现Runnable {
        PhotoToLoad photoToLoad;        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad = photoToLoad;
        }        @覆盖
        公共无效的run(){
            尝试{
                如果(imageViewReused(photoToLoad))
                    返回;
                BMP位图= getBitmap(photoToLoad.url);
                memoryCache.put(photoToLoad.url,BMP);
                如果(imageViewReused(photoToLoad))
                    返回;
                BitmapDisplayer BD =新BitmapDisplayer(BMP,photoToLoad);
                handler.post(BD);
            }赶上(的Throwable日){
                th.printStackTrace();
            }
        }
    }    布尔imageViewReused(PhotoToLoad photoToLoad){
        字符串标记= imageViews.get(photoToLoad.imageView);
        如果(标记== NULL ||!tag.equals(photoToLoad.url))
            返回true;
        返回false;
    }    //用在UI线程来显示位图
    类BitmapDisplayer实现Runnable {
        位图位图;
        PhotoToLoad photoToLoad;        公共BitmapDisplayer(位图B,PhotoToLoad P){
            位= B;
            photoToLoad = P;
        }        公共无效的run(){
            如果(imageViewReused(photoToLoad))
                返回;
            如果(位图!= NULL)
                photoToLoad.imageView.setImageBitmap(位图);
            其他
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }    公共无效clearCache(){
        memoryCache.clear();
        fileCache.clear();
    }}


我的JSON结构

  {
  餐馆:[
    {
      Sl_no:1,
      PERSON_NAME:萨尔曼·汗
      IMAGE_NAME:image.jpg的
    },
    {
      Sl_no:2,
      PERSON_NAME:AmirKhan
      IMAGE_NAME:c92beeaf5ba50e65.jpg
    },
    {
      Sl_no:3,
      PERSON_NAME:卡尔,
      IMAGE_NAME:f2d835b73945ded2.jpg
    },

我是什么不能做:如何实现搜索过滤器,当我们从服务器检索数据并填充列表视图


{编辑}

 包com.example.datapostingproject;进口的java.util.ArrayList;
进口的java.util.HashMap;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.text.Editable;
进口android.util.Log;
进口android.widget.EditText;
进口android.widget.ListView;公共类ListOfContacts延伸活动{
    //声明变量
    的JSONObject的JSONObject;
    JSONArray jsonarray;
    ListView控件列表视图;
    ListViewAdapter适配器;
    ProgressDialog mProgressDialog;
    ArrayList的<&HashMap的LT;字符串,字符串>> ArrayList的;
    静态字符串NAME =等级;
    静态串旗=标志;
    的EditText mEditText;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        //从listview_main.xml视图
        的setContentView(R.layout.listview_main);
        //定位listview_main.xml列表视图
        列表视图=(ListView控件)findViewById(R.id.listview);
        mEditText =(EditText上)findViewById(R.id.inputSearch);
        //执行DownloadJSON的AsyncTask
        新DownloadJSON()执行();        mEditText =(EditText上)findViewById(R.id.inputSearch);
        mEditText.addTextChangedListener(新TextWatcher()
        {            公共无效afterTextChanged(编辑S)
            {            }            公共无效beforeTextChanged(CharSequence中,诠释开始,诠释计数后INT)
            {            }            公共无效onTextChanged(CharSequence中,诠释开始,诠释之前,诠释计数)
            {                ArrayList的<&HashMap的LT;字符串,字符串>> arrayTemplist =新的ArrayList<&HashMap的LT;字符串,字符串>>();
                。字符串搜索字符串= mEditText.getText()的toString();
                的for(int i = 0; I< arraylist.size();我++)
                {
                    字符串currentString = arraylist.get(I)获得(ListOfContacts.NAME);
                    如果(searchString.equalsIgnoreCase(currentString)
                    {
                        arrayTemplist.add(arraylist.get(I));
                    }
                }
                适配器=新ListViewAdapter(ListOfContacts.this,arrayTemplist);
                listview.setAdapter(适配器);
             }
            });
        }
    }    // DownloadJSON的AsyncTask
    类DownloadJSON扩展的AsyncTask<太虚,太虚,太虚> {        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            //创建一个progressdialog
            mProgressDialog =新ProgressDialog(ListOfContacts.this);
            //设置progressdialog称号
            //mProgressDialog.setTitle(\"Fetching信息);
            //设置progressdialog消息
            mProgressDialog.setMessage(正在加载...);
            mProgressDialog.setIndeterminate(假);
            //显示progressdialog
            mProgressDialog.show();
        }        @覆盖
        保护无效doInBackground(虚空...... PARAMS){
            //创建一个数组
            ArrayList的=新的ArrayList<&HashMap的LT;字符串,字符串>>();
            //从给定的URL地址JSON对象
            的JSONObject = JSONfunctions.getJSONfromURL(http://54.218.73.244:7004/DescriptionSortedPrice/);            尝试{
                //找到在JSON数组名
                jsonarray = jsonobject.getJSONArray(餐馆);                的for(int i = 0; I< jsonarray.length();我++){
                    HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
                    的JSONObject = jsonarray.getJSONObject(ⅰ);
                    // Retrive JSON对象
                    map.put(ListOfContacts.NAME,jsonobject.getString(PERSON_NAME));
                    map.put(ListOfContacts.FLAGhttp://54.218.73.244:7004/\"+jsonobject.getString(\"Image_Name));                    //设置JSON对象到数组
                    arraylist.add(地图);
                }
            }赶上(JSONException E){
                Log.e(错误,e.getMessage());
                e.printStackTrace();
            }
            返回null;
        }        @覆盖
        保护无效onPostExecute(无效参数){
            //将结果传递到ListViewAdapter.java
            适配器=新ListViewAdapter(ListOfContacts.this,ArrayList的);
            //适配器设置到ListView
            listview.setAdapter(适配器);
            //关闭progressdialog
            mProgressDialog.dismiss();
        }
    }
}



解决方案

在下面添加code中的OnCreate() ListOfContacts.java

的方法

  mEditText =(EditText上)findViewById(R.id.inputSearch);
        mEditText.addTextChangedListener(新TextWatcher()
        {            公共无效afterTextChanged(编辑S)
            {            }            公共无效beforeTextChanged(CharSequence中,诠释开始,诠释计数后INT)
            {            }            公共无效onTextChanged(CharSequence中,诠释开始,诠释之前,诠释计数)
            {                ArrayList的<&HashMap的LT;字符串,字符串>> arrayTemplist =新的ArrayList<&HashMap的LT;字符串,字符串>>();
                。字符串搜索字符串= mEditText.getText()的toString();
                的for(int i = 0; I< arraylist.size();我++)
                {
                    字符串currentString = arraylist.get(I)获得(ListOfContacts.NAME);
                    如果(searchString.equalsIgnoreCase(currentString)
                    {
                        arrayTemplist.add(arraylist.get(I));
                    }
                }
                适配器=新ListViewAdapter(ListOfContacts.this,arrayTemplist);
                listview.setAdapter(适配器);
             }
            });
        }

Implementing search filter for data from server retrieved as JSON What i refered

  1. link1
  2. link2

What i am able to do

I am able to perform search filter when i consider simple arrays by adding some data to it

ListOfContacts.java

public class ListOfContacts extends Activity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String NAME = "rank";
    static String FLAG = "flag";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main);


        // Locate the listview in listview_main.xml
        listview = (ListView) findViewById(R.id.listview);

        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(ListOfContacts.this);
            // Set progressdialog title
            //mProgressDialog.setTitle("Fetching the information");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7004/DescriptionSortedPrice/");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("restaurants");

                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(ListOfContacts.NAME, jsonobject.getString("Person_Name"));
                    map.put(ListOfContacts.FLAG, "http://54.218.73.244:7004/"+jsonobject.getString("Image_Name"));



                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(ListOfContacts.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }
}


listview_main.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="vertical" >

    <!-- Editext for Search -->
    <EditText android:id="@+id/inputSearch"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Search Here"
        android:inputType="textVisiblePassword"/>

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>


ListViewAdapter.java

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    ImageLoader imageLoader;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapter(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        imageLoader = new ImageLoader(context);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView name;
        ImageView flag;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.listview_item, parent, false);
        // Get the position
        resultp = data.get(position);

        // Locate the TextViews in listview_item.xml
        name = (TextView) itemView.findViewById(R.id.RestaurantNameID);
        flag = (ImageView) itemView.findViewById(R.id.flag);

        name.setText(resultp.get(MainActivity.NAME));
        imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
        // Capture ListView item click

        return itemView;
    }
}


ImageLoader.java

public class ImageLoader {

    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;
    // Handler to display images in UI thread
    Handler handler = new Handler();

    public ImageLoader(Context context) {
        fileCache = new FileCache(context);
        executorService = Executors.newFixedThreadPool(5);
    }

    final int stub_id = R.drawable.ic_launcher;

    public void DisplayImage(String url, ImageView imageView) {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null)
            imageView.setImageBitmap(bitmap);
        else {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }

    private void queuePhoto(String url, ImageView imageView) {
        PhotoToLoad p = new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);

        Bitmap b = decodeFile(f);
        if (b != null)
            return b;

        // Download Images from the Internet
        try {
            Bitmap bitmap = null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl
                    .openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            conn.disconnect();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex) {
            ex.printStackTrace();
            if (ex instanceof OutOfMemoryError)
                memoryCache.clear();
            return null;
        }
    }

    // Decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream stream1 = new FileInputStream(f);
            BitmapFactory.decodeStream(stream1, null, o);
            stream1.close();

            // Find the correct scale value. It should be the power of 2.
            // Recommended Size 512
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            FileInputStream stream2 = new FileInputStream(f);
            Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // Task for the queue
    private class PhotoToLoad {
        public String url;
        public ImageView imageView;

        public PhotoToLoad(String u, ImageView i) {
            url = u;
            imageView = i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;

        PhotosLoader(PhotoToLoad photoToLoad) {
            this.photoToLoad = photoToLoad;
        }

        @Override
        public void run() {
            try {
                if (imageViewReused(photoToLoad))
                    return;
                Bitmap bmp = getBitmap(photoToLoad.url);
                memoryCache.put(photoToLoad.url, bmp);
                if (imageViewReused(photoToLoad))
                    return;
                BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
                handler.post(bd);
            } catch (Throwable th) {
                th.printStackTrace();
            }
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad) {
        String tag = imageViews.get(photoToLoad.imageView);
        if (tag == null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    // Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;

        public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
            bitmap = b;
            photoToLoad = p;
        }

        public void run() {
            if (imageViewReused(photoToLoad))
                return;
            if (bitmap != null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}


My JSON Structure::

{
  "restaurants": [
    {
      "Sl_no": 1,
      "Person_Name": "salmanKhan",
      "Image_Name": "image.jpg"
    },
    {
      "Sl_no": 2,
      "Person_Name": "AmirKhan",
      "Image_Name": "c92beeaf5ba50e65.jpg"
    },
    {
      "Sl_no": 3,
      "Person_Name": "carl",
      "Image_Name": "f2d835b73945ded2.jpg"
    },

What i am not able to do : How to implement search filter when we retrieve Data from server and populate the list view


{EDIT}

package com.example.datapostingproject;

import java.util.ArrayList;
import java.util.HashMap;
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.util.Log;
import android.widget.EditText;
import android.widget.ListView;

public class ListOfContacts extends Activity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String NAME = "rank";
    static String FLAG = "flag";
    EditText mEditText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main);


        // Locate the listview in listview_main.xml
        listview = (ListView) findViewById(R.id.listview);
        mEditText = (EditText) findViewById(R.id.inputSearch);
        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();

        mEditText = (EditText) findViewById(R.id.inputSearch);
        mEditText.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)
            {

                ArrayList<HashMap<String, String>> arrayTemplist= new ArrayList<HashMap<String,String>>();
                String searchString =mEditText.getText().toString();
                for (int i = 0; i < arraylist.size(); i++)
                {
                    String currentString =arraylist.get(i).get(ListOfContacts.NAME);
                    if (searchString.equalsIgnoreCase(currentString)
                    {
                        arrayTemplist.add(arraylist.get(i));
                    }
                }
                adapter = new ListViewAdapter(ListOfContacts.this, arrayTemplist);
                listview.setAdapter(adapter);
             }
            });
        }
    }

    // DownloadJSON AsyncTask
    class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(ListOfContacts.this);
            // Set progressdialog title
            //mProgressDialog.setTitle("Fetching the information");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7004/DescriptionSortedPrice/");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("restaurants");

                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(ListOfContacts.NAME, jsonobject.getString("Person_Name"));
                    map.put(ListOfContacts.FLAG, "http://54.218.73.244:7004/"+jsonobject.getString("Image_Name"));



                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(ListOfContacts.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }
}


解决方案

Add below code in OnCreate() method of ListOfContacts.java

mEditText = (EditText) findViewById(R.id.inputSearch);
        mEditText.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)
            {

                ArrayList<HashMap<String, String>> arrayTemplist= new ArrayList<HashMap<String,String>>();
                String searchString =mEditText.getText().toString();
                for (int i = 0; i < arraylist.size(); i++)
                {
                    String currentString =arraylist.get(i).get(ListOfContacts.NAME);
                    if (searchString.equalsIgnoreCase(currentString)
                    {
                        arrayTemplist.add(arraylist.get(i));
                    }
                }
                adapter = new ListViewAdapter(ListOfContacts.this, arrayTemplist);
                listview.setAdapter(adapter);
             }
            });
        }

这篇关于实施搜索筛选器从服务器中检索的JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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