如何使用mySQL和Json在AutoCompleteTextView中获取数据?

时间:2016-08-17 13:18:38

标签: android mysql json

我尝试使用此代码 MainActivity.java

public class MainActivity extends Activity {
    public String data;
    public List<String> suggest;
    public AutoCompleteTextView autoComplete;
    public ArrayAdapter<String> aAdapter;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        suggest = new ArrayList<String>();
        autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
        autoComplete.addTextChangedListener(new TextWatcher(){

            public void afterTextChanged(Editable editable) {
                // TODO Auto-generated method stub

            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String newText = s.toString();
                new getJson().execute(newText);
            }

        });

    }
    class getJson extends AsyncTask<String,String,String>{

        @Override
        protected String doInBackground(String... key) {
            String newText = key[0];
            newText = newText.trim();
            newText = newText.replace(" ", "+");
            try{
                HttpClient hClient = new DefaultHttpClient();
                HttpGet hGet = new HttpGet("http://10.0.2.2/autocmplt/abc.php?name=");
                ResponseHandler<String> rHandler = new BasicResponseHandler();
                data = hClient.execute(hGet,rHandler);
                suggest = new ArrayList<String>();
                JSONArray jArray = new JSONArray(data);
                for(int i=0;i<jArray.getJSONArray(1).length();i++){
                    String SuggestKey = jArray.getJSONArray(1).getString(i);
                    suggest.add(SuggestKey);
                }

            }catch(Exception e){
                Log.w("Error", e.getMessage());
            }
            runOnUiThread(new Runnable(){
                public void run(){
                    aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,suggest);
                    autoComplete.setAdapter(aAdapter);
                    aAdapter.notifyDataSetChanged();
                }
            });

            return null;
        }

    }
}

这是我的main_activity.xml 在这里我创建autocompletetextview             

    <AutoCompleteTextView
        android:id="@+id/autoCompleteTextView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp"
        android:ems="13"
        android:hint="AutoCompleteTextView" >

        <requestFocus />
    </AutoCompleteTextView>

</LinearLayout>

这是我的item.xml文件 在这里我使用TextView进行下拉菜单。

   
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textSize="16sp"
    android:textColor="#000"
    android:background="#eaeaea">
</TextView>

.php文件的响应

{"results":[{"id":"1","name":"sachin"},{"id":"2","name":"solanki"},{"id":"3","name":"abc"},{"id":"4","name":"abcd"}]} 

这就是我的尝试..

得到错误

08-17 18:14:33.745 5284-5307/com.example.sachin.autocomplete W/Error: Value {"results":[{"id":"1","name":"sachin"},{"id":"2","name":"solanki"},{"id":"3","name":"abc"},{"id":"4","name":"abcd"}]} of type org.json.JSONObject cannot be converted to JSONArray

1 个答案:

答案 0 :(得分:0)

您确定要正确解析JSON吗?除非您发布的返回字符串不正确,否则我会在您的代码尝试解析时遇到异常。我建议使用带有POJO的json框架:

第一次测试失败,第二次测试成功:

@Test
    public void testJson() {

        String data = "{\"results\":[{\"id\":\"1\",\"name\":\"sachin\"},{\"id\":\"2\",\"name\":\"solanki\"},{\"id\":\"3\",\"name\":\"abc\"},{\"id\":\"4\",\"name\":\"abcd\"}]}";
        JSONArray jArray = null;
        ArrayList<String> suggest = new ArrayList<>();
        try {
            jArray = new JSONArray(data);
            for(int i=0;i<jArray.getJSONArray(1).length();i++){
                String SuggestKey = jArray.getJSONArray(1).getString(i);
                suggest.add(SuggestKey);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Test
    public void testJson2() {

        String data = "{\"results\":[{\"id\":\"1\",\"name\":\"sachin\"},{\"id\":\"2\",\"name\":\"solanki\"},{\"id\":\"3\",\"name\":\"abc\"},{\"id\":\"4\",\"name\":\"abcd\"}]}";
        ArrayList<String> suggest = new ArrayList<>();

        Gson gson = new Gson();
        Results r = gson.fromJson(data, Results.class);
        for ( Custom c : r.customArray ) {
            suggest.add(c.name);
        }
    }

    class Results {
        @SerializedName("results")
        @Expose
        public ArrayList<Custom> customArray;
    }

    class Custom {
        @SerializedName("id")
        @Expose
        public String id;
        @SerializedName("name")
        @Expose
        public String name;
    }