mardi 4 août 2015

Android App using GPS connection stops working

I had trouble to get the speed of my Android device. So i tried to use a sample, wich should work. With the code from http://ift.tt/1ONb631 i should get the speed. But the app always crashes before connecting to GPS. The code is:

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;



public class MainActivity extends Activity {


    Context context;
   protected void onCreate(Bundle savedInstanceState)
    { super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.Geschwindigkeit);

        LocationManager locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE);

        LocationListener locationListener = newLocationListener(){ public void onLocationChanged(Location location) {

            location.getLatitude();

            Toast.makeText(context, "Current speed:" + location.getSpeed(), Toast.LENGTH_SHORT).show(); }

            public void onStatusChanged(String provider, int status, Bundle extras) { }

            public void onProviderEnabled(String provider) { }

            public void onProviderDisabled(String provider) { }
        };

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    }
}

The log says the following:

08-04 14:36:51.023  11219-11219/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at android.widget.Toast.<init>(Toast.java:105)
        at android.widget.Toast.makeText(Toast.java:261)
        at test.gpsspeed.MainActivity$1.onLocationChanged(MainActivity.java:34)
        at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:257)
        at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:186)
        at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:202)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:5365)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
        at dalvik.system.NativeStart.main(Native Method)

What can i do? Or what Am i doying wrong?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire