ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java – 使用jview文件中的listview的Android搜索功能(硬)

2019-06-28 16:13:18  阅读:187  来源: 互联网

标签:json java android listview android-search


1.我的搜索功能使用edittext工作正常,但是例如,如果我输入“1”而不是删除它,listview显示为null,我怎样才能使listview在输入内容后再次显示JSON然后将其删除?

2.如果我改为搜索COUNTRY而不是RANK,我需要输入像“INDIA”这样的完整字符,我怎么才能输入“in”然后才能显示INDIA?
谢谢

MainActivity.java

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends Activity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String RANK = "rank";
    static String COUNTRY = "country";
    static String POPULATION = "population";
    static String URL="url";
    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);
        // 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(MainActivity.RANK);
                        if (searchString.equalsIgnoreCase(currentString)) {
                            arrayTemplist.add(arraylist.get(i));
                        }

                    }
                    adapter = new ListViewAdapter(MainActivity.this, arrayTemplist);
                    listview.setAdapter(adapter);

            }


        });
    }


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

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(MainActivity.this);
            // Set progressdialog title
            mProgressDialog.setTitle("Android JSON Parse Tutorial");
            // 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://ndublog.twomini.com/123.txt.txt");

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

                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("rank", jsonobject.getString("rank"));
                    map.put("country", jsonobject.getString("country"));
                    map.put("population", jsonobject.getString("population"));
                    map.put("url",jsonobject.getString("url"));
                    map.put("flag", jsonobject.getString("flag"));
                    // 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) {
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.listview);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(MainActivity.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }



        }

ListViewAdapter.java

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

public class ListViewAdapter  extends BaseAdapter  {

    Context context;
    LayoutInflater inflater;
    public 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 rank;
        TextView country;
        TextView population;
        TextView url;
        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
        rank = (TextView) itemView.findViewById(R.id.rank);
        country = (TextView) itemView.findViewById(R.id.country);
        population = (TextView) itemView.findViewById(R.id.population);
        url=(TextView)itemView.findViewById(R.id.url);
        // Locate the ImageView in listview_item.xml
        flag = (ImageView) itemView.findViewById(R.id.flag);

        // Capture position and set results to the TextViews
        rank.setText(resultp.get(MainActivity.RANK));
        country.setText(resultp.get(MainActivity.COUNTRY));
        population.setText(resultp.get(MainActivity.POPULATION));
        url.setText(resultp.get(MainActivity.URL));
        // Capture position and set results to the ImageView
        // Passes flag images URL into ImageLoader.class
        imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
        // Capture ListView item click
        itemView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Get the position
                resultp = data.get(position);
                Intent intent = new Intent(context, SingleItemView.class);
                // Pass all data rank
                intent.putExtra("rank", resultp.get(MainActivity.RANK));
                // Pass all data country
                intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
                // Pass all data population
                intent.putExtra("population",resultp.get(MainActivity.POPULATION));

                intent.putExtra("url",resultp.get(MainActivity.URL));
                // Pass all data flag

                intent.putExtra("flag", resultp.get(MainActivity.FLAG));
                // Start SingleItemView Class
                context.startActivity(intent);

            }
        });
        return itemView;

    }
}

在下面编辑此代码,谢谢

  import android.app.ListActivity;
    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.util.Log;
    import android.widget.EditText;
    import android.widget.ListView;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.ArrayList;
    import java.util.HashMap;


public class MainActivity extends ListActivity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String RANK = "rank";
    static String COUNTRY = "country";
    static String POPULATION = "population";
    static String URL="url";
    static String FLAG = "flag";
    EditText mEditText;
    String globalQuery="";
    ArrayList<HashMap<String, String>> globalList = new ArrayList<HashMap<String, String>>();
    ListViewAdapter globalListAdapter,globalAdapter=null;
    public void filteredList()
    {
//First of all checks for our globalList is not a null one.
        if(globalList!=null)
        {

            ArrayList<HashMap<String, String>> tempList = new ArrayList<HashMap<String, String>>();
//Checks our search term is empty or not.
            ListViewAdapter globalAdapter = null;
            if(!globalQuery.trim().equals(""))
            {
                boolean isThereAnyThing=false;
                for(int i=0;i<globalList.size();i++)
                {
//Get the value of globalList that is HashMap indexed at i.
                    HashMap<String, String> tempMap=globalList.get(i);
//Now getting all your HashMap values into local variables.
                    String rank=tempMap.get(MainActivity.RANK);
                    String country=tempMap.get(MainActivity.COUNTRY);
                    String population=tempMap.get(MainActivity.POPULATION);
                    String url=tempMap.get(MainActivity.URL);
                    String flag=tempMap.get(MainActivity.FLAG);
//Now all the core checking goes here for which one of these was typed like rank or country or population .....
                    if(rank.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || country.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || population.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || url.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || flag.regionMatches(true, 0, globalQuery,0, globalQuery.length()))
                    {
//If anything matches then it will add to tempList
                        tempList.add(tempMap);
                        isThereAnyThing=true;
                    }
                }
//Checks for is there anything matched from the ArrayList with the user type search query
                if(isThereAnyThing)
                {
//then set the globalAdapter with the new HashMaps tempList
                    globalAdapter = new ListViewAdapter(MainActivity.this, tempList);
                    listview.setAdapter(globalAdapter);
                    setListAdapter(globalAdapter);
                    ((ListViewAdapter)globalAdapter).notifyDataSetChanged();
                }
                else
                {
//If else set list adapter to null
                    setListAdapter(null);
                }
            }
            else
            {
                // Do something when there's no input
                if(globalAdapter==null)
                {
//If no user inputs then it will list everything in the globalList.
                    justListAll();
                }
                else
                {
                    final ListViewAdapter finalGlobalAdapter = globalAdapter;
                    runOnUiThread(new Runnable()
                    {
                        public void run()
                        {

                            ((ListViewAdapter) finalGlobalAdapter).notifyDataSetChanged();

                        }
                    });
                }

            }
            // updating listview

        }
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main);
        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();




        mEditText = (EditText) findViewById(R.id.inputSearch);

      mEditText.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    // Search
                    globalQuery=s.toString();
