1

I am making an android app. There is a problem coming with autocomplete. Autocomplete is working when i connect autocomplete with a variable like this

String[] languages = { "C","C++","Java","C#","PHP","JavaScript","jQuery","AJAX","JSON" };

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_singlechoice, languages);
    //Find TextView control
    AutoCompleteTextView acTextView = (AutoCompleteTextView) findViewById(R.id.languages);
    //Set the number of characters the user must type before the drop down list is shown
    acTextView.setThreshold(1);
    //Set the adapter
    acTextView.setAdapter(adapter);

But i want too connect it to my web page which generates JSON i tried to connect it with my web page but its not working.

try
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://example.com/test.php");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.e("Pass 1", "connection success ");
    }
    catch(Exception e)
    {
        Log.e("Fail 1", e.toString());
    }

    try
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(is,"iso-8859-8"),8);
        StringBuilder sb=new StringBuilder();
        while((line=br.readLine())!=null)
        {
            sb.append(line+"\n");
        }
        is.close();
        result=sb.toString();
        Log.e("Pass 2", "Success");
    }
    catch(Exception e)
    {
        Log.e("Fail 2", e.toString());
    }


    try
    {
        JSONArray ja=new JSONArray(result);
        JSONObject jo=null;
        String[] str=new String[ja.length()];
        for(int i=0;i<ja.length();i++)
        {
            jo=ja.getJSONObject(i);
            str[i]=jo.getString("name");
        }

        MultiAutoCompleteTextView auto=(MultiAutoCompleteTextView) findViewById(R.id.names);
        auto.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
        ArrayAdapter<String> adp= new ArrayAdapter<String>(getBaseContext(),
                android.R.layout.simple_dropdown_item_1line,str);
        adp.setDropDownViewResource(android.R.layout.simple_expandable_list_item_1);
        auto.setThreshold(1);
        auto.setAdapter(adp);
    }
    catch(Exception e)
    {
        Log.e("Fail 2", e.toString());
    }



}

I just wanna connect my auto complete with my webpage and retrieve name string when search. I also added Internet permissions to my Android Manifest.

  • Are you trying to say that whatever value is entered in your `AutocompleteTextView` that value should be passed on your webserver and you will get result accordingly? – GrIsHu Aug 07 '14 at 05:07
  • Yes, For example i search conutry name Like USA and autocomplete search USA in json file – Burhan aka SLIM SHADY Aug 07 '14 at 05:10
  • It seems a very tedious job since for each time it needs to parse the whole json file which takes time, so i think it is not a good practice. You can parse the json file and save it in a arraylist and then use it in autocompletetextview. – ORIGINAL Aug 07 '14 at 05:18
  • see my answer here http://stackoverflow.com/questions/19858843/how-to-dynamically-add-suggestions-to-autocompletetextview-with-preserving-chara – pskink Aug 07 '14 at 05:20
  • Is there a way to fetch and save json data in string variable like i am doing in languages variables, it will be helpful if u show it in code – Burhan aka SLIM SHADY Aug 07 '14 at 05:24
  • Like this :ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.select_dialog_singlechoice, languages); //Find TextView control AutoCompleteTextView acTextView = (AutoCompleteTextView) findViewById(R.id.languages); //Set the number of characters the user must type before the drop down list is shown acTextView.setThreshold(1); //Set the adapter acTextView.setAdapter(adapter); save all names in laguages variable when load – Burhan aka SLIM SHADY Aug 07 '14 at 05:26
  • @ORIGINAL what if you want to query wikipedia site for example, would you like to store 4000000+ keywords in arraylist? – pskink Aug 07 '14 at 05:30
  • @BurhanakaSLIMSHADY did you see my first comment? – pskink Aug 07 '14 at 05:32
  • Yes i got what u wanna say and u right about it. But in my case i created separate pages like for names i created test.php and for cities i created test1.php, that is why i am not querying like test.php?name=variable. I made separate pages for different autocompletetextview. I know its a dull mistake to do it but in my case i have to do it. – Burhan aka SLIM SHADY Aug 07 '14 at 05:40
  • Now tell me how i store json data from my webpage into a string variable – Burhan aka SLIM SHADY Aug 07 '14 at 05:41
  • so you want every time to send a list of all (196) world countries instead of those that match your query? what a waste of time and resources... – pskink Aug 07 '14 at 06:35
  • Yes, but its not what its look like json data is controlled by my site dynamically. It only shows countries or cities which are enables on my site. – Burhan aka SLIM SHADY Aug 07 '14 at 06:53
  • Ok if u say so i do it ur way and add string to my webpage like this test.php?name=variable, So now what i do ? I tried this way also but not working – Burhan aka SLIM SHADY Aug 07 '14 at 06:54
  • did you run my code? it queries wikipedia site, type something in ACTV field and see whats done in runQuery method – pskink Aug 07 '14 at 06:57

1 Answers1

-1

the JSONParser.java is a parser class:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    static DefaultHttpClient httpClient;

    public String getJSONFromUrl(String url) {
        // Making HTTP request
        try {
            // defaultHttpClient
            httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();   
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
        } 
}

In your Activity class:

public class MyActivity extends Activity{
    String url="http://example.com/test.php";
    private ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.your_layout);

        new JSONParse().execute();

    }


    private class JSONParse extends AsyncTask<String, String, String> {
        JSONObject jo=null;
            ArrayList<String> namelist = new ArrayList<String>();
        @Override
        protected void onPreExecute(){
                super.onPreExecute();
                pDialog = new ProgressDialog(MyActivity.this);
                pDialog.setMessage("Please wait...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();         
        }

        @Override
        protected String doInBackground(String... args) {
            JSONParser jParser = new JSONParser(); 
            String json = jParser.getJSONFromUrl(url); 
            return json;           
        }

        @Override
        protected void onPostExecute(String json) {
            if (pDialog != null) {
                pDialog.dismiss();
            }

              try {
                        JSONArray ja=new JSONArray(json);

                    for(int i=0;i<ja.length();i++)
                    {
                     jo=ja.getJSONObject(i);
                     String n =jo.getString("name");
                     namelist.add(n);
                     Collections.sort(namelist);
                    }
                    AutoCompleteTextView srch=(AutoCompleteTextView) findViewById(R.id.search);
                        ArrayAdapter<String> adpter = new ArrayAdapter<String>(this,
                        R.layout.my_custom_dropdown, namelist);
                        srch.setThreshold(1);
                        srch.setAdapter(adpter);

            }           
        catch (Exception e) {
                pDialog.dismiss();
                Toast.makeText(getApplicationContext(), "No Network Connection!!!", Toast.LENGTH_LONG).show();
            }             

        }
    }
}

my_custom_dropdown.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView 
    xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:padding="5sp"
    android:textColor="#000000"
    android:background="#ffffff"/>
ORIGINAL
  • 179
  • 1
  • 12