使用SearchView搜索ListView(关于JSON)

时间:2017-07-29 09:42:24

标签: java android json listview

我很难过,而且我是编程方面的新手,我已经搜索了有关在ListView中搜索的教程(使用JSON检索数据的位置),但是当我尝试将它应用于我的应用程序时,它不起作用。没有错误,我可以输入SearchView,但ListView不会更新或回复我在其中输入的内容。

我的MainActivity.java类:

package rjj.tutorial_jsonandlistview;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class MainActivity extends AppCompatActivity {

    String Json_STRING;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new BackgroundTask().execute();
        //new line


    }


    class BackgroundTask extends AsyncTask<Void, Void, String> {

        String json_url;
        String JSON_STRING;

        @Override
        protected void onPreExecute() {

            json_url = "http://10.0.2.2/rizal22.php";
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                URL url = new URL(json_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();
                while ((JSON_STRING = bufferedReader.readLine()) != null) {

                    stringBuilder.append(JSON_STRING + "\n");
                }

                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return stringBuilder.toString().trim();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(String result) {
            TextView textView = (TextView)findViewById(R.id.textView2);
            textView.setText(result);
            Json_STRING = result;
        }

    }
    //List view time!
    public void parseJSON(View view) {
        if(Json_STRING == null){
            Toast.makeText(getApplicationContext(), "First Get JSON", Toast.LENGTH_SHORT).show();
        }else{
            Intent intent = new Intent(this, DisplayListView.class);
            intent.putExtra("json_data", Json_STRING);
            startActivity(intent);
        }

    }

}

我的DisplayListView类,我将使用SearchView进行搜索。

package rjj.tutorial_jsonandlistview;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;

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



public class DisplayListView extends AppCompatActivity {

    String json_string;
    JSONObject jsonObject;
    JSONArray jsonArray;
    ContactAdapter contactAdapter;
    ListView listView;
    SearchView sv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display_listview_layout);
        listView = (ListView)findViewById(R.id.listview);

        contactAdapter = new ContactAdapter(this,R.layout.row_layout);
        listView.setAdapter(contactAdapter);

        json_string = getIntent().getExtras().getString("json_data");
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {



                TextView textView = (TextView) view.findViewById(R.id.tx_id);

                String text = textView.getText().toString();
                Intent intent = new Intent(DisplayListView.this, Update.class);
                intent.putExtra("id", text);
                //new line
                intent.putExtra("json_data", json_string);
                startActivity(intent);
            }

        });
        //Searchview
        sv = (SearchView)findViewById(R.id.search);

        sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                contactAdapter.getFilter(

                ).filter(newText);
                listView.setFilterText(newText);
                return true;
            }
        });
        //End of Searchview

        try {
            jsonObject = new JSONObject(json_string);
            jsonArray = jsonObject.getJSONArray("server_response");
            int count = 0;
            String id ,firstname , surname, age , username, password;


            while(count<jsonArray.length()){
                JSONObject JO = jsonArray.getJSONObject(count);
                id = JO.getString("id");
                firstname = JO.getString("PLATE_NUM");
                surname = JO.getString("PUV_TYPE");
                Contacts contact = new Contacts(id, firstname, surname);
                contactAdapter.add(contact);


                count++;

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

}

这是我的Contacts.java类:

package rjj.tutorial_jsonandlistview;

/**
 * Created by Julian on 7/20/2017.
 */

public class Contacts {

    private String id,firstname,surname,age,username,password;

    public Contacts(String id, String firstname, String surname){


            this.setId(id);
            this.setFirstname(firstname);
            this.setSurname(surname);





    }
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }


}

这是我的ContactAdapater.java类:

package rjj.tutorial_jsonandlistview;

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Julian on 7/20/2017.
 */

public class ContactAdapter extends ArrayAdapter {
    List list = new ArrayList();

    public ContactAdapter(@NonNull Context context, @LayoutRes int resource) {
        super(context, resource);


    }


    public void add(Contacts object) {
        super.add(object);
        list.add(object);
    }

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

    @Nullable
    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        View row;
        row = convertView;
        ContactHolder contactHolder;
        if(row == null){
            LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.row_layout,parent,false);
            contactHolder = new ContactHolder();
            contactHolder.tx_id = (TextView)row.findViewById(R.id.tx_id);
            contactHolder.tx_firstname = (TextView)row.findViewById(R.id.tx_firstname);
            contactHolder.tx_surname = (TextView)row.findViewById(R.id.tx_surname);

            row.setTag(contactHolder);

        } else{
            contactHolder = (ContactHolder)row.getTag();
        }
        Contacts contacts = (Contacts)this.getItem(position);
        contactHolder.tx_id.setText(contacts.getId());
        contactHolder.tx_firstname.setText(contacts.getFirstname());
        contactHolder.tx_surname.setText(contacts.getSurname());

        return row;
    }

    static class ContactHolder{
        TextView tx_id, tx_firstname, tx_surname;
    }

}

我的PHP文件:

<?php
$host='localhost';
$user='root';
$password='';
$db='employee101';
//Old id $_id = $_POST['id'];
$sql = "select * from employee_data;";
//Old line $sql = "select * from employee_data where id = $_id;";

$con = mysqli_connect($host,$user,$password,$db);

$result = mysqli_query($con, $sql);

$response = array();

while($row = mysqli_fetch_array($result)){

    array_push($response,array("id"=>$row[0],"PLATE_NUM"=>$row[1],"PUV_TYPE"=>$row[2]));

}

echo json_encode(array("server_response"=>$response));

mysqli_close($con);




?>

1 个答案:

答案 0 :(得分:0)

希望这种方法有所帮助。

在Adapter

中声明此变量
 public ArrayList<Contacts> searchList=new ArrayList<>();

然后在Adapter

中使用此方法
    public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    list.clear();
    if (charText.length() == 0) {
        list.addAll(searchList);
    }
    else
    {
        for (Contacts wp : searchList)
        {
            if (wp.getTitle().toLowerCase(Locale.getDefault()).contains(charText))
            {
                list.add(wp);
            }
        }
    }
    notifyDataSetChanged();
}

最后在这样的活动中调用此方法

mAdapter.filter(text);

将上述方法调用放在

 @Override
        public boolean onQueryTextChange(String newText) {
            contactAdapter.filter(newText);
            return true;
        }