谷歌地图使应用程序停止不幸

时间:2016-04-30 13:09:12

标签: android google-maps

我们正在使用Android应用程序,第一页是启动画面,后一页是谷歌地图。这个谷歌地图活动使应用程序停止在一些Android手机,如Android版本4.4.2。但在一些Android手机中它运行正常。谷歌地图是否对android API有一些限制。

在4.4.2版本的Android版本中运行时。它显示了这个错误。

java.lang.RuntimeException: Unable to start activity ComponentInfo{salon.com.barber/salon.com.barber.GoogleMapsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2342)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1266)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5421)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:970)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:786)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at salon.com.barber.GoogleMapsActivity.populateMap(GoogleMapsActivity.java:287)
at salon.com.barber.GoogleMapsActivity.onCreate(GoogleMapsActivity.java:205)
at android.app.Activity.performCreate(Activity.java:5263)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1099)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
... 11 more

我的Google地图活动

 public class GoogleMapsActivity extends FragmentActivity  {

ImageButton imageButton;
NavDrawerListAdapterSalonDetails adapternav;
DrawerLayout dLayout;
List<NavDrawerSalonDetailsItem> menu;
private ProgressDialog pDialog;
ListView dList1;
private GoogleMap mMap;
GPSTracker gps;
boolean isGpsON;
ArrayList<String> arry_salondetails;
String SaloonDetails = "";
String Street = null;
String Zipcode = null;
String HouseNumber = null;
String City = null;
//final ArrayList<String> SalonNames = new ArrayList<String>();
final HashMap SalonData = new HashMap();

 double lati,longi;
final ArrayList<String> serviceDataList = new ArrayList<String>();
Boolean isInternetPresent;
JSONObject objectNextClass;
private GoogleMap googleMap;
JSONArray saloonDetails = null;
RelativeLayout selectedLayout;
double latitude, longitude, range;
String tableName = "barber";
Marker selectedMarker;
ImageButton button_bookmark ;
String objectId = "";
public static final String BARBER_MAP_PREFS = "MAP_PREFS";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);




    setContentView(R.layout.activity_google_maps);
    selectedLayout = (RelativeLayout) findViewById(R.id.selectedView);


    networkCheck cd = new networkCheck(getApplicationContext());
    isInternetPresent = cd.isConnectingToInternet(); // true or
    // false

    Log.i("sfeeee", "wwwwwww111w");




    SharedPreferences prefs = getSharedPreferences(BARBER_MAP_PREFS, MODE_PRIVATE);
    String r = prefs.getString("range", null);
    if (r == null) {
        SharedPreferences.Editor editor = prefs.edit();

        editor.putString("range", "10");
        editor.commit();
    }


    AndroidLog.appendLog("En:2");
    imageButton =(ImageButton) findViewById(R.id.Search_btn);

    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        // On click function
        public void onClick(View view) {
            // Create the intent to start another activity
            Log.i("sfeeee1111111", "wwwwwwww");
            Intent i = new Intent(GoogleMapsActivity.this, Search.class);
            startActivity(i);
        }
    });


    AndroidLog.appendLog("Ex:2");


    dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    dList1 = (ListView) findViewById(R.id.list_slidermenu);

    menu = getNavDraweItemList();
    adapternav = new NavDrawerListAdapterSalonDetails(this, menu);
    LayoutInflater inflater=this.getLayoutInflater();
    View header=inflater.inflate(R.layout.footer, null);
    dList1.addHeaderView(header);
    dList1.setAdapter(adapternav);

    ImageButton buttonMenu =((ImageButton) findViewById(R.id.buttonMenu));

    dList1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            getListPosition(position);


            // TODO Auto-generated method stub

        }
    });

    buttonMenu.setOnClickListener(new View.OnClickListener() {
        @Override
        // On click function
        public void onClick(View view) {

            dLayout.openDrawer(dList1);

        }
    });


    ImageButton  button_map=(ImageButton) findViewById(R.id.button_map);
    Log.i("111111111111111", "qqqqqqqqqqqqq");
    button_map.setOnClickListener(new View.OnClickListener() {
        @Override
        // On click function
        public void onClick(View view) {
            // Create the intent to start another activity

            if (isInternetPresent) {
                LatLng myCurrentLoc = getCurrentLoaction();
                Log.i("mycurrentLoc", myCurrentLoc.toString());
                Log.i("2222222222211", "qqqqqqqqqqqqq");
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                        (myCurrentLoc), 11));
                Log.i("3333333333333331", "qqqqqqqqqqqqq");
            }
        }
    });



    AndroidLog.appendLog("En:3");
    if (isInternetPresent) {
        // Calling async task to get json
        //new getLocationData().execute();
        populateMap();
        AndroidLog.appendLog("Ex:3");
        Log.i("4444444411111", "qqqqqqqqqqqqq");
    } else {

        // Internet connection  not present
        // Ask user to connect to Internet
        showAlertDialog(GoogleMapsActivity.this, "No Internet Connection",
                "You don't have internet connection.", false);
    }



    selectedLayout.setVisibility(View.GONE);
    Button button = ((Button) selectedLayout
            .findViewById(R.id.selec_button_id));

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        // On click function
        public void onClick(View view) {
            // Create the intent to start another activity
            Intent intent = new Intent(view.getContext(),
                    Salon_Detail.class);

            //intent.putExtra("SalonName", (CharSequence) nameView);

            // intent.putExtra("json", objectNextClass.toString());

            startActivity(intent);
        }
    });


}




