0

I have an app that shows user's current location on google map, the app runs in emulator (though it doesn't show location) however it crashes in real device. Here is the error I'm getting

01-04 15:00:59.509 26494-26494/io.xgear.geotag E/AndroidRuntime: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{io.xgear.geotag/io.xgear.geotag.MainActivity}: java.lang.NullPointerException

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659)

at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)

at android.app.ActivityThread.access$1500(ActivityThread.java:121)

at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)

at android.os.Handler.dispatchMessage(Handler.java:99)

at android.os.Looper.loop(Looper.java:130)

at android.app.ActivityThread.main(ActivityThread.java:3701)

at java.lang.reflect.Method.invokeNative(Native Method)

at java.lang.reflect.Method.invoke(Method.java:507)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)

at dalvik.system.NativeStart.main(Native Method)

Caused by: java.lang.NullPointerException

at io.xgear.geotag.MainActivity.onCreate(MainActivity.java:72)

at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)

at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675) 

at android.app.ActivityThread.access$1500(ActivityThread.java:121) 

at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943) 

at android.os.Handler.dispatchMessage(Handler.java:99) 

at android.os.Looper.loop(Looper.java:130) 

at android.app.ActivityThread.main(ActivityThread.java:3701) 

at java.lang.reflect.Method.invokeNative(Native Method) 

at java.lang.reflect.Method.invoke(Method.java:507) 

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624) 

at dalvik.system.NativeStart.main(Native Method)

 

and here's my code for main activity

package io.xgear.geotag;


import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import android.support.v4.app.Fragment;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import io.xgear.geotag.helper.Post;

public class MainActivity extends FragmentActivity implements LocationListener {
    GoogleMap googleMap;
    private GeoTagTask mAuthTask = null;
    //GPSTracker gps;
    private JSONObject jsonObj;

    // UI references.
    private EditText txtShopCode;
    private EditText lblAddress;
    private View mProgressView;
    private View mGeoTagForm;
    private Button btnGeoTag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.activity_main);

        txtShopCode = (EditText) findViewById(R.id.txtShopCode);
        btnGeoTag = (Button) findViewById(R.id.btnGeoTag);
        mGeoTagForm = (View) findViewById(R.id.geoTagForm);
        mProgressView = findViewById(R.id.geoTagProgress);
        if (!isGooglePlayServicesAvailable()) {
            finish();
        }
        setContentView(R.layout.activity_main);
        SupportMapFragment supportMapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
        googleMap = supportMapFragment.getMap();
        googleMap.setMyLocationEnabled(true);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, 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
            //    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 location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);

       // gps = new GPSTracker(MainActivity.this);
        btnGeoTag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String shopid = txtShopCode.getText().toString();
                boolean cancel = false;
                View focusView = null;

               //txtShopCode.setInputType(InputType.TYPE_CLASS_NUMBER);

                if (TextUtils.isEmpty(shopid)) {
                    txtShopCode.setError(getString(R.string.error_field_required));
                    focusView = txtShopCode;
                    cancel = true;

                }
                else {


                    showProgress(true);
                    mAuthTask = new GeoTagTask(shopid);
                    mAuthTask.execute((Void) null);
                }
            }

        });

    }


//
//    public void btnGeoTag_Click(View v){
//
//    }
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
            mGeoTagForm.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
        private final String shopCode;
       // private String lat= Double.toString( gps.getLatitude());
      //  private String lng = Double.toString( gps.getLongitude());
       Location location;
        private String lat = Double.toString(location.getLatitude());
        private String lng = Double.toString(location.getLongitude());
       // double longitude = location.getLongitude();
        private boolean isConnect;
        GeoTagTask(String shopId) {
            shopCode = shopId;
            isConnect = false;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            boolean res = false;
     try {
                ContentValues nameValuePairs = new ContentValues();
                nameValuePairs.put("Id", shopCode);
                nameValuePairs.put("lat", lat);
                nameValuePairs.put("lng", lng);
         //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
               Log.i("Latitude", lat+"");

                Post post = new Post(getApplicationContext());
                String result = "";
//                isConnect = post.isConnected();
  //              if(isConnect) {
                    result = post.doPost(nameValuePairs);
                    jsonObj = new JSONObject(result);
                    Log.i("Result", result+"");
                    if(jsonObj.getInt("success") == 1)
                        res = true;
    //            }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return res;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
//                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//                intent.putExtra("jsonObj", jsonObj.toString());
//                startActivity(intent);
                txtShopCode.getText().clear();
                txtShopCode.requestFocus();
                Toast.makeText(getBaseContext(), "Your shop is geo tagged ", Toast.LENGTH_LONG).show();

            } else {
//                if(isConnect){
//                    mPasswordView.setError(getString(R.string.error_incorrect_password));
//                    mPasswordView.requestFocus();

//                }
//                else
                    Toast.makeText(getBaseContext(), R.string.geoTagError, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);
        googleMap.addMarker(new MarkerOptions().position(latLng));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            return false;
        }
    }

}

why is google map null? I'm using API in my meta deta

enter image description here

MIC
  • 47
  • 9

1 Answers1

0

Change you or on create to start with

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

Remove additional setContentView calls.

Use getMapAsyc to handle asynchronous map initialization:

SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
supportMapFragment.getMapAsync(new OnMapReadyCallback(){
    @Override
    public void onMapReady(final GoogleMap map) {
        map.setMyLocationEnabled(true);
    }
});
miensol
  • 39,733
  • 7
  • 116
  • 112
  • @MIC If the original error is gone please update the question providing new stacktrace – miensol Jan 04 '16 at 11:21
  • can you please check I have added a picture above – MIC Jan 04 '16 at 11:26
  • @MIC update to latest version of [maps](https://developers.google.com/android/reference/com/google/android/gms/maps/SupportMapFragment.html#getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)) – miensol Jan 04 '16 at 11:29
  • yeah that fixed the error! this.map = map; here map is giving me the error cannot resolve symbol map – MIC Jan 04 '16 at 11:33
  • @MIC `this.map=map` was just a sample. I've removed it form answer. If I've answered your question please accept it and upvote it. – miensol Jan 04 '16 at 12:24