Search code examples
javaandroidgeolocation

Attempt to invoke virtual method. App to display Location


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

07-27 14:47:53.766: E/AndroidRuntime(28080): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference

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 have already allowed the permissions for fine and coarse location in the android manifest. Why is this happening?


Solution

  • This might not solve the problem but you are finding the views before the layout has been inflated. Move the

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

    to the inside of onCreate, after setContentView().