Hello I have this application that could track users location I have two Activity which are HomeActivity and MapsActivity. On the first run of application After I pressed a button on HomeActivity it will go to the MapsActivity, but after a clicking back button or onBAckpressed the app crashes but on the second time opening the app and clicking back to HomeActivity the do not crash.
here is my code.
package www.teamruby.com.capstoneproject;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Criteria;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.storage.StorageManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.format.Formatter;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpResponse;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.GroundOverlayOptions;
import com.google.android.gms.maps.model.LatLngBounds;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.http.HttpEntity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
public class SendHelp extends FragmentActivity implements OnMapReadyCallback{
private Map<Integer, LatLng> marker = new HashMap();
String e_date="";
String e_type="";
String e_position="";
String e_desc="";
String e_user_id="";
String e_location="";
Button stop;
private GoogleMap mMap;
private Marker currentLocationMarker,locationsMarker,clickedMarker;
String provider;
LocationManager locationManager;
private final static int MY_PERMISSION_FINE_LOCATION = 101;
AlertDialog.Builder builder;
Context ctx;
String current_loc="0000";
String loc_url ="http://192.168.8.100/sample_login/location.php";
String locs_url ="http://192.168.8.100/sample_login/locs_list.php";
private ArrayList<LatLng> points; //added
Polyline line; //added
private List<LatLng>latLngList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_help);
// 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);
Bundle extras = getIntent().getExtras();
if (extras != null) {
e_date = extras.getString("e_date");
e_type = extras.getString("e_type");
e_position = extras.getString("e_position");
e_desc = extras.getString("e_desc");
e_user_id = extras.getString("e_user_id");
}
// Toast.makeText(SendHelp.this, e_date, Toast.LENGTH_LONG).show();
// Toast.makeText(SendHelp.this, e_type, Toast.LENGTH_LONG).show();
// Toast.makeText(SendHelp.this, e_position, Toast.LENGTH_LONG).show();
// Toast.makeText(SendHelp.this, e_desc, Toast.LENGTH_LONG).show();
// Toast.makeText(SendHelp.this, e_user_id, Toast.LENGTH_LONG).show();
points = new ArrayList<LatLng>(); //added
latLngList = new ArrayList<LatLng>();
WifiManager manager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
final int ip = info.getIpAddress();
final String ipAddress = BigInteger.valueOf(ip).toString();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
final LocationListener mlocListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if(currentLocationMarker != null){
currentLocationMarker.remove();
}
double latitude = location.getLatitude();
double longitude = location.getLongitude();
final LatLng latLng = new LatLng(latitude, longitude);
points.add(latLng); //added
// redrawLine();
MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng);
markerOptions.title(e_user_id).snippet(e_position);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
currentLocationMarker = mMap.addMarker(markerOptions);
// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17.2f));
current_loc = latLng.toString();
Toast.makeText(SendHelp.this, ipAddress, Toast.LENGTH_LONG).show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, loc_url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// try {
// JSONArray jsonArray= new JSONArray(response);
// JSONObject jsonObject = jsonArray.getJSONObject(0);
// String code = jsonObject.getString("code");
// String message = jsonObject.getString("message");
// builder.setTitle("Server Response");
// builder.setMessage(message);
// displayAlert(code);
//
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("current_loc", current_loc);
return params;
}
};
MySingleton.getInstance(SendHelp.this).addToRequestQueue(stringRequest);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = 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;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, mlocListener);
stop =(Button)findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
locationManager.removeUpdates(mlocListener);
Toast.makeText(SendHelp.this, "STOPPPPPPPPP", Toast.LENGTH_LONG).show();
Intent i = new Intent(SendHelp.this,INeedHelp.class);
finish();
startActivity(i);
}
});
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.raw.cspc);
LatLng southwest = new LatLng(13.40411165, 123.37296439);
LatLng northeast = new LatLng(13.40764800, 123.37730890);
LatLngBounds latLngBounds = new LatLngBounds(southwest, northeast);
GroundOverlayOptions groundOverlayOptions = new GroundOverlayOptions();
groundOverlayOptions.positionFromBounds(latLngBounds);
groundOverlayOptions.image(bitmapDescriptor);
googleMap.addGroundOverlay(groundOverlayOptions);
LatLng tlatLng = new LatLng(13.4062, 123.3750);
mMap.moveCamera(CameraUpdateFactory.newLatLng(tlatLng));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(tlatLng, 17.2f));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_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;
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSION_FINE_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return;
// mMap.setMyLocationEnabled(true);
// Intent i = new Intent(SendHelp.this,SendHelp.class);
// startActivity(i);
}
}
else{
Toast.makeText(getApplicationContext(),"This App Requires location to be granted", Toast.LENGTH_LONG).show();
return;
}
break;
}
}
public void displayAlert(final String code){
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(code.equals("no_location")){
current_loc="";
}
else if(code.equals("loc_success")){
current_loc="";
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
// private void redrawLine(){
//
//// mMap.clear(); //clears all Markers and Polylines
//
// PolylineOptions options = new PolylineOptions().width(5).color(Color.RED).geodesic(true);
// for (int i = 0; i < points.size(); i++) {
// LatLng point = points.get(i);
// options.add(point);
// }
//
// line = mMap.addPolyline(options); //add Polyline
// }
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setMessage("Do you want to Exit?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//if user pressed "yes", then he is allowed to exit from application
stop.performClick();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//if user select "No", just cancel this dialog and continue with app
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
Here is the logcat:
07-06 02:13:45.548 27451-27451/www.teamruby.com.capstoneproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: www.teamruby.com.capstoneproject, PID: 27451
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.Button.performClick()' on a null object reference
at www.teamruby.com.capstoneproject.SendHelp$4.onClick(SendHelp.java:430)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
As I see it, it is because you have not instantiated the button called stop. You only have declared a reference variable as stop, which is null by default. Therefore in the onCreate method, instantiate the button by using the following code.
stop=(Button) findViewById(R.id.XXyourButtonNameInTheXML);