Can not retrieve location, app crashes - java

I have two classes.
MainActivity:
package ytu.ytu1;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button gpsBtn;
private TextView gpsTxt;
private LocationManager locMngr;
private LocationListener locLstnr;
GPSTracker gps;
double lot,lat;
String txt;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lat=gps.getLocation().getLongitude();
lot=gps.getLocation().getLatitude();
txt="longti "+lat + "latit " +lot;
gpsTxt = (TextView) findViewById(R.id.gpsTxt);
gpsTxt.setText("Coordinates: ");
gpsTxt.append(txt);
Toast.makeText(MainActivity.this,txt,
Toast.LENGTH_LONG).show();
}}
GPSTracker.java from here
http://pastie.org/9300205
only permissions were changed, because i am using this on android kitkat tablet.
package ytu.ytu1;
/**
* Created by mia on 11/28/2015.
*/
import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
private TextView txt;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 5000; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void StoprequestUpdates() {
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// 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 Activity#requestPermissions for more details.
if (isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isNetworkEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
return;
} else {
}
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
// if GPS Enabled get lat/long using GPS Services
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
if (isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isNetworkEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
locationManager.removeUpdates(GPSTracker.this);return;}
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
*
*
*
*
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog
.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
this.location = location;
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
I can not even debug, as soon as it starts, it crashes without showing any view.
logcat:
11-28 16:51:19.541 9413-9413/? D/dalvikvm: Late-enabling CheckJNI
11-28 16:51:19.591 9413-9413/? D/ActivityThread: handleBindApplication:ytu.ytu1
11-28 16:51:19.621 9413-9413/ytu.ytu1 W/ApplicationPackageManager: getCSCPackageItemText()
11-28 16:51:19.631 9413-9413/ytu.ytu1 D/DisplayManager: DisplayManager()
11-28 16:51:19.641 9413-9413/ytu.ytu1 W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
11-28 16:51:19.641 9413-9413/ytu.ytu1 I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onSearchRequested
11-28 16:51:19.641 9413-9413/ytu.ytu1 W/dalvikvm: VFY: unable to resolve interface method 17904: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
11-28 16:51:19.641 9413-9413/ytu.ytu1 D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-28 16:51:19.641 9413-9413/ytu.ytu1 I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onWindowStartingActionMode
11-28 16:51:19.641 9413-9413/ytu.ytu1 W/dalvikvm: VFY: unable to resolve interface method 17908: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
11-28 16:51:19.641 9413-9413/ytu.ytu1 D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-28 16:51:19.661 9413-9413/ytu.ytu1 D/AndroidRuntime: Shutting down VM
11-28 16:51:19.661 9413-9413/ytu.ytu1 W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x416adbc0)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: FATAL EXCEPTION: main
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: Process: ytu.ytu1, PID: 9413
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{ytu.ytu1/ytu.ytu1.MainActivity}: java.lang.NullPointerException
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2429)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.access$800(ActivityThread.java:166)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.os.Looper.loop(Looper.java:136)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5584)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: Caused by: java.lang.NullPointerException
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at ytu.ytu1.MainActivity.onCreate(MainActivity.java:44)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:5447)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.access$800(ActivityThread.java:166) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.os.Looper.loop(Looper.java:136) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5584) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method) 
I am using on android studio and i did not change the original code so much. I dont understand why it wont start.

Try something like this:
GPSTracker gps = new GPSTracker(this);
also check this tutorial: http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/

Related

TextWatcher shuts down my application after starting up