public void onDestroy() {
    super.onDestroy();
    SharedPreferences prefs = getSharedPreferences(BARBER_MAP_PREFS, MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.clear();

}





public void populateMap(){

    Log.d("searched", "map");

    pDialog = new ProgressDialog(GoogleMapsActivity.this);
    pDialog.setMessage("Please wait...");
    pDialog.setCancelable(false);
    pDialog.show();

    if (mMap == null) {
        mMap = ((MapFragment) getFragmentManager()
                .findFragmentById(R.id.map)).getMap();
    }

    LatLng myCurrentLoc = getCurrentLoaction();
    if(!isGpsON)
    {
        Toast.makeText(getApplicationContext(),"Switch on the location service for more  accuracy",
                30000).show();

    }
    Log.i("Latti and Longii", myCurrentLoc.toString());
    latitude = myCurrentLoc.latitude;
    Log.i("latitude of current Loc", String.valueOf(latitude));

    longitude = myCurrentLoc.longitude;
    Log.i("longitudeofcurrent Loc",String.valueOf(longitude));

   mMap.addCircle(new CircleOptions()

            .center(new LatLng(myCurrentLoc.latitude,
                    myCurrentLoc.longitude)).radius(10000)
            .strokeColor(Color.parseColor("#34DDDD")).strokeWidth(6.0f)
                .fillColor(Color.parseColor("#93D5E4")));

    Log.i("777777777777777", "qqqqqqqqqqqqq");

    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
            (myCurrentLoc), 11));
    Log.i("666666666666666666", "qqqqqqqqqqqqq");
    Marker TP = mMap.addMarker(new MarkerOptions().position(
            myCurrentLoc).title("").icon(BitmapDescriptorFactory.fromResource(R.mipmap.pin_blue)));
    //icon(BitmapDescriptorFactory.fromResource(R.drawable.navigate))

    TP.showInfoWindow();
    Log.i("5555555555555555555555", "qqqqqqqqqqqqq");
    TP.setSnippet("currentLocation");


    SharedPreferences prefs = getSharedPreferences(BARBER_MAP_PREFS, MODE_PRIVATE);
    range = Double.parseDouble(prefs.getString("range",null));


    //range = 100;




    new GmapUtil().onGetCustomMarkers(getApplicationContext(), longitude, latitude, range, tableName,
            new GmapUtil.CustomMarker() {
                @Override
                public void onSuccess(String data) {
                    Log.i("resulttttttt od dataaa", data);
                    pDialog.hide();

                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        Log.i("jsonObjectttttttttttt", jsonObject.toString());
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        Log.i("jsonObjecttttttt1", jsonObject1.toString());
                        JSONArray jsonArray = jsonObject1.getJSONArray("results");

                        for (int i = 0; i < jsonArray.length(); i++) {
                            final JSONObject child = jsonArray.getJSONObject(i);
                            //final String sName = child.getString("SalonName");
                            //SalonNames.add(child.getString("SalonName"));
                            //Log.i("salonn namesss", SalonNames.toString());
                            latitude = child.getDouble("Latitude");
                            longitude = child.getDouble("Longitude");
                            LatLng saloonLoc = new LatLng(latitude, longitude);
                            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                            Marker marker = mMap.addMarker(new MarkerOptions()
                                    .position(saloonLoc).title("TutorialsPoint").icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_red)));

                            marker.setSnippet(child.getString("objectId"));
                            SalonData.put(child.getString("objectId"), child);
                            Log.i("8888888888888888", "qqqqqqqqqqqqq");
                            // googleMap.setOnMarkerClickListener(this);

                            mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

                                        @Override
                                        public boolean onMarkerClick(Marker marker) {

                                            SaloonDetails = "";
                                            // Take some action here
                                            String snippet = marker.getSnippet();
                                            objectId = snippet;

                                            if (selectedMarker != null && !("currentLocation".equals(snippet))) {
                                                selectedMarker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.map_red));

                                            }

                                            selectedMarker = marker;
                                            if (!("currentLocation".equals(snippet)))
                                                marker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.map_blue));


                                            Log.i("TAG", "snippet::::" + snippet);

                                            if ("currentLocation".equals(snippet)) {
                                                selectedLayout.setVisibility(View.GONE);
                                                //button_bookmark.setVisibility(View.GONE);
                                                return false;
                                            } else {

                                                selectedLayout
                                                        .setVisibility(View.VISIBLE);



                                                TextView nameView = ((TextView) selectedLayout
                                                        .findViewById(R.id.name_txt_id));
                                                TextView addressView = ((TextView) selectedLayout
                                                        .findViewById(R.id.address_txt_id));



                                                try {
                                                    JSONObject jSalonData = (JSONObject)SalonData.get(snippet);

                                                    nameView.setText(jSalonData.getString("SalonName"));
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }


                                                try {
                                                    JSONObject jSalonData = (JSONObject)SalonData.get(snippet);
                                                    Log.i("jSalonData",jSalonData.toString());

                                                    //addressView.append(System.getProperty("line.separator"));
                                                    City = jSalonData.optString("City");
                                                    SaloonDetails = SaloonDetails + City;
                                                    Zipcode = jSalonData.optString("Zipcode");
                                                    SaloonDetails = SaloonDetails  +" "+ Zipcode;
                                                    HouseNumber = jSalonData.optString("HouseNumber");
                                                    SaloonDetails = SaloonDetails  +" "+ HouseNumber;
                                                    Street = jSalonData.optString("Street");
                                                    SaloonDetails = SaloonDetails +" "+ Street;
                                                    Log.i("SaloonDetails", SaloonDetails);
                                                    //addressView.setText(jSalonData.getString("Zipcode"));
                                                    //addressView.setText(jSalonData.getString("City"));
                                                    addressView.setText(SaloonDetails);

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

                                    });

                        }

                    } catch (Exception e) {
                        Log.i("Exception", e.toString());
                    }


                }

                @Override
                public void onError(String data) {

                }
            });

}



