1

I am having a hard time and I am new in programming and I've searched tutorials about searching in ListView (Where the data is retrieved with JSON) but when I tried applying it with my application it does not work. No errors and I can type in the SearchView but ListView doesn't update or respond to what I type inside it.

My MainActivity.java Class:

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

    }

}

My DisplayListView class, where I will search using 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();
        }

    }

}

This is my Contacts.java class:

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


}

This is my ContactAdapater.java class:

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

}

My PHP file:

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




?>
  • whats the http status/response code from urlconnection ? assuming device and localhost both are in same network – user1140237 Jul 29 '17 at 09:46
  • try impplementing FIlterable in your custome arrayadapter class. Check [this](https://stackoverflow.com/a/19301216/5343320) for reference. – huk Jul 29 '17 at 09:52
  • @user1140237 the listview shows the proper JSON array. The SearchView just does not respond to what the user types, it just stays the same. Sorry, we had an INternet problem that is why I just responded right now – YaZao RuZakiaga Jul 29 '17 at 11:33

1 Answers1

0

Hope this method helps.

Declare this variable on top in Adapter

 public ArrayList<Contacts> searchList=new ArrayList<>();

And then this method in 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();
}

And at last call this method in activity like this

mAdapter.filter(text);

And place the above method call in

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