为从JSON检索到的服务器的数据实现搜索过滤器

时间:2013-12-20 05:32:04

标签: java android json

为来自作为JSON检索的服务器的数据实施搜索过滤器 我提到的是什么

  1. link1
  2. link2
  3. 我能做什么

    当我通过向其添加一些数据来考虑简单数组时,我能够执行搜索过滤器

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

    我的JSON结构 ::

    {
      "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"
        },
    

    我无法做到的事情:当我们从服务器检索数据并填充列表视图时如何实现搜索过滤器


    {编辑}

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

1 个答案:

答案 0 :(得分:3)

ListOfContacts.java

的OnCreate()方法中添加以下代码
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);
             }
            });
        }