简体   繁体   English

尝试在非活动类中调用方法时的Java NPE

[英]Java NPE when trying to call method in non-activity class

I have googled here and there for two days already, but no solution seems not be working. 我已经在这里和那里搜索了两天,但是似乎没有解决方案。 Issue is within Fitness.getSessionsClient(this, Objects.requireNonNull(GoogleSignIn.getLastSignedInAccount(2ndclass.mContext))) and its passed activity ( this ) and context ( 2ndClass.mContext ) variables, which I can populate (variables or not null or empty via debugger inspection) by many found approaches already. 问题在Fitness.getSessionsClient(this, Objects.requireNonNull(GoogleSignIn.getLastSignedInAccount(2ndclass.mContext)))及其传递的活动( this )和上下文( 2ndClass.mContext )变量之内,我可以对其进行填充(变量,不能为null或为空或为空)通过调试器检查)已经找到了许多方法。 Still - all the time I get either NPE (java.lang.NullPointerException) or that getApplicationContext() is null. 仍然-我一直都得到NPE(java.lang.NullPointerException)或getApplicationContext()为null。 Any ideas? 有任何想法吗?

Screenshot, if it helps: 屏幕截图,如果有帮助的话: 在此处输入图片说明

Crash log line: 崩溃日志行:

E/<SOME TAG>: Error during PUT connection... Data: {"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"stations","main":{"temp":13.11,"pressure":1033,"humidity":77,"temp_min":10,"temp_max":16.11},"visibility":10000,"wind":{"speed":3.1,"deg":330},"clouds":{"all":69},"dt":1568357213,"sys":{"type":1,"id":1414,"message":0.0113,"country":"GB","sunrise":1568352700,"sunset":1568398909},"timezone":3600,"id":2643743,"name":"London","cod":200} Message: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

Code pieces: 代码段:

1st (MainActivity) class: 第一(MainActivity)类:

public class 1stClass extends AppCompatActivity {
    public static 1stClass instance;
    public static Context mContext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        instance = this;
        mContext = getApplicationContext();
    }
public final void 1stmethod(){
        2ndClass.2ndmethod();
}
/**
 * @return instance
 */
@Contract(pure = true)
public static 1stClass getInstance() { return instance; } // return.getInstance();

public static Context getContext() {
    //  return instance.getApplicationContext();
    return mContext;
}
}

2nd class: 二等班:

public class 2ndClass extends 1stClass{
  static 2ndClass instance;
  public final void 2ndmethod() {
  instance = this;
    3rdClass MFP = new 3rdClass();
    MFP.3rdmethod(..);
  }
/**
 * @return instance
 */
@Contract(pure = true)
public static 2ndClass getInstance() { return instance; } //return.getInstance();
}

Non-activity (3rd) class: 非活动(第3类):

public final class 3rdClass extends 2ndClass {
static 3rdClass instance;

public void 3rdmethod() {
    instance = this;
Fitness.getSessionsClient(this, Objects.requireNonNull(GoogleSignIn.getLastSignedInAccount(2ndclass.mContext))) // <---- ERROR HERE
                .insertSession(request)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.i(TAG, "Session insert was successful!");
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.wtf(TAG, "There was a problem inserting the session: " +
                                e.getLocalizedMessage());
                    }
                });
/**
 * @return instance
 */
@Contract(pure = true)
public static MFPalInterface getInstance() {
    return instance;
} // return.getInstance();

} }

I think I understand what you're doing, even though the code is one great mess. 我认为我了解您在做什么,即使代码是一团糟。

You are trying to create your own activity in your 2ndClass 's method '2ndmethod()' and then call the method on that newly created 3rdClass . 您尝试在2ndClass的方法'2ndmethod()'中创建自己的活动,然后在该新创建的3rdClass上调用该方法。

public final void 2ndmethod() {
    3rdClass MFP = new 3rdClass();
    MFP.3rdmethod(..);
}

Even though you've extended 3rdClass from your AppCompatActivity , you've not asked the system to create the Activity instance and attempted to create it yourself. 即使您从AppCompatActivity扩展了3rdClass ,也没有要求系统创建Activity实例并尝试自己创建它。 This means the newly created instance has no context and the system does not know about it. 这意味着新创建的实例没有上下文,系统也不知道。


What You Need to Do 你需要做什么

Start the activity by calling the startActivity() method of your current running Activity (in this case 2ndClass I think) and by passing an intent. 通过调用当前正在运行的ActivitystartActivity()方法(在这种情况下,我认为是2ndClass)并传递一个意图来启动活动。 Like so: 像这样:

Intent intent = new Intent(this, 3rdClass.class);    // this is your current Activity's reference.
currentActivity.startActivity(intent);

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

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