javaandroidandroid-fusedlocation

Problem: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference


Process crashed while executing mainTest(ru.myitschool.lab23.InstrumentedTestGeo): 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:190) at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174) at android.content.Context.obtainStyledAttributes(Context.java:809) at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:852) at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:819) at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640) at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:261) at ru.myitschool.lab23.MainActivity.(MainActivity.java:26) at java.lang.Class.newInstance(Native Method) at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95) at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45) at android.app.Instrumentation.newActivity(Instrumentation.java:1273) at androidx.test.runner.MonitoringInstrumentation.newActivity(MonitoringInstrumentation.java:866) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3901) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4201) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2438) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loopOnce(Looper.java:226) at android.os.Looper.loop(Looper.java:313) at android.app.ActivityThread.main(ActivityThread.java:8669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)

It is my "homework" and I should to do location provider, but I have minimum 1 problem and my teacher is at holidays(

MainActivity:

import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.location.Address;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.location.Geocoder;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

private FusedLocationProviderClient mFusedLocationClient;

TextView text_longitude = findViewById(R.id.text_longitude),
        text_accuracy = findViewById(R.id.text_accuracy), text_address = findViewById(R.id.text_address);

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


 }
 @SuppressLint("Range")
 public void getLoc(View v) {


    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=                PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
    }
          mFusedLocationClient.getLastLocation().addOnSuccessListener(this, location -> {
        if (location != null) {
            text_longitude.setText(String.valueOf(location.getLatitude()));
            text_accuracy.setText(String.valueOf(location.getAccuracy()));
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            try {
                text_address.setText((CharSequence) geocoder.getFromLocation(location.getLatitude(),  location.getAccuracy(), 1));
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    });


      }



   }

Solution

  • In this line

    TextView text_longitude = findViewById(R.id.text_longitude);
    

    You are trying to assign the variables to the widgets from the layout with findViewById() before actually inflating the Activity's UI.

    The proper way is firstly to declare them

    private TextView textLongitude;
    private TextView textAccuracy;
    private TextView textAddress;
    

    and assign later in onCreate() after setContentView(R.layout.activity_main); instruction.

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        textLongitude = findViewById(R.id.text_longitude);
        textAccuracy = findViewById(R.id.text_accuracy);
        textAddress = findViewById(R.id.text_address);
     }