2016-10-24 42 views
-1

我想運行一個地圖應用程序,但也表現出一些錯誤GoogleApiClient顯示空指針錯誤

的logcat:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tracker.systechdigital.realtimetrackingandmonitoring/com.tracker.systechdigital.realtimetrackingandmonitoring.NavigationDrawerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.api.GoogleApiClient.connect()' on a null object reference 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2521) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2595) 
    at android.app.ActivityThread.access$800(ActivityThread.java:178) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470) 
    at android.os.Handler.dispatchMessage(Handler.java:111) 
    at android.os.Looper.loop(Looper.java:194) 
    at android.app.ActivityThread.main(ActivityThread.java:5631) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754) 

搖籃:

dependencies { 
    compile fileTree(include: ['*.jar'], dir: 'libs') 
    testCompile 'junit:junit:4.12' 
    compile 'com.android.support:appcompat-v7:23.1.1' 
    compile 'com.android.support:design:23.1.1' 
    compile 'com.google.android.gms:play-services:9.6.1' 
    compile 'com.google.maps.android:android-maps-utils:0.3.4' 
    compile 'com.android.support:support-v4:23.1.1' 
    compile 'com.squareup.picasso:picasso:2.5.2' 
    compile 'com.google.android.gms:play-services-location:9.6.1' 
    compile 'com.google.android.gms:play-services-maps:9.6.1' 

} 

的Java:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_navigation_drawer); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    context = NavigationDrawerActivity.this; 

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
      this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
    drawer.setDrawerListener(toggle); 
    toggle.syncState(); 

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
    navigationView.setNavigationItemSelectedListener(this); 
    View hView = navigationView.getHeaderView(0); 


    ownProfilePic = (ImageView) hView.findViewById(R.id.ownImageShowDrawerHeaderIvId_navigationDrawer); 
    ownNameShow = (TextView) hView.findViewById(R.id.showUserNameTvId_navigationDrawer); 

    /****************************** own profile name and image show ************************** */ 


    ownNameShow.setText(UserInfo.getOwnProfileName()); 
    //  new ImageDownloaderTask(ownProfilePic).execute(UserInfo.ownProfilePicUrl); 
    Picasso.with(context).load(UserInfo.getOwnProfilePicUrl()).resize(100, 100).placeholder(R.drawable.profile_show).error(R.drawable.profile_show).transform(new CircleTransform()).into(ownProfilePic); 

    // 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 (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 

     return; 
    } 
    this.lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

    Criteria criteria = new Criteria(); 
    provider = lm.getBestProvider(criteria, false); 
    location = this.lm.getLastKnownLocation(provider); 
    this.locationListener = new NavigationDrawerActivity(); 
    this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, locationListener); 


    if (location != null) { 

     setUpMapIfNeeded(location); 
     updateUserLatLong(location); 

    } 
    // ATTENTION: This was auto-generated to implement the App Indexing API. 
    // See https://g.co/AppIndexing/AndroidStudio for more information. 
    if (client == null) 
     client = new GoogleApiClient.Builder(this).addOnConnectionFailedListener(this).addConnectionCallbacks(this).addApi(AppIndex.API).build(); 

    //route 
} 

@Override 

protected void onResume() { 
    super.onResume(); 
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 

     return; 

    } 
    Location location = this.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
    if (location != null) { 
     setUpMapIfNeeded(location); 
    } 

} 

public void onStart() { 
    super.onStart(); 

    // ATTENTION: This was auto-generated to implement the App Indexing API. 
    // See https://g.co/AppIndexing/AndroidStudio for more information. 
    //  if(client!=null) 
    client.connect(); 
    Action viewAction = Action.newAction(
      Action.TYPE_VIEW, // TODO: choose an action type. 
      "Maps Page", // TODO: Define a title for the content shown. 
      // TODO: If you have web page content that matches this app activity's content, 
      // make sure this auto-generated web page URL is correct. 
      // Otherwise, set the URL to null. 
      Uri.parse("http://host/path"), 
      // TODO: Make sure this auto-generated app deep link URI is correct. 
      Uri.parse("android-app://com.tracker.systechdigital.realtimetrackingandmonitoring/http/host/path") 
    ); 
    AppIndex.AppIndexApi.start(client, viewAction); 
} 

@Override 
public void onMapReady(GoogleMap googleMap) { 

    this.mMap = googleMap; 

    mMap.setMyLocationEnabled(true); 
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     return; 
    } 
    Location location = this.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 

    if (location != null) { 
     setUpMapIfNeeded(location); 

     UserInfo.setLat(location.getLatitude()); 
     UserInfo.setLng(location.getLongitude()); 
     UserInfo.setLocation(location); 
    } 
    //setUpMapIfNeeded(location); 

    mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() { 
     @Override 
     public void onInfoWindowClick(Marker marker) { 

      Intent intent = new Intent(context, Live_MapActivity.class); 
      intent.putExtra("Driver", "anyFriend"); 

      UserInfo.setFriendsId(friendIds.optString(marker.getId())); 
      startActivity(intent); 

      Toast.makeText(context, "You tracking " + marker.getTitle(), Toast.LENGTH_LONG).show(); 

     } 
    }); 
} 

