2015-12-13 60 views
1

我有一個適用於我的應用程序的自動完成適配器,我從Google Places API獲取json結果。我的麻煩是試圖讓結果顯示在屏幕上。我正在使用本指南:http://examples.javacodegeeks.com/android/android-google-places-autocomplete-api-example/過濾自動完成適配器的json結果

大多數情況下,代碼看起來很合理,但無論出於何種原因,我無法獲取任何內容以便將其打印到顯示器上。我真的不明白過濾器是如何工作的,也許有關如何與自動完成適配器一起工作的解釋會有所幫助。

我的onCreate是:

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     buildGoogleApiClient(); 
     setContentView(R.layout.activity_maps); 
     // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 

     if (savedInstanceState != null) { 
      mIsResolving = savedInstanceState.getBoolean(KEY_IS_RESOLVING); 
      mShouldResolve = savedInstanceState.getBoolean(KEY_SHOULD_RESOLVE); 
     } 

//  Create the LocationRequest object 
     mLocationRequest = LocationRequest.create() 
       .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY) 
       .setInterval(10 * 1000)   //10 seconds, in milliseconds 
       .setFastestInterval(1 * 1000); //1 second, in milliseconds 

     Log.d(TAG, "GoogleApiClient built"); 

     if (savedInstanceState != null) { 
      mSignInProgress = savedInstanceState 
        .getInt(SAVED_PROGRESS, STATE_DEFAULT); 
     } 

     mShouldResolve = true; 
     mGoogleApiClient.connect(); 
     Log.d(TAG, "Starting sign-in"); 



     AutoCompleteTextView autoCompView = (AutoCompleteTextView) 
       findViewById(R.id.autoCompleteTextView); 


     autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.activity_maps)); 
     autoCompView.setOnItemClickListener(this); 

    } 

我爲獲得JSON的結果的方法是:

public ArrayList<String> autocomplete(String input) { 
     Log.d(TAG, "performSearch()"); 

     ArrayList resultList = null; 

     AsyncTask<ArrayList<String>, Void, ArrayList> 
       myTask = new AsyncTask<ArrayList<String>, Void, ArrayList>() { 

      AutoCompleteTextView text = (AutoCompleteTextView) 
        findViewById(R.id.autoCompleteTextView); 
      private String input = text.getText().toString(); 

      @Override 
      protected ArrayList doInBackground(ArrayList<String>... params) { 
       Log.d(TAG, "Starting Search"); 

       ArrayList resultList = null; 

       HttpURLConnection conn = null; 
       StringBuilder jsonResults = new StringBuilder(); 
       try { 
        KEYWORD = input; 

        ENDPOINT = Uri 
          .parse("https://maps.googleapis.com/maps/api/place/nearbysearch/json") 
          .buildUpon() 
          .appendQueryParameter("location", LOCATION) 
          .appendQueryParameter("radius", "10000") 
          .appendQueryParameter("keyword", KEYWORD) 
          .appendQueryParameter("key", API_KEY) 
          .build(); 

        URL url = new URL(ENDPOINT.toString()); 

        Log.d(TAG, "URL: " + url); 

        conn = (HttpURLConnection) url.openConnection(); 
        InputStreamReader in = new InputStreamReader(conn.getInputStream()); 

        // Load the results into a StringBuilder 
        int read; 
        char[] buff = new char[1024]; 
        while ((read = in.read(buff)) != -1) { 
         jsonResults.append(buff, 0, read); 
        } 
        Log.d(TAG, jsonResults.toString()); 
       } catch (MalformedURLException e) { 
        Log.e(TAG, "Error processing Places API URL", e); 
        return resultList; 
       } catch (IOException e) { 
        Log.e(TAG, "Error connecting to Places API", e); 
        return resultList; 
       } finally { 
        if (conn != null) { 
         conn.disconnect(); 
        } 
       } 
       try { 
        // Create a JSON object hierarchy from the results 
        JSONObject jsonObj = new JSONObject(jsonResults.toString()); 
        JSONArray predsJsonArray = jsonObj.getJSONArray("results"); 

        // Extract the Place descriptions from the results 
        resultList = new ArrayList(predsJsonArray.length()); 
        for (int i = 0; i < predsJsonArray.length(); i++) { 
         System.out.println(predsJsonArray.getJSONObject(i).getString("name")); 
         System.out.println(predsJsonArray.getJSONObject(i).getString("vicinity")); 
         System.out.println("====================================================="); 
         resultList.add(predsJsonArray.getJSONObject(i).getString("name")); 
         resultList.add(predsJsonArray.getJSONObject(i).getString("vicinity")); 
        } 
       } catch (JSONException e) { 
        Log.e(TAG, "Cannot process JSON results", e); 
       } 
       Log.d(TAG, resultList.toString()); 
       return resultList; 
      } 

     }; 

     myTask.execute(); 

     Log.d(TAG, resultList.toString()); 
     return resultList; 
    } 

