繁体   English   中英

问题:尝试在 null object 引用上调用虚拟方法“android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()”

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

执行 mainTest(ru.myitschool.lab23.InstrumentedTestGeo) 时进程崩溃:java.lang.NullPointerException:尝试在 null 882828889 引用 at2 上调用虚拟方法“android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()” 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) 在 ru.myitschool.lab23.MainAc tivity.(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(TransactionExecuto r.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) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)

这是我的“作业”,我应该做位置提供者,但我至少有 1 个问题,我的老师正在放假(

主要活动:

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();
            }

        }
    });


      }



   }

在这一行

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

在实际膨胀 Activity 的 UI 之前,您尝试使用findViewById()将变量分配给布局中的小部件。

正确的方法是首先声明它们

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

并稍后在setContentView(R.layout.activity_main);之后的onCreate()中分配; 操作说明。

@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);
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM