【问题标题】:AutoComplete Android with JSON使用 JSON 自动完成 Android
【发布时间】:2014-09-30 05:20:19
【问题描述】:

我正在制作一个安卓应用程序。自动完成存在问题。当我将自动完成功能与这样的变量连接时,自动完成功能正在工作

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

但我也想将它连接到生成 JSON 的网页我试图将它连接到我的网页但它不起作用。

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



}

我只想将我的自动完成功能与我的网页连接起来,并在搜索时检索名称字符串。我还在我的 Android Manifest 中添加了 Internet 权限。

【问题讨论】:

  • 您是否想说在您的AutocompleteTextView 中输入的任何值都应该在您的网络服务器上传递,您会得到相应的结果?
  • 是的,例如我搜索国家名称 Like USA 并在 json 文件中自动完成搜索 USA
  • 这似乎是一项非常繁琐的工作,因为每次都需要解析整个 json 文件,这需要时间,所以我认为这不是一个好习惯。您可以解析json文件并将其保存在arraylist中,然后在autocompletetextview中使用它。
  • 在这里查看我的答案stackoverflow.com/questions/19858843/…
  • 有没有办法像我在语言变量中那样在字符串变量中获取和保存 json 数据,如果你在代码中显示它会很有帮助

标签: android json autocomplete autocompletetextview


【解决方案1】:

JSONParser.java 是一个解析器类:

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

在您的 Activity 类中:

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"/>

【讨论】:

  • 我的网址或 json 文件地址放在哪里
  • Android Debugger android.os.NetworkOnMainThreadException 中也出现此错误
  • 你的清单中有这个权限吗
  • 是的,我在最后一行提到了这个问题,你可以看到它
  • 当我将它附加到字符串数组变量时它的工作。那么告诉我如何检索 json 数据并将其保存在字符串数组变量中
猜你喜欢
  • 2017-08-14
  • 1970-01-01
  • 2016-07-28
  • 2018-01-18
  • 2013-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多