2016-08-17 2 views
1

я пытался с этим кодом MainActivity.javaКак получить данные в AutoCompleteTextView с помощью mySQL и Json?

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 

ответ

0

Вы уверены, что вы разбор ваших JSON правильно? Если возвращаемая строка, которую вы отправили, не верна, я получаю исключение из кода, пытающегося его проанализировать. Я предложил бы использовать рамки JSon с POJOs вместо:

Первый тест не пройден ниже, второй преуспевает:

@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; 
    } 
+0

я извиняюсь, сэр Б.Т. я не получаю эту point..and это мой первый проект так мало путать с этой штукой. –

+0

Это простые модульные тесты для тестирования изолированных разделов кода. Первый модульный тест - это ваш код, который генерирует исключение при анализе строки json. Второй тест - это мое предлагаемое решение для вашего кода, который терпит неудачу. –

Смежные вопросы