Trying to call a virtual method. Location App

I am trying to make an Android application that displays the current (or last known location) of a device. This is the error that appears in logcat:

07-27 14: 47: 53.766: E / AndroidRuntime (28080): called: java.lang.NullPointerException: attempt to call the virtual method 'double android.location.Location.getLatitude ()' on a null object Link

This is my Java code:

package com.example.autosilence;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView lat = (TextView)findViewById(R.id.lat);
    TextView lon = (TextView)findViewById(R.id.lon);
    int b,c;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

        Location lastLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (lastLocation != null)
        {
            lat.setText(Double.toString(lastLocation.getLatitude()));
            lon.setText(Double.toString(lastLocation.getLongitude()));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

I already allowed permissions for small and rough placement in android manifest. Why is this happening?

+4
source share
2 answers

, , .

TextView lat = (TextView)findViewById(R.id.lat);
TextView lon = (TextView)findViewById(R.id.lon);

onCreate, setContentView().

+1

?

null , GPS. , nullPointerException. GPS , .

+1

All Articles