private LatLng getCurrentLoaction() {
    // TODO Auto-generated method stub
    Log.i("sfeeee","wwwwwwww");
    gps = new GPSTracker(GoogleMapsActivity.this);

    // check if GPS enabled
    if (gps.canGetLocation()) {
        isGpsON=true;
        double latitude = gps.getLatitude();
        double longitude = gps.getLongitude();

        LatLng latLng = new LatLng(latitude, longitude);
        Log.i("Latiiiiiiiiii",latLng.toString());
        return latLng;
        // \n is for new line
    } else {
        // can't get location
        // GPS or Network is not enabled
        // Ask user to enable GPS/network in settings
        isGpsON=false;
        LatLng latLng = new LatLng(52.156111,5.387827);
        return latLng;

    }

}

private List<NavDrawerSalonDetailsItem> getNavDraweItemList() {


    String search = "Search";
    String Privacypolicy = "Privacy policy";
    String termsofconditions = "Terms and Conditions";
    String favorite = " Favourites";
    String Setting = "Settings";

    String[] list = new String[] {search, Privacypolicy,termsofconditions,favorite,Setting};
    int[] icons = { R.mipmap.small_search, R.mipmap.small_about_us };
    List<NavDrawerSalonDetailsItem> menu = new ArrayList<NavDrawerSalonDetailsItem>();
    for (int i = 0; i < list.length; i++) {
        menu.add(new NavDrawerSalonDetailsItem(list[i], i));
    }

    return menu;
}