我的過濾器類:

class GooglePlacesAutocompleteAdapter extends ArrayAdapter implements Filterable { 
     private ArrayList resultList; 

     public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) { 
      super(context, textViewResourceId); 
     } 

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

     @Override 
     public String getItem(int index) { 
      return (String) resultList.get(index); 
     } 

     @Override 
     public Filter getFilter() { 
      Filter filter = new Filter() { 
       @Override 
       protected FilterResults performFiltering(CharSequence constraint) { 
        FilterResults filterResults = new FilterResults(); 
        if (constraint != null) { 
         // Retrieve the autocomplete results. 
         resultList = autocomplete(constraint.toString()); 

         // Assign the data to the FilterResults 
         filterResults.values = resultList; 
         filterResults.count = resultList.size(); 
        } 
        return filterResults; 
       } 

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

我知道我得到一個聲音結果從谷歌和我的建立陣列看起來像這樣(它包括名稱和附近):

[城全球市場,920東湖街#G10,明尼阿波利斯,該 錨魚&芯片,302第13大道東北,明尼阿波利斯,布拉斯卡 高級烤肉店,600東亨內大街,明尼阿波利斯,楔形 社區共管-OP,2105 Lyndale酒店大道南,明尼阿波利斯,陶自然 食品,2200亨內大街,明尼阿波利斯,新鮮&天然食品,1075 公路96西,聖保羅,全食市場,222亨內大街, 明尼阿波利斯,森艾歷森泰國,2422 Central Avenue Northeast, 明尼阿波利斯,密西西比市場天然食品合作社,622 Selby Avenue, 聖保羅,Eastside Food Co-Op,2551 Central Avenue Northeast, 明尼阿波利斯,Bills進口食品,721 West Lake Street,Minneapolis, Seoul Foods,1071 East Moore Lake Drive,明尼阿波利斯,蘇厄德社區 合作社 - 富蘭克林店,2823 East Franklin Avenue,Minneapolis,Foxy Falafel,791 Raymond Avenue,聖保羅,亞洲食品,1300 L'Orient Street,Saint Paul,Pohl Distributing Co,510 Kasota Avenue Southeast, Minneapolis,Rainbow Foods,1566 University Avenue西部,聖保羅, 蒲公英廚房卡車,800 Nicollet購物中心,明尼阿波利斯,世界街道 廚房,2743 Lyndale大道南#5,明尼阿波利斯,CES食品架, 明尼阿波利斯東19街]

任何幫助表示讚賞,謝謝!

[編輯] 這裏是我的activity_maps XML:

<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" 
       tools:context="com.hudsoncorp.zahudson.roadtrip.MapsActivity"> 

     <fragment xmlns:android="http://schemas.android.com/apk/res/android" 
      xmlns:tools="http://schemas.android.com/tools" 
      xmlns:map="http://schemas.android.com/apk/res-auto" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:id="@+id/map" 
      tools:context="com.hudsoncorp.zahudson.roadtrip.MapsActivity" 
      android:name="com.google.android.gms.maps.SupportMapFragment"/> 

     <RelativeLayout 
      android:orientation="vertical" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:padding="10dp"> 

      <AutoCompleteTextView 
       android:id="@+id/autoCompleteTextView" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:padding="10dp" 
       android:hint="Search location" 
       android:background="#FFFFFF" 
       android:textColor="#00000F" 
         android:theme="@android:style/Widget.Material.AutoCompleteTextView" 
       android:ems="10" 
       android:shadowColor="@color/background_floating_material_dark"> 
       <requestFocus /> 

      </AutoCompleteTextView> 

     </RelativeLayout> 

</RelativeLayout> 

回答

1

我看到你有一個AsyncTask從服務器訪問數據,但你並不真的需要一個AsyncTask因爲performFiltering()已經在運行背景,所以你可以把你的doInBackground()邏輯放在performFiltering()

  @Override 
      protected FilterResults performFiltering(CharSequence constraint) { 

       ArrayList<String> resultList = null; 
       FilterResults filterResults = new FilterResults(); 

       if (constraint != null) { 
        // Retrieve the autocomplete results. 
        Log.d(TAG, "Starting Search"); 

        HttpURLConnection conn = null; 
        StringBuilder jsonResults = new StringBuilder(); 
        try { 
         KEYWORD = constraint.toString(); 

         ENDPOINT = Uri 
           .parse("https://maps.googleapis.com/maps/api/place/nearbysearch/json") 
           .buildUpon() 
           .appendQueryParameter("location", LOCATION) 
           .appendQueryParameter("radius", "10000") 
           .appendQueryParameter("keyword", KEYWORD) 
           .appendQueryParameter("key", API_KEY) 
           .build(); 

         URL url = new URL(ENDPOINT.toString()); 

         Log.d(TAG, "URL: " + url); 

         conn = (HttpURLConnection) url.openConnection(); 
         InputStreamReader in = new InputStreamReader(conn.getInputStream()); 

         // Load the results into a StringBuilder 
         int read; 
         char[] buff = new char[1024]; 
         while ((read = in.read(buff)) != -1) { 
          jsonResults.append(buff, 0, read); 
         } 
         Log.d(TAG, jsonResults.toString()); 
        } catch (MalformedURLException e) { 
         Log.e(TAG, "Error processing Places API URL", e); 
         return filterResults ; 
        } catch (IOException e) { 
         Log.e(TAG, "Error connecting to Places API", e); 
         return filterResults ; 
        } finally { 
         if (conn != null) { 
          conn.disconnect(); 
         } 
        } 
        try { 
         // Create a JSON object hierarchy from the results 
         JSONObject jsonObj = new JSONObject(jsonResults.toString()); 
         JSONArray predsJsonArray = jsonObj.getJSONArray("results"); 

         // Extract the Place descriptions from the results 
         resultList = new ArrayList(predsJsonArray.length()); 
         for (int i = 0; i < predsJsonArray.length(); i++) { 
          System.out.println(predsJsonArray.getJSONObject(i).getString("name")); 
          System.out.println(predsJsonArray.getJSONObject(i).getString("vicinity")); 
          System.out.println("====================================================="); 
          resultList.add(predsJsonArray.getJSONObject(i).getString("name")); 
          resultList.add(predsJsonArray.getJSONObject(i).getString("vicinity")); 
         } 
        } catch (JSONException e) { 
         Log.e(TAG, "Cannot process JSON results", e); 
        } 
        Log.d(TAG, resultList.toString()); 

        // Assign the data to the FilterResults 
        filterResults.values = resultList; 
        filterResults.count = resultList.size(); 
       } 
       return filterResults; 
      } 

一個Filter的作品就像一個AsyncTaskperformFiltering就像doInBackgroundpublishResults()就像onPostExecute()

順便提一下,不要在後臺線程中更新適配器列表。創建一個新列表並將其分配給FilterResults.values,然後在publishResults()中分配適配器列表。

publishResults()應該是這樣的:

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

我覺得這是工作,但它仍然沒有給我下拉。它也崩潰我的應用程序與錯誤「android.view.InflateException:二進制XML文件行#7:錯誤膨脹類片段」,然後「引起:java.lang.IllegalArgumentException:二進制XML文件行#7:重複ID 0x7f0d0090,將null標記爲null,或將父標識0xffffffff與com.google.android.gms.maps.SupportMapFragment的另一個片段「相關聯。我認爲這個錯誤出現在我的XML中,所以我將它添加到了問題中。有什麼想法? – zahudson95

+1

因此,您在某個佈局XML文件中出現錯誤。發佈另一個關於你的佈局XML的問題。一旦你理清了,如果你仍然有自動完成問題,請在這裏發表評論,我們會再看一次。 –

+0

哦,只是看到你的編輯。我不確定,但我認爲這是抱怨,因爲包含地圖片段的'RelativeLayout'沒有ID。 –