autocompleteEditText with dynamic data from json

AutoCompleteEditText with dynamic data from JSON

Hey, guys in this tutorial we are going to learn how to make an AutoCompleteEditText with dynamic data from JSON. Creating an AutoCompleteEditText is easy with static data but when is come to fetching dynamic data from JSON it’s more tricky. So let’s get started.
AutoCompleteEditText with static data




Project Structure
Project Structure

AndroidManifest.xml

First we have to get the internet permission so that we can fetch dynamic json data from a web server

<uses-permission android:name="android.permission.INTERNET"/>

activity_main.xml

This file is the main layout file of our application

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.husain.autocompleteedittext.MainActivity">

    <AutoCompleteTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/searcj"
        android:id="@+id/search"
        />
</RelativeLayout>

auto_complete_layout.xml

this file will be the layout for a our autoComplete drop down list

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_account_balance_black_24dp"
        android:padding="10dp"
        android:id="@+id/imageView" />


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="country name"
        android:id="@+id/countryName"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/imageView"
        android:layout_toEndOf="@+id/imageView"
        android:padding="10dp"/>
</RelativeLayout>

AutoCompleteEditText with dynamic data from json

autocompleteEditText with dynamic data from json
auto_complete_layout preview

MainActivity.java

In mainActivit we will set our AutoCompleteAdapter to the AutoCompleteTextView

package com.example.husain.autocompleteedittext;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final AutoCompleteTextView countrySearch = (AutoCompleteTextView) findViewById(R.id.search);
        final AutocompleteAdapter adapter = new AutocompleteAdapter(this,android.R.layout.simple_dropdown_item_1line);
        countrySearch.setAdapter(adapter);

        //when autocomplete is clicked
        countrySearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String countryName = adapter.getItem(position).getName();
                countrySearch.setText(countryName);
            }
        });
    }
}

Country.java

We will create a POJO class to store Country names which we have parsed from JSON

package com.example.husain.autocompleteedittext;

public class Country {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

AutocompleteAdapter.java

This class will be responsible to fetch JSON data from the server and store that data into the Contry POJO list and populating that list into a AutoCompleteEditText

package com.example.husain.autocompleteedittext;


import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

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

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

public class AutocompleteAdapter extends ArrayAdapter implements Filterable {
    private ArrayList mCountry;
    private String COUNTRY_URL =
            "http://demo.hackerkernel.com/jqueryui_autocomplete_dropdown_with_php_and_json/country.php?term=";

    public AutocompleteAdapter(Context context, int resource) {
        super(context, resource);
        mCountry = new ArrayList<>();
    }

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

    @Override
    public Country getItem(int position) {
        return mCountry.get(position);
    }

    @Override
    public Filter getFilter() {
        Filter myFilter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if(constraint != null){
                    try{
                        //get data from the web
                        String term = constraint.toString();
                        mCountry = new DownloadCountry().execute(term).get();
                    }catch (Exception e){
                        Log.d("HUS","EXCEPTION "+e);
                    }
                    filterResults.values = mCountry;
                    filterResults.count = mCountry.size();
                }
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if(results != null && results.count > 0){
                    notifyDataSetChanged();
                }else{
                    notifyDataSetInvalidated();
                }
            }
        };

        return myFilter;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View view = inflater.inflate(R.layout.auto_complete_layout,parent,false);

        //get Country
        Country contry = mCountry.get(position);

        TextView countryName = (TextView) view.findViewById(R.id.countryName);

        countryName.setText(contry.getName());

        return view;
    }

    //download mCountry list
    private class DownloadCountry extends AsyncTask>{

        @Override
        protected ArrayList doInBackground(String... params) {
            try {
                //Create a new COUNTRY SEARCH url Ex "search.php?term=india"
                String NEW_URL = COUNTRY_URL + URLEncoder.encode(params[0],"UTF-8");
                Log.d("HUS", "JSON RESPONSE URL " + NEW_URL);

                URL url = new URL(NEW_URL);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                InputStream in = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                String line;
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null){
                    sb.append(line).append("\n");
                }

                //parse JSON and store it in the list
                String jsonString =  sb.toString();
                ArrayList countryList = new ArrayList<>();

                JSONArray jsonArray = new JSONArray(jsonString);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jo = jsonArray.getJSONObject(i);
                    //store the country name
                    Country country = new Country();
                    country.setName(jo.getString("label"));
                    countryList.add(country);
                }

                //return the countryList
                return countryList;

            } catch (Exception e) {
                Log.d("HUS", "EXCEPTION " + e);
                return null;
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *