2013-07-30 65 views
-4

問題:無法從MainActiviy> MapActivity的按鈕單擊開始活動。Android開發中的開始活動(NullPointerException)出錯

P/s:我按照這個地圖教程並更改類名並將所有元素複製到我的項目工作區。 This Tutorial

按鈕偵聽

public void onClick(View v) { 
       Intent intent = new Intent(getApplicationContext(), 
         MapActivity.class); 
       startActivity(intent);} 

logcat的:

07-31 02:22:58.267: E/AndroidRuntime(20784): FATAL EXCEPTION: main 
07-31 02:22:58.267: E/AndroidRuntime(20784): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fa.financeassistant/com.fa.financeassistant.MapActivity}: java.lang.NullPointerException 
07-31 02:22:58.267: E/AndroidRuntime(20784): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308) 
07-31 02:22:58.267: E/AndroidRuntime(20784): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358) 
07-31 02:22:58.267: E/AndroidRuntime(20784): at android.app.ActivityThread.access$600(ActivityThread.java:153) 
07-31 02:22:58.267: E/AndroidRuntime(20784): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247) 
07-31 02:22:58.267: E/AndroidRuntime(20784): at android.os.Handler.dispatchMessage(Handler.java:99) 
07-31 02:22:58.267: E/AndroidRuntime(20784): at android.os.Looper.loop(Looper.java:137) 
07-31 02:22:58.267: E/AndroidRuntime(20784): at android.app.ActivityThread.main(ActivityThread.java:5227) 
07-31 02:22:58.267: E/AndroidRuntime(20784): at java.lang.reflect.Method.invokeNative(Native Method) 
07-31 02:22:58.267: E/AndroidRuntime(20784): at java.lang.reflect.Method.invoke(Method.java:511) 
07-31 02:22:58.267: E/AndroidRuntime(20784): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795) 
07-31 02:22:58.267: E/AndroidRuntime(20784): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562) 
07-31 02:22:58.267: E/AndroidRuntime(20784): at dalvik.system.NativeStart.main(Native Method) 
07-31 02:22:58.267: E/AndroidRuntime(20784): Caused by: java.lang.NullPointerException 
07-31 02:22:58.267: E/AndroidRuntime(20784): at com.fa.financeassistant.MapActivity.onCreate(MapActivity.java:46) 
07-31 02:22:58.267: E/AndroidRuntime(20784): at android.app.Activity.performCreate(Activity.java:5104) 
07-31 02:22:58.267: E/AndroidRuntime(20784): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 
07-31 02:22:58.267: E/AndroidRuntime(20784): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2262) 
07-31 02:22:58.267: E/AndroidRuntime(20784): ... 11 more 

我MapActivity類

package com.fa.financeassistant; 

import java.util.ArrayList; 

import android.R.array; 
import android.app.ActionBar; 
import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Context; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 
import android.widget.ArrayAdapter; 

import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.MapFragment; 
import com.google.android.gms.maps.model.BitmapDescriptorFactory; 
import com.google.android.gms.maps.model.CameraPosition; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 


public class MapActivity extends Activity { 


    private final String TAG = getClass().getSimpleName(); 
    private GoogleMap mMap; 
    private String[] places; 
    private LocationManager locationManager; 
    private Location loc; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.mapactivity); 
     initCompo(); 
     places = getResources().getStringArray(R.array.places); 
     currentLocation(); 
     final ActionBar actionBar = getActionBar(); 
     actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); 
     actionBar.setListNavigationCallbacks(ArrayAdapter.createFromResource(
       this, R.array.places, android.R.layout.simple_list_item_1), 
       new ActionBar.OnNavigationListener() { 

        @Override 
        public boolean onNavigationItemSelected(int itemPosition, 
          long itemId) { 
         Log.e(TAG, 
           places[itemPosition].toLowerCase().replace("-", 
             "_")); 
         if (loc != null) { 
          mMap.clear(); 
          new GetPlaces(MapActivity.this, 
            places[itemPosition].toLowerCase().replace(
              "-", "_").replace(" ", "_")).execute(); 
         } 
         return true; 
        } 

       }); 

    } 

    private class GetPlaces extends AsyncTask<Void, Void, ArrayList<Place>> { 

     private ProgressDialog dialog; 
     private Context context; 
     private String places; 

     public GetPlaces(Context context, String places) { 
      this.context = context; 
      this.places = places; 
     } 

     @Override 
     protected void onPostExecute(ArrayList<Place> result) { 
      super.onPostExecute(result); 
      if (dialog.isShowing()) { 
       dialog.dismiss(); 
      } 
      for (int i = 0; i < result.size(); i++) { 
       mMap.addMarker(new MarkerOptions() 
         .title(result.get(i).getName()) 
         .position(
           new LatLng(result.get(i).getLatitude(), result 
             .get(i).getLongitude())) 
         .icon(BitmapDescriptorFactory 
           .fromResource(R.drawable.pin)) 
         .snippet(result.get(i).getVicinity())); 
      } 
      CameraPosition cameraPosition = new CameraPosition.Builder() 
        .target(new LatLng(result.get(0).getLatitude(), result 
          .get(0).getLongitude())) // Sets the center of the map to 
              // Mountain View 
        .zoom(14) // Sets the zoom 
        .tilt(30) // Sets the tilt of the camera to 30 degrees 
        .build(); // Creates a CameraPosition from the builder 
      mMap.animateCamera(CameraUpdateFactory 
        .newCameraPosition(cameraPosition)); 
     } 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      dialog = new ProgressDialog(context); 
      dialog.setCancelable(false); 
      dialog.setMessage("Loading"); 
      dialog.isIndeterminate(); 
      dialog.show(); 
     } 

     @Override 
     protected ArrayList<Place> doInBackground(Void... arg0) { 
      PlacesService service = new PlacesService(
        "AIzaSyBquLw9vJPDHAZO8kzKw6ft0bPxsgBmblg"); 
      ArrayList<Place> findPlaces = service.findPlaces(loc.getLatitude(), // 28.632808 
        loc.getLongitude(), places); // 77.218276 

      for (int i = 0; i < findPlaces.size(); i++) { 

       Place placeDetail = findPlaces.get(i); 
       Log.e(TAG, "places : " + placeDetail.getName()); 
      } 
      return findPlaces; 
     } 

    } 

    private void initCompo() { 
     mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)) 
       .getMap(); 
    } 


    private void currentLocation() { 
     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

     String provider = locationManager 
       .getBestProvider(new Criteria(), false); 

     Location location = locationManager.getLastKnownLocation(provider); 

     if (location == null) { 
      locationManager.requestLocationUpdates(provider, 0, 0, listener); 
     } else { 
      loc = location; 
      new GetPlaces(MapActivity.this, places[0].toLowerCase().replace(
        "-", "_")).execute(); 
      Log.e(TAG, "location : " + location); 
     } 

    } 

    private LocationListener listener = new LocationListener() { 

     @Override 
     public void onStatusChanged(String provider, int status, Bundle extras) { 

     } 

     @Override 
     public void onProviderEnabled(String provider) { 

     } 

     @Override 
     public void onProviderDisabled(String provider) { 

     } 

     @Override 
     public void onLocationChanged(Location location) { 
      Log.e(TAG, "location update : " + location); 
      loc = location; 
      locationManager.removeUpdates(listener); 
     } 
    }; 

} 

SOLUTION:除了下面給出的答案。我通過刪除這一行來應用快速修復,並像魅力一樣工作!感謝所有幫助過我的人。祝你有美好的一天:)

android:theme="@style/Theme.NoTitle" 
+0

什麼是第46行? – codeMagic

+0

確保'getActionBar()'不返回'null'。或者考慮到它可以返回null。 – MAV

+0

如果我已經計算正確,它是'actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);' - 在這一行上放置一個斷點。 ActionBar是否爲空? – Simon

回答

1

46行是;

actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); 

可以爲空在這裏的唯一的事情就是動作條,因此getActionBar()是返回null,這種情況的原因;

getActionBar() returns null - 標題欄不可見。

getActionBar returns null - 您必須使用getWindow().requestFeature(Window.FEATURE_ACTION_BAR);請求操作欄,您可能認爲您的信息欄是一個操作欄。

您應該能夠通過許多其他SO帖子問同樣的問題找到答案。

+0

感謝您的快速回復!有用! 對不起,在這個網站再次提出愚蠢的問題。 :P (我對開發非常陌生,我不知道NULL會導致這個問題。) – BlackHat

+0

將來,如果你得到一個NULL指針錯誤,找到它發生的代碼行並選擇所有的該語句中的變量可能爲NULL,然後斷開這一行或添加'System.out'並檢查哪些變量爲空。一旦你發現了NULL變量,追溯到它的創建,然後研究爲什麼它被創建爲NULL。這將幫助您解決絕大多數NULL指針錯誤。 – Robadob