/**
 * Function to display simple Alert Dialog
 *
 * @param context
 *            - application context
 * @param title
 *            - alert dialog title
 * @param message
 *            - alert message
 * @param status
 *            - success/failure (used to set icon)
 * */
@SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message,
                            Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();
    // Setting Dialog Title
    alertDialog.setTitle(title);
    // Setting Dialog Message
    alertDialog.setMessage(message);
    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(final DialogInterface dialog, final int which) {

        }
    });

    // Showing Alert Message
    alertDialog.show();
}


public void search(){

    // Create the intent to start another activity
    Intent intent = new Intent(GoogleMapsActivity.this, Search.class);

    startActivity(intent);
}

public void privacyPolicy(){


    // Create the intent to start another activity
    Intent intent = new Intent(GoogleMapsActivity.this, privacypolicy.class);

    startActivity(intent);

}

public void termsAndCondition(){


    // Create the intent to start another activity
    Intent intent = new Intent(GoogleMapsActivity.this, Terms_and_condition.class);

    startActivity(intent);

}

public void favorite(){
    Intent intent = new Intent(GoogleMapsActivity.this,comingsoon.class);
    startActivity(intent);
}

public void Settings(){
    Intent intent = new Intent(GoogleMapsActivity.this,comingsoon.class);
    startActivity(intent);
}




public void getListPosition(int position) {

    switch (position) {
        case 1: {

            search();

            break;
        }
        case 2: {
            privacyPolicy();
            break;
        }
       case 3: {
            termsAndCondition();
            break;
        }
         case 4: {
            favorite();

            break;
        }
       case 5: {

            Settings();
            break;
        }
        default: {

            break;
        }

    }

}

}

1 个答案:

答案 0 :(得分:2)

要确保您使用的是GoogleMap的非null实例,您应该实现OnMapReadyCallback。来自文档https://developers.google.com/android/reference/com/google/android/gms/maps/OnMapReadyCallback

  

在MapFragment或MapView对象上设置此接口的实例后,当地图准备好使用时会触发onMapReady(GoogleMap)方法并提供GoogleMap的非空实例。

因此,您的GoogleMapsActivity需要实施OnMapReadyCallback,您必须将调用populateMap();方法转移到onMapReady方法:

public class GoogleMapsActivity extends FragmentActivity implements OnMapReadyCallback {
    // ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Remove populateMap(); and change it for
        ((MapFragment) getFragmentManager()
            .findFragmentById(R.id.map)).getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        populateMap();
    }
}