0

我試圖讓Google Places連接到MapView,但得到錯誤,它之前工作正常,但在將Android庫更新到最新版本後出現錯誤。AsyncTask錯誤 - 在新的Android SDK更新後

請讓我知道錯誤發生了什麼。

06-20 05:41:47.429: E/AndroidRuntime(20755): FATAL EXCEPTION: main 
06-20 05:41:47.429: E/AndroidRuntime(20755): java.lang.NullPointerException 
06-20 05:41:47.429: E/AndroidRuntime(20755): at com.x.get2food.MainActivity$LoadPlaces$1.run(MainActivity.java:217) 
06-20 05:41:47.429: E/AndroidRuntime(20755): at android.app.Activity.runOnUiThread(Activity.java:3717) 
06-20 05:41:47.429: E/AndroidRuntime(20755): at com.x.get2food.MainActivity$LoadPlaces.onPostExecute(MainActivity.java:211) 
06-20 05:41:47.429: E/AndroidRuntime(20755): at com.x.get2food.MainActivity$LoadPlaces.onPostExecute(MainActivity.java:1) 
06-20 05:41:47.429: E/AndroidRuntime(20755): at android.os.AsyncTask.finish(AsyncTask.java:417) 
06-20 05:41:47.429: E/AndroidRuntime(20755): at android.os.AsyncTask.access$300(AsyncTask.java:127) 
06-20 05:41:47.429: E/AndroidRuntime(20755): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429) 
06-20 05:41:47.429: E/AndroidRuntime(20755): at android.os.Handler.dispatchMessage(Handler.java:99) 
06-20 05:41:47.429: E/AndroidRuntime(20755): at android.os.Looper.loop(Looper.java:123) 
06-20 05:41:47.429: E/AndroidRuntime(20755): at android.app.ActivityThread.main(ActivityThread.java:3687) 
06-20 05:41:47.429: E/AndroidRuntime(20755): at java.lang.reflect.Method.invokeNative(Native Method) 
06-20 05:41:47.429: E/AndroidRuntime(20755): at java.lang.reflect.Method.invoke(Method.java:507) 
06-20 05:41:47.429: E/AndroidRuntime(20755): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842) 
06-20 05:41:47.429: E/AndroidRuntime(20755): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 
06-20 05:41:47.429: E/AndroidRuntime(20755): at dalvik.system.NativeStart.main(Native Method) 

錯誤區域;

 // calling background Async task to load Google Places 
     // After getting places from Google all the data is shown in listview 
     // Fired @ onCreate() 
     try{ 

      new LoadPlaces().execute(); 

     }catch(Exception e){} 

/** 
* Background Async Task to Load Google places 
* */ 
class LoadPlaces extends AsyncTask<String, String, String> { 

    /** 
    * Before starting background thread Show Progress Dialog 
    * */ 
    protected void onPreExecute() 
    { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(MainActivity.this); 
     pDialog.setMessage(Html.fromHtml("Loading Places...")); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show(); 

    } 

    /** 
    * getting Places JSON 
    * */ 
    protected String doInBackground(String... args) { 
     googlePlaces = new GooglePlaces(); 

     try { 

      String types = "bus_station"; 
      double radius = 1000; 
      nearPlaces = googlePlaces.search(gps.getLatitude(), 
        gps.getLongitude(), radius, types); 


     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    protected void onPostExecute(String file_url) { 
     // dismiss the dialog after getting all products 
     pDialog.dismiss(); 
     // updating UI from Background Thread 
     runOnUiThread(new Runnable() { 
      public void run() { 
       /** 
       * Updating parsed Places into LISTVIEW 
       * */ 
       // Get json response status 
       String status = nearPlaces.status; 

       // Check for all possible status 
       if(status.equals("OK")){ 
        // Successfully got places details 
        if (nearPlaces.results != null) { 
         // loop through each place 
         for (Place p : nearPlaces.results) { 
          HashMap<String, String> map = new HashMap<String, String>(); 

          map.put(KEY_REFERENCE, p.reference); 

          // Place name 
          map.put(KEY_NAME, p.name); 


          // adding HashMap to ArrayList 
          placesListItems.add(map); 
         } 
         // list adapter 
         ListAdapter adapter = new SimpleAdapter(MainActivity.this, placesListItems, 
           R.layout.list_item, 
           new String[] { KEY_REFERENCE, KEY_NAME}, new int[] { 
             R.id.reference, R.id.name }); 

         // Adding data into listview 
         lv.setAdapter(adapter); 
        } 
       } 
       else if(status.equals("ZERO_RESULTS")){ 
        // Zero results found 
        alert.showAlertDialog(MainActivity.this, "Near Places", 
          "Sorry no places found. Try to change the types of places", 
          false); 
       } 
       else if(status.equals("UNKNOWN_ERROR")) 
       { 
        alert.showAlertDialog(MainActivity.this, "Places Error", 
          "Sorry unknown error occured.", 
          false); 
       } 
       else if(status.equals("OVER_QUERY_LIMIT")) 
       { 
        alert.showAlertDialog(MainActivity.this, "Places Error", 
          "Sorry query limit to google places is reached", 
          false); 
       } 
       else if(status.equals("REQUEST_DENIED")) 
       { 
        alert.showAlertDialog(MainActivity.this, "Places Error", 
          "Sorry error occured. Request is denied", 
          false); 
       } 
       else if(status.equals("INVALID_REQUEST")) 
       { 
        alert.showAlertDialog(MainActivity.this, "Places Error", 
          "Sorry error occured. Invalid Request", 
          false); 
       } 
       else 
       { 
        alert.showAlertDialog(MainActivity.this, "Places Error", 
          "Sorry error occured.", 
          false); 
       } 
      } 
     }); 

    } 

} 

回答

0

您沒有以正確的方式使用AsyncTask。參數的用法是錯誤的。

  1. 你必須歸還從doInbackground到onPostExecute方法,也許地址的數組的東西,因爲你的doinbackground只是想下載的東西,而你已經訪問數據。嘗試讀取堆棧跟蹤,它指向您的217行代碼,也在您的runOnUiThread。在第217行,你的變量爲空。
  2. onPostExecute已經是一個uiThread方法,所以不應該在那裏執行runnables。正好你的代碼水木清華這樣的:
protected void onPostExecute(List<Address> addressList) { 
    for (Address address : addressList) { 
     YourActivity.this.displayAddressLines(address); 
    } 
} 
+0

嗨PAcan,謝謝你的回覆。我根據你所說的嘗試過,我不能使它工作..它崩潰。我已經上傳了最初的項目,鏈接;請快速瀏覽一下; http://www.reunioni.com/tests/Get2Food.zip(地圖庫可以在libs文件夾中找到) – GameBug

0

的問題是,你使用了錯誤的HTTP客戶端,這是已經過時,它沒有下載任何東西。你的數組「nearPlaces」爲null。嘗試使用標準的android http客戶端。閱讀:

http://android-developers.blogspot.ru/2011/09/androids-http-clients.html http://developer.android.com/training/basics/network-ops/connecting.html

對於使用的AsyncTask:你應該改變你的代碼水木清華這樣的:

class LoadPlaces extends AsyncTask<Void , Void, PlacesList> 
{ 

    /** 
    * Before starting background thread Show Progress Dialog 
    * */ 
    protected void onPreExecute() 
    { 
     super.onPreExecute(); 

     Log.d(TAG, "onPreExecute"); 
     /* 
     pDialog = new ProgressDialog(MainActivity.this); 
     pDialog.setMessage(Html.fromHtml("Loading Places...")); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show(); */ 

    } 

    @Override 
    protected PlacesList doInBackground(Void... params) { 
     Log.d(TAG, "doInBackground"); 

     // creating Places class object 
     googlePlaces = new GooglePlaces(); 
     try { 
      // Separeate your place types by PIPE symbol "|" 
      // If you want all types places make it as null 
      // Check list of types supported by google 
      // 
      String types = "bus_station"; 

      // Radius in meters 
      double radius = 1609.34; // 1609.34 meters = 1 mile 

      // get nearest places 
      nearPlaces = googlePlaces.search(gps.getLatitude(), 
        gps.getLongitude(), radius, types); 
      Log.d(TAG, nearPlaces.toString()); 


     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return nearPlaces; 
    } 


    /** 
    * After completing background task Dismiss the progress dialog 
    * and show the data in UI 
    * Always use runOnUiThread(new Runnable()) to update UI from background 
    * thread, otherwise you will get error 
    * **/ 
    @Override 
    protected void onPostExecute(PlacesList nearPlaces1) { 
     super.onPostExecute(nearPlaces1); 
     Log.d(TAG, "onPostExecute"); 

     nearPlaces=nearPlaces1; 


     // dismiss the dialog after getting all products 
     pDialog.dismiss(); 
     // updating UI from Background Thread 
     // updating UI from Background Thread 
     /* 
     runOnUiThread(new Runnable() { 
      public void run() { */ 


     /** 
     * Updating parsed Places into LISTVIEW 
     * */ 
     // Get json response status 
     String status = nearPlaces.status; 

     // Check for all possible status 
     if(status.equals("OK")) 
     { 

      // Successfully got places details 
      if (nearPlaces.results != null) 
      { 

       // loop through each place 
       for (Place p : nearPlaces.results) 
       { 

        HashMap<String, String> map = new HashMap<String, String>(); 

        // Place reference won't display in listview - it will be hidden 
        // Place reference is used to get "place full details" 
        map.put(KEY_REFERENCE, p.reference); 

        // Place name 
        map.put(KEY_NAME, p.name); 


        // adding HashMap to ArrayList 
        placesListItems.add(map); 
       } 

       // list adapter 
       ListAdapter adapter = new SimpleAdapter(MainActivity.this, placesListItems, 
         R.layout.list_item, 
         new String[] { KEY_REFERENCE, KEY_NAME}, new int[] { 
         R.id.reference, R.id.name }); 

       // Adding data into listview 
       lv.setAdapter(adapter); 

      } 
     } 
     else if(status.equals("ZERO_RESULTS")){ 
      // Zero results found 
      alert.showAlertDialog(MainActivity.this, "Near Places", 
        "Sorry no places found. Try to change the types of places", 
        false); 
     } 
     else if(status.equals("UNKNOWN_ERROR")) 
     { 
      alert.showAlertDialog(MainActivity.this, "Places Error", 
        "Sorry unknown error occured.", 
        false); 
     } 
     else if(status.equals("OVER_QUERY_LIMIT")) 
     { 
      alert.showAlertDialog(MainActivity.this, "Places Error", 
        "Sorry query limit to google places is reached", 
        false); 
     } 
     else if(status.equals("REQUEST_DENIED")) 
     { 
      alert.showAlertDialog(MainActivity.this, "Places Error", 
        "Sorry error occured. Request is denied", 
        false); 
     } 
     else if(status.equals("INVALID_REQUEST")) 
     { 
      alert.showAlertDialog(MainActivity.this, "Places Error", 
        "Sorry error occured. Invalid Request", 
        false); 
     } 
     else 
     { 
      alert.showAlertDialog(MainActivity.this, "Places Error", 
        "Sorry error occured.", 
        false); 
     } 
    } 
} 

它只是用正確的參數。

關於你的自定義對象:在android中,他們應該實現Parcelable接口,而不是標準的Java Serializable。 http://developer.android.com/reference/android/os/Parcelable.html

祝你好運!

+0

您好PAcan,非常感謝您的解決方案,異步任務現在更有意義。但我仍然遇到以下錯誤:NullPointerException; (MainActivity.java:221) mapplace.MainActivity $ LoadPlaces.onPostExecute(MainActivity.java:1) android.os.AsyncTask.finish $ 300(AsyncTask.java:127) – GameBug

+0

我在調試它,應用程序在它試圖用HTTPRequestFactory搜索位置時死亡,但它顯示它在onPostExecute中死亡,因爲它正在該部分中執行。 [code] HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT); HttpRequest請求= httpRequestFactory .buildGetRequest(new GenericUrl(PLACES_SEARCH_URL)); [/ code] – GameBug

+0

請再次閱讀我的答案。您正在使用錯誤的舊客戶端連接到互聯網並找到您的位置數組。請嘗試以下這些:http://android-developers.blogspot。ru/2011/09/androids-http-clients.html http://developer.android.com/training/basics/network-ops/connecting.html – PAcan