//This method will filter all your categories just calling this method.
                    filteredList();
                } else {
                    globalQuery="";
//If the text is empty the list all the content of the list adapter
                    justListAll();
                }
            }

            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();
                    if(searchString.equals("")){new DownloadJSON().execute();}

                else{


                for (int i = 0; i < arraylist.size(); i++) {
                    String currentString = arraylist.get(i).get(MainActivity.COUNTRY);
                    if (searchString.contains(currentString)) {
//pass the character-sequence instead of currentstring
                        arrayTemplist.add(arraylist.get(i));
                    }
                }
                    }
                    adapter = new ListViewAdapter(MainActivity.this, arrayTemplist);
                    listview.setAdapter(adapter);

            }


        });
    }


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

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(MainActivity.this);
            // Set progressdialog title
            mProgressDialog.setTitle("Android JSON Parse Tutorial");
            // 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://ndublog.twomini.com/123.txt.txt");

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

                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("rank", jsonobject.getString("rank"));
                    map.put("country", jsonobject.getString("country"));
                    map.put("population", jsonobject.getString("population"));
                    map.put("url",jsonobject.getString("url"));
                    map.put("flag", jsonobject.getString("flag"));
                    // 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) {
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.listview);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(MainActivity.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }


    public void justListAll()
    {
        ListViewAdapter globalAdapter = new ListViewAdapter(MainActivity.this, globalList);
        listview.setAdapter(adapter);
        setListAdapter(globalAdapter);
        ((ListViewAdapter)globalAdapter).notifyDataSetChanged();
    }

   }

解决方法:

感谢您按照SO指南以良好的方式提出问题.

我相信这会解决你的问题.

//First of all declare a global variables
String globalQuery="";
ArrayList<HashMap<String, String>> globalList = new ArrayList<HashMap<String, String>>();
ListViewAdapter globalListAdapter;

public void afterTextChanged(Editable s) {
 if (s.toString().length() > 0) {
                    // Search
globalQuery=s.toString();
//This method will filter all your categories just calling this method.
filteredList();
                } else {
                    globalQuery="";
//If the text is empty the list all the content of the list adapter
                justListAll();
                }
            }

public void justListAll()
{
    globalAdapter = new ListViewAdapter(MainActivity.this, globalList);
                    listview.setAdapter(adapter);
    setListAdapter(globalAdapter);
    ((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}

public void filteredList()
{
//First of all checks for our globalList is not a null one.
if(globalList!=null)
            {

    ArrayList<HashMap<String, String>> tempList = new ArrayList<HashMap<String, String>>();
//Checks our search term is empty or not.
    if(!globalQuery.trim().equals(""))
    {
        boolean isThereAnyThing=false;
    for(int i=0;i<globalList.size();i++)
    {
//Get the value of globalList that is HashMap indexed at i.
        HashMap<String, String> tempMap=globalList.get(i);
//Now getting all your HashMap values into local variables.
        String rank=tempMap.get(MainActivity.RANK);
        String country=tempMap.get(MainActivity.COUNTRY);
        String population=tempMap.get(MainActivity.POPULATION);
        String url=tempMap.get(MainActivity.URL);
        String flag=tempMap.get(MainActivity.FLAG);
//Now all the core checking goes here for which one of these was typed like rank or country or population .....
                if(rank.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || country.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || population.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || url.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || flag.regionMatches(true, 0, globalQuery,0, globalQuery.length()))
                {
//If anything matches then it will add to tempList
                    tempList.add(tempMap);
                    isThereAnyThing=true;
                }
    }
//Checks for is there anything matched from the ArrayList with the user type search query
    if(isThereAnyThing)
    {
//then set the globalAdapter with the new HashMaps tempList
     globalAdapter = new ListViewAdapter(MainActivity.this, tempList);
                    listview.setAdapter(globalAdapter);
    setListAdapter(globalAdapter);
    ((ListViewAdapter)globalAdapter).notifyDataSetChanged();
    }
    else
    {
//If else set list adapter to null
        setListAdapter(null);
    }
}
else
{
    // Do something when there's no input
    if(globalAdapter==null)
    {
//If no user inputs then it will list everything in the globalList.
justListAll();
    }
    else
    {
         runOnUiThread(new Runnable()
         {
             public void run()
             {

    ((ListViewAdapter)globalAdapter).notifyDataSetChanged();

             }
         });
    }

         }
     // updating listview

            }
}

只需要执行的操作就是将所有JSON解析值填充到全局ArrayList globalList中.

希望它通过额外的包装回答整个问题.

标签:json,java,android,listview,android-search
来源: https://codeday.me/bug/20190628/1317423.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有