My app keeps crashing since I started using a TextWatcher...
As you can see below i made a TextWatcher to 3 EditText fields...
And i made a button which listens to the 3 EditText..
If they are empty the button become disabled.
When the fields are filled the button should become enabled..
package com.example.magazijnapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.MenuPopupWindow;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.sql.Array;
public class MainActivity extends AppCompatActivity {
Spinner spinnermagazijn;
Button knop;
private EditText EditTextregisternummerbalk;
private EditText EditTextticketnummerbalk;
private EditText EditTextartikelnummerbalk;
private Button knopconfirm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditTextregisternummerbalk = findViewById(R.id.registernummerbalk);
EditTextticketnummerbalk = findViewById(R.id.ticketnummerbalk);
EditTextartikelnummerbalk = findViewById(R.id.artikelnummerbalk);
knopconfirm = findViewById(R.id.knop);
EditTextregisternummerbalk.addTextChangedListener(invulTextWatcher);
EditTextticketnummerbalk.addTextChangedListener(invulTextWatcher);
EditTextartikelnummerbalk.addTextChangedListener(invulTextWatcher);
}
private TextWatcher invulTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String registernummerinput = EditTextregisternummerbalk.getText().toString().trim();
String ticketnummerinput = EditTextticketnummerbalk.getText().toString().trim();
String artikelnummerinput = EditTextartikelnummerbalk.getText().toString().trim();
knopconfirm.setEnabled(!registernummerinput.isEmpty() && !ticketnummerinput.isEmpty() &&! artikelnummerinput.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
};
{
spinnermagazijn = findViewById(R.id.spinnermagazijn);
knop = findViewById(R.id.knop);
populatespinnermagazijn();
// Dit is het stukje voor de Knop afboeken waarmee je een melding genereerd, String aanpassen voor ander resultaat.
knop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
});
}
// Dit gedeelte is voor de spinner.
private void populatespinnermagazijn() {
ArrayAdapter<String> magazijnenAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.steunpunten));
magazijnenAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnermagazijn.setAdapter(magazijnenAdapter);
}
}
And this is my logcat...
03-19 21:04:06.293 21151-21151/? E/libprocessgroup: failed to make and chown /acct/uid_10060: Read-only file system
03-19 21:04:06.293 21151-21151/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
03-19 21:04:06.293 21151-21151/? I/art: Not late-enabling -Xcheck:jni (already on)
03-19 21:04:06.313 21151-21161/? I/art: Debugger is no longer active
03-19 21:04:06.351 21151-21151/? D/AndroidRuntime: Shutting down VM
03-19 21:04:06.354 21151-21151/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.magazijnapp, PID: 21151
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.magazijnapp/com.example.magazijnapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:437)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.magazijnapp.MainActivity.<init>(MainActivity.java:73)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
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:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
03-19 21:04:07.996 21151-21151/? I/Process: Sending signal. PID: 21151 SIG: 9
There are two findViewById(R.id.knop);
remove this line:
knop = findViewById(R.id.knop);
and change :
knopconfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
});
You are saying your app is crashing since you started using TextWatcher. So why don't you stop using it?
you can achieve the same thing without using TextWatcher by doing this.
knop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String registernummerinput = EditTextregisternummerbalk.getText().toString().trim();
String ticketnummerinput = EditTextticketnummerbalk.getText().toString().trim();
String artikelnummerinput = EditTextartikelnummerbalk.getText().toString().trim();
if((!registernummerinput.isEmpty() && !ticketnummerinput.isEmpty() &&! artikelnummerinput.isEmpty())) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
}
});
you will not need any TextWathcer just modify the listner

at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)