@Override 
public void onLocationChanged(Location location) { 

    if (location != null && SharedPreference.getDefaults("ownUserId", context) != "0") { 

     updateUserLatLong(location); 
     //setUpMapIfNeeded(location); 
     float speed = location.getSpeed(); 
     UserInfo.setSpeed(speed); 

     UserInfo.setLat(location.getLatitude()); 
     UserInfo.setLng(location.getLongitude()); 
     UserInfo.setLocation(location); 
    } 
    userPosition = new LatLng(location.getLatitude(), 
      location.getLongitude()); 

    if (mMap != null) { 
     mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userPosition, 
       12)); 
     mMap.setMapType(UserInfo.getMapType()); 
    } 


    //updateUserLatLong(location); 


    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 

    { 

     return; 
    } 

    //  Criteria criteria = new Criteria(); 
    //  criteria.setAccuracy(Criteria.ACCURACY_COARSE); 

    LatLng userPosition = new LatLng(location.getLatitude(), 
      location.getLongitude()); 

    if (mMap != null) { 
     mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userPosition, 
       UserInfo.getZoomLevel())); 

     mMap.setMapType(UserInfo.getMapType()); 

     userFriendsPos(); 

    } 
    // Do a null check to confirm that we have not already instantiated the map. 
    if (mMap == null) { 
     // Try to obtain the map from the SupportMapFragment. 
     ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this); 

     //   mMap.setMyLocationEnabled(true); 
    } 
} 

@Override 
public void onStop() { 
    super.onStop(); 

    // ATTENTION: This was auto-generated to implement the App Indexing API. 
    // See https://g.co/AppIndexing/AndroidStudio for more information. 
    Action viewAction = Action.newAction(
      Action.TYPE_VIEW, // TODO: choose an action type. 
      "Maps Page", // TODO: Define a title for the content shown. 
      // TODO: If you have web page content that matches this app activity's content, 

      // make sure this auto-generated web page URL is correct. 
      // Otherwise, set the URL to null. 

      Uri.parse("http://host/path"), 
      // TODO: Make sure this auto-generated app deep link URI is correct. 
      Uri.parse("android-app://com.tracker.systechdigital.realtimetrackingandmonitoring/http/host/path") 
    ); 
    AppIndex.AppIndexApi.end(client, viewAction); 
    client.disconnect(); 
} 

@Override 
public void onConnected(Bundle bundle) { 

    Action viewAction = Action.newAction(
      Action.TYPE_VIEW, // TODO: choose an action type. 
      "Maps Page", // TODO: Define a title for the content shown. 
      // TODO: If you have web page content that matches this app activity's content, 
      // make sure this auto-generated web page URL is correct. 
      // Otherwise, set the URL to null. 
      Uri.parse("http://host/path"), 
      // TODO: Make sure this auto-generated app deep link URI is correct. 
      Uri.parse("android-app://com.tracker.systechdigital.realtimetrackingandmonitoring/http/host/path") 
    ); 
    AppIndex.AppIndexApi.start(client, viewAction); 

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    location = LocationServices.FusedLocationApi.getLastLocation(
      client); 


} 

任何人都可以請解決是。我找不到那裏需要的正確的東西。我編輯的問題,增加了oncreated方法

+0

不清楚!發表你的錯誤msg – Anurag

+1

我認爲'if(client!= null)'應該是'if(client == null)'。 –

+0

未使用該@SuperThomasLab解決 – AAA

回答

1

更換您的onCreate方法用下面的代碼:

private static final int MY_PERMISSION_REQUEST_CODE = 1; 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_navigation_drawer); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    context = NavigationDrawerActivity.this; 

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
      this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
    drawer.setDrawerListener(toggle); 
    toggle.syncState(); 

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
    navigationView.setNavigationItemSelectedListener(this); 
    View hView = navigationView.getHeaderView(0); 


    ownProfilePic = (ImageView) hView.findViewById(R.id.ownImageShowDrawerHeaderIvId_navigationDrawer); 
    ownNameShow = (TextView) hView.findViewById(R.id.showUserNameTvId_navigationDrawer); 

    /****************************** own profile name and image show ************************** */ 


    ownNameShow.setText(UserInfo.getOwnProfileName()); 
    //  new ImageDownloaderTask(ownProfilePic).execute(UserInfo.ownProfilePicUrl); 
    Picasso.with(context).load(UserInfo.getOwnProfilePicUrl()).resize(100, 100).placeholder(R.drawable.profile_show).error(R.drawable.profile_show).transform(new CircleTransform()).into(ownProfilePic); 

    // 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 (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     ActivityCompat.requestPermissions(
       this, 
       new String[]{ 
         Manifest.permission.ACCESS_FINE_LOCATION, 
         Manifest.permission.ACCESS_COARSE_LOCATION 
       }, 
       MY_PERMISSION_REQUEST_CODE 
     ); 
     return; 
    } else { 
     setupLocation(); 
    } 

    // ATTENTION: This was auto-generated to implement the App Indexing API. 
    // See https://g.co/AppIndexing/AndroidStudio for more information. 
    if (client == null) 
     client = new GoogleApiClient.Builder(this) 
       .addOnConnectionFailedListener(this) 
       .addConnectionCallbacks(this) 
       .addApi(AppIndex.API) 
       .build(); 

    //route 
} 

@Override 
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 
    super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
    switch (requestCode) { 
     case MY_PERMISSION_REQUEST_CODE: 
      if (grantResults[0] == PackageManager.PERMISSION_DENIED || grantResults[1] == PackageManager.PERMISSION_DENIED) { 
       // TODO 
       finish(); 
       return; 
      } 

      setupLocation(); 
      break; 
    } 
} 

private void setupLocation() { 
    this.lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

    Criteria criteria = new Criteria(); 
    provider = lm.getBestProvider(criteria, false); 
    location = this.lm.getLastKnownLocation(provider); 
    this.locationListener = new NavigationDrawerActivity(); 
    this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, locationListener); 


    if (location != null) { 

     setUpMapIfNeeded(location); 
     updateUserLatLong(location); 

    } 
} 
+0

沒有解決與這個人 – AAA

+0

@AAA你確定嗎?你能發佈完整的java代碼嗎? –

+0

@AAA代碼崩潰了哪行? –