I am new on android and working on my android app's login activity for which em using php mysql with volley library. But every time I run my app on emulator it shows the message Unfortunately, app has stopped. Here the login activity code is:
package com.example.u.locationtracker;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText pass1, email1;
private Button login;
private TextView link_reg;
private ProgressBar loading;
private String URL_LOGIN= "http://192.168.1.1/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email1= (EditText) findViewById(R.id.etemail1);
pass1= (EditText) findViewById(R.id.etpassl);
loading= (ProgressBar) findViewById(R.id.loading1);
link_reg= (TextView) findViewById(R.id.signup);
login= (Button) findViewById(R.id.btnlogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail= email1.getText().toString().trim();
String mpass= pass1.getText().toString().trim();
if(!mEmail.isEmpty() || !mpass.isEmpty()){
Login(mEmail, mpass);
}else{
email1.setError("Please Enter Email...!");
pass1.setError("Please Enter Password...!");
}
}
});
link_reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent it= new Intent(MainActivity.this, Register.class);
startActivity(it);
}
});
}
private void Login(final String email, final String pass) {
loading.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
StringRequest stringRequest= new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject= new JSONObject(response);
String success= jsonObject.getString("Success");
JSONArray jsonArray= jsonObject.getJSONArray("Login");
if(success.equals("1")){
for (int i= 0; i < jsonArray.length(); i++){
JSONObject object= jsonArray.getJSONObject(i);
Toast t= Toast.makeText(MainActivity.this,
"Login Successful", Toast.LENGTH_LONG);
t.show();
loading.setVisibility(View.GONE);
}
}
}catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t1= Toast.makeText(MainActivity.this,
"Error" + e.toString(),
Toast.LENGTH_LONG);
t1.show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t2= Toast.makeText(MainActivity.this,
"Error" + error.toString(),
Toast.LENGTH_LONG);
t2.show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params= new HashMap<>();
params.put("Email", email);
params.put("Password", pass);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
According to logcat the problem is:
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
here the php code:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email= $_POST['email1'];
$pass= $_POST['pass1'];
require_once 'connect.php';
$select= "SELECT * FROM user_table WHERE Email= '$email' ";
$r= mysqli_query($conn, $select);
$result= array();
$result['login']= array();
if (mysqli_num_rows($r)=== 1) {
$row= mysqli_fetch_assoc($r);
if ( password_verify($pass, $row['Pass']) ) {
$index['Name']= $row['Name'];
$index['Email']= $row['Email'];
array_push($result['login'], $index);
$result['success']= "1";
$result['message']= "Success";
echo json_encode($result);
mysql_close($conn);
}else{
$result['success']= "0";
$result['message']= "Error";
echo json_encode($result);
mysql_close($conn);
}
}
}
?>
Here is the Logcat:
02-03 21:03:21.626 2006-2012/? E/jdwp: Failed writing handshake bytes: Broken pipe (-1 of 14)
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper', referenced from method android.support.v4.view.ViewCompat.addOnUnhandledKeyEventListener
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.dispatchApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.onApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.View$OnUnhandledKeyEventListener', referenced from method android.support.v4.view.ViewCompat.removeOnUnhandledKeyEventListener
02-03 21:03:21.836 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$1', referenced from method android.support.v4.view.ViewCompat.setOnApplyWindowInsetsListener
02-03 21:03:22.756 2006-2006/com.example.u.locationtracker E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
02-03 21:03:27.786 2006-2006/com.example.u.locationtracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.u.locationtracker, PID: 2006
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.u.locationtracker/com.example.u.locationtracker.MainActivity}: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5019) 
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:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f07005d a=-1 r=0x7f07005d}
at android.content.res.Resources.loadDrawable(Resources.java:2068)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.ImageView.<init>(ImageView.java:129)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:72)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:68)
at android.support.v7.app.AppCompatViewInflater.createImageView(AppCompatViewInflater.java:182)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1266)
at android.support.v7.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1316)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:684)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:492) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:397) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:353) 
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39) 
at android.app.Activity.performCreate(Activity.java:5231) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5019) 
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:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
The problem seems to lie in this line:
setContentView(R.layout.activity_main);
Are you sure, the layout exists and doesn't have compile errors?
A full stacktrace would be more helpful

Google Maps API Key Error when launching Activity

I am trying to build an application that uses a Google maps activity using Android Studio.
I am facing issue: every time I try to launch the activity the app crashes. When I am using an emulator with SDK 24, the activity launches, it requires my permission and then it gives me an authentication error, even though I placed the correct API key.
On an emulator with SDK 26 the activity doesn't even launch and it crashes instantly.
Can you please help with this?
MapsActivity
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
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.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.util.ArrayList;
#SuppressWarnings("unchecked")
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onMapReady: map is ready");
mMap = googleMap;
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
private static final String TAG = "MapsActivity";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 15f;
//vars
private Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
getLocationPermission();
}
private void getDeviceLocation(){
Log.d(TAG, "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
if(mLocationPermissionsGranted){
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM);
}else{
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(MapsActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
}
}
private void moveCamera(LatLng latLng, float zoom){
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void initMap(){
Log.d(TAG, "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
}
private void getLocationPermission(){
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = true;
initMap();
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: called.");
mLocationPermissionsGranted = false;
switch(requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length > 0){
for(int i = 0; i < grantResults.length; i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
//initialize our map
initMap();
}
}
}
}
}
Error from the logcat for an emulator with SDK 24:
06-21 16:52:53.625 13392-13392/com.example.raluca.geoloc.feature E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:52:55.011 1314-1321/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
06-21 16:52:55.452 13392-13560/com.example.raluca.geoloc.feature E/Google Maps Android API: Authorization failure. Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
06-21 16:52:55.454 13392-13560/com.example.raluca.geoloc.feature E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
Ensure that the "Google Maps Android API v2" is enabled.
Ensure that the following Android Key exists:
API Key: XXX_Key
Android Application (<cert_fingerprint>;<package_name>): D3:DF:7B:C7:09:CA:00:9F:32:DD:93:98:D6:E2:09:A1:18:B1:F6:6B;com.example.raluca.geoloc.feature
06-21 16:53:01.866 13392-13392/com.example.raluca.geoloc.feature E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.raluca.geoloc.feature, PID: 13392
java.lang.RuntimeException: Failure delivering result ResultInfo{who=#android:requestPermissions:, request=1234, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4053)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at com.example.raluca.geoloc.feature.MapsActivity.initMap(MapsActivity.java:110)
at com.example.raluca.geoloc.feature.MapsActivity.onRequestPermissionsResult(MapsActivity.java:154)
at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:7067)
at android.app.Activity.dispatchActivityResult(Activity.java:6919)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4049)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096) 
at android.app.ActivityThread.-wrap20(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
06-21 16:53:02.076 1314-1322/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
06-21 16:53:05.957 8187-8220/? E/InputDispatcher: channel '65bcf76 com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.LoginActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
06-21 16:53:05.957 8187-8220/? E/InputDispatcher: channel '23dfb3a com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.MapsActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
06-21 16:53:26.978 8543-12462/? E/NetworkScheduler: Unrecognised action provided: android.intent.action.PACKAGE_REMOVED
06-21 16:53:27.653 8543-11730/? E/NetworkScheduler: Unrecognised action provided: android.intent.action.PACKAGE_REPLACED
06-21 16:53:28.495 8906-13710/? E/FontsPackageChangeOp: Error adding manifest dependency for newly downloaded font {Press Start 2P, wdth 100.0, wght 400, ital 0.0, bestEffort false}
06-21 16:53:28.507 8906-13053/? E/FontDisk: Error inserting metadata for Press Start 2P
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/user/0/com.google.android.gms/databases/metadata.db
at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1442)
at vdo.run(Unknown Source)
at ovb.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431):27)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at pbc.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431))
at java.lang.Thread.run(Thread.java:761)
06-21 16:53:29.228 13637-13764/? E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:53:29.611 13637-13764/? E/Finsky: [464] com.google.android.finsky.am.c.a(34): Unable to build selector: /storage/emulated/0/Download/marketenvs.csv (No such file or directory)
06-21 16:53:30.423 13637-13637/? E/Finsky: [1] com.google.android.finsky.wear.y.a(3): onConnectionFailed: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
06-21 16:53:35.484 13637-13828/? E/Finsky: [483] com.google.android.finsky.splitinstallservice.ad.a(3): Can't schedule deferred install. No modules found.
06-21 16:53:36.939 13637-13637/? E/Finsky: [1] com.google.android.finsky.wear.y.a(3): onConnectionFailed: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
06-21 16:53:37.759 13836-13836/? E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:53:38.320 8906-8965/? E/AsyncOpDispatcher: Unable to get current module info in ModuleManager created with non-module Context
06-21 16:53:39.373 8543-13891/? E/BluetoothAdapter: Bluetooth binder is null
06-21 16:53:39.503 8543-13891/? E/GCoreUlr: java.lang.IllegalStateException: Missing location or location status: 3016643, -1, 3781840, 7160153
at awot.a(:com.google.android.gms#12685026#12.6.85 (040700-197041431):387)
at awos.a(:com.google.android.gms#12685026#12.6.85 (040700-197041431):12)
at awos.handleMessage(:com.google.android.gms#12685026#12.6.85 (040700-197041431):7)
at oup.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431):6)
at ovb.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431):27)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at pbc.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431))
at java.lang.Thread.run(Thread.java:761)
06-21 16:53:40.868 12038-13901/? E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:58:10.742 8543-13895/? E/BluetoothAdapter: Bluetooth binder is null
06-21 16:58:10.743 8543-13895/? E/GCoreUlr: java.lang.IllegalStateException: Missing location or location status: 3016643, -1, 3781840, 7431479
at awot.a(:com.google.android.gms#12685026#12.6.85 (040700-197041431):387)
at awos.a(:com.google.android.gms#12685026#12.6.85 (040700-197041431):12)
at awos.handleMessage(:com.google.android.gms#12685026#12.6.85 (040700-197041431):7)
at oup.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431):6)
at ovb.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431):27)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at pbc.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431))
at java.lang.Thread.run(Thread.java:761)
06-21 17:07:17.957 8543-9125/? E/WakeLock: release without a matched acquire!
06-21 17:07:18.371 14053-14083/? E/SQLiteLog: (1) no such table: mmsconfig
06-21 17:07:18.376 14053-14083/? E/Babel_SMS: canonicalizeMccMnc: invalid mccmnc nullnull
Error from the logcat for an emulator with SDK 26:
06-21 17:13:05.646 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:14.440 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.440 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.441 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.441 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.443 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.899 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:15.787 5360-5360/com.example.raluca.geoloc.feature E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.raluca.geoloc.feature, PID: 5360
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at com.example.raluca.geoloc.feature.MapsActivity.initMap(MapsActivity.java:110)
at com.example.raluca.geoloc.feature.MapsActivity.getLocationPermission(MapsActivity.java:123)
at com.example.raluca.geoloc.feature.MapsActivity.onCreate(MapsActivity.java:67)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
06-21 17:13:16.975 1510-1510/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:16.976 1510-1510/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:16.978 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:16.990 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:16.990 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-21 17:13:16.998 2349-5365/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
06-21 17:13:17.682 2308-2853/com.google.android.gms.persistent E/ctxmgr: [ProducerStatusImpl]updateStateForNewContextData: inactive, contextName=7
06-21 17:13:17.794 2308-2308/com.google.android.gms.persistent E/BeaconBle: Missing BluetoothAdapter
06-21 17:13:17.895 2308-2308/com.google.android.gms.persistent E/BeaconBle: Scan couldn't start for Places
06-21 17:13:22.074 1510-1650/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:22.074 1510-1650/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:22.074 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:22.084 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:22.084 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-21 17:13:22.086 2349-5365/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
06-21 17:13:27.115 1510-1648/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:27.116 1510-1648/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:27.116 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:27.123 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:27.124 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-21 17:13:27.714 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:27.737 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:31.070 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:31.084 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:32.154 1510-1650/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:32.155 1510-1650/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:32.155 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:32.157 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:32.157 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
Msps Activity Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity"
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
/>
</RelativeLayout>
Gradle
android {
compileSdkVersion 26
defaultConfig {
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
debuggable true
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation project(':base')
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.github.orhanobut:logger:1.12'
compile 'com.google.android.gms:play-services-maps:11.6.0'
implementation "com.google.android.gms:play-services-location:11.6.0"
}
You have to initialize your map in onCreate() as done here and this will do your job.
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback
{
private GoogleMap mMap;
#Override
public void onMapReady(GoogleMap googleMap)
{
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d("Mapready", "onMapReady: map is ready");
mMap = googleMap;
if (mLocationPermissionsGranted)
{
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
private static final String TAG = "MapsActivity";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 15f;
//vars
private Boolean mLocationPermissionsGranted = false;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
initMap();
getLocationPermission();
}
private void getDeviceLocation(){
Log.d(TAG, "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
if(mLocationPermissionsGranted){
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM);
}else{
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(MapsActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
}
}
private void moveCamera(LatLng latLng, float zoom){
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void initMap(){
Log.d(TAG, "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
}
private void getLocationPermission(){
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = true;
initMap();
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: called.");
mLocationPermissionsGranted = false;
switch(requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length > 0){
for(int i = 0; i < grantResults.length; i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
//initialize our map
initMap();
}
}
}
}
}
Also, do the following changes in the manifest file:-
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY"/>
Create a New Project and check on the "Use androidx.* artifacts" and it will work fine.
Should use API 23 or newer.

always not get location information

The program was running before. But now I can not get location information anymore. the location value will be null all the time. I am very glad to get your help! Thank you very much!
mainActivity.jave
package com.example.a12086.map;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;
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.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private GPS gps;
private Location mlocation;
private EditText input;
double longitude;
double latitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
input = (EditText) findViewById(R.id.Edittext);
gps=new GPS(getApplicationContext());
mlocation=gps.getLocation();
if(mlocation==null)
{
Toast.makeText(getApplicationContext(),"something wrong",Toast.LENGTH_LONG).show();
}
else{
latitude=mlocation.getLatitude();
longitude=mlocation.getLongitude();
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng Myposition = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(Myposition).title("My Position"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(Myposition));
}
}
GPS.java
package com.example.a12086.map;
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.ContextCompat;
public class GPS extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled=false;
boolean isNETWORKEnable=false;
boolean canGetLocation=false;
Location location;
protected LocationManager locationManager;
public GPS (Context context){
this.context=context;
}
public Location getLocation(){
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
isNETWORKEnable = locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER);
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
if (locationManager == null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
if (location == null) {
if (isNETWORKEnable) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
if (locationManager == null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
}
}
}catch(Exception ex){
}
return location;
}
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
public IBinder onBind(Intent arg0){
return null;
}
}
logcat
04-27 17:51:42.930 6663-6854/com.example.a12086.map I/OpenGLRenderer: Initialized EGL, version 1.4
04-27 17:51:42.935 6663-6854/com.example.a12086.map W/linker: /vendor/lib64/libhwuibp.so: unused DT entry: type 0xf arg 0xe3a
04-27 17:51:42.949 6663-6830/com.example.a12086.map E/BufferQueueProducer: [SurfaceTexture-0-6663-0] connect: already connected (cur=1 req=1)
04-27 17:51:42.962 6663-6854/com.example.a12086.map E/OpenGLRenderer: allen debug liyu Key: 0
04-27 17:51:42.965 6663-6854/com.example.a12086.map E/OpenGLRenderer: allen debug liyu Key: 5242945
04-27 17:51:42.966 6663-6854/com.example.a12086.map E/OpenGLRenderer: allen debug liyu Key: 5242944
04-27 17:51:42.989 6663-6854/com.example.a12086.map E/OpenGLRenderer: allen debug liyu Key: 1
04-27 17:51:43.026 6663-6854/com.example.a12086.map E/OpenGLRenderer: allen debug liyu Key: 824633720832
04-27 17:51:44.873 6663-6836/com.example.a12086.map W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
04-27 17:51:44.885 6663-6836/com.example.a12086.map I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:2
04-27 17:51:44.885 6663-6836/com.example.a12086.map I/DynamiteModule: Selected remote version of com.google.android.gms.googlecertificates, version >= 2
04-27 17:52:16.559 6663-6663/com.example.a12086.map W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
04-27 17:53:03.234 6663-6663/com.example.a12086.map W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
04-27 17:53:03.240 6663-6830/com.example.a12086.map E/BufferQueueProducer: [SurfaceTexture-0-6663-1] connect: already connected (cur=1 req=1)
04-27 17:53:04.791 6663-6663/com.example.a12086.map W/IInputConnectionWrapper: reportFullscreenMode on inexistent InputConnection
04-27 17:53:04.791 6663-6663/com.example.a12086.map W/IInputConnectionWrapper: finishComposingText on inactive InputConnection

FATAL EXCEPTION: main Android

Hi i am new to android development. i am trying to get the users coordinates using the GPS, i get the error saying FATAL EXCEPTION: main Android.
here is my code
package lk.adspace.finetech;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class Main extends Activity implements LocationListener {
TextView viewlocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,1.0f, this);
boolean isGPS = locationManager.isProviderEnabled (LocationManager.GPS_PROVIDER);
if (isGPS){
}else{
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
String locationProvider = LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(locationProvider, 400, 1, this);
// Location loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
viewlocation = (TextView) findViewById(R.id.location);
viewlocation.setText("My Current location \n Latitude = "+ loc.getLatitude()+" \n Longitude = "+ loc.getLongitude());
}
...
}
This the error i get
08-20 12:08:37.436: E/AndroidRuntime(25888): FATAL EXCEPTION: main
08-20 12:08:37.436: E/AndroidRuntime(25888): java.lang.RuntimeException: Unable to start activity ComponentInfo{lk.adspace.finetech/lk.adspace.finetech.Main}: java.lang.NullPointerException
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.ActivityThread.access$600(ActivityThread.java:162)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.os.Handler.dispatchMessage(Handler.java:107)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.os.Looper.loop(Looper.java:194)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.ActivityThread.main(ActivityThread.java:5371)
08-20 12:08:37.436: E/AndroidRuntime(25888): at java.lang.reflect.Method.invokeNative(Native Method)
08-20 12:08:37.436: E/AndroidRuntime(25888): at java.lang.reflect.Method.invoke(Method.java:525)
08-20 12:08:37.436: E/AndroidRuntime(25888): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
08-20 12:08:37.436: E/AndroidRuntime(25888): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
08-20 12:08:37.436: E/AndroidRuntime(25888): at dalvik.system.NativeStart.main(Native Method)
08-20 12:08:37.436: E/AndroidRuntime(25888): Caused by: java.lang.NullPointerException
08-20 12:08:37.436: E/AndroidRuntime(25888): at lk.adspace.finetech.Main.onCreate(Main.java:68)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.Activity.performCreate(Activity.java:5122)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
08-20 12:08:37.436: E/AndroidRuntime(25888): ... 11 more
can anyone help me to fix this problem. tnx.
You are checking if GPS is enabled as a boolean isGPS. Move your code to within the block. Probably, the exception is thrown when the GPS provider is not enabled via settings. Your code should probably be as below:
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,1.0f, this);
boolean isGPS = locationManager.isProviderEnabled (LocationManager.GPS_PROVIDER);
if (isGPS){
// -------- IF GPS IS ENABLED, GET COORDINATES AND DISPLAY TO USER ------
String locationProvider = LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(locationProvider, 400, 1, this);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) // <---- This line can be included to avoid null pointer exception in case you are not able to get the coordinates.
{
viewlocation = (TextView) findViewById(R.id.location);
viewlocation.setText("My Current location \n Latitude = "+ loc.getLatitude()+" \n Longitude = "+ loc.getLongitude());
}
}else{
// --------IF GPS NOT ENABLED, THEN MOVE TO SETTINGS SCREEN TO HELP USER TO ENABLE GPS.
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
I think you should check loc is null or not;
if (loc != null) {
viewlocation = (TextView) findViewById(R.id.location);
viewlocation.setText("My Current location \n Latitude = "+ loc.getLatitude()+" \n Longitude = "+ loc.getLongitude());
}
There is null pointer exception at Line #68
8-20 12:08:37.436: E/AndroidRuntime(25888): at lk.adspace.finetech.Main.onCreate(Main.java:68)
I think loc below is returned as null. Please check.
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
While accessing loc.getLatitude(), its throwing exception. You can add null check or fetch location from different provider. Also, check if GPS provider is disabled currently.

Categories

Resources