-1

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. Still - all the time I get either NPE (java.lang.NullPointerException) or that getApplicationContext() is null. Any ideas?

Screenshot, if it helps: enter image description here

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:

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:

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

}

HX_unbanned
  • 583
  • 1
  • 15
  • 51
  • 1
    Could you edit your code and add a comment pointing out the line that throws the exception? With all those renamed methods I'm having a hard time figuring out the call hierarchy. Also: all those `static` keywords are setting off all sorts of warning bells – Jeroen Steenbeeke Sep 13 '19 at 10:10
  • 1
    Also add the crash logs. – Abbas Sep 13 '19 at 10:11
  • @JeroenSteenbeeke, comment added! Thanks! :) – HX_unbanned Sep 13 '19 at 10:15
  • can't understand anything in code(question), this is too dirty – Priyanka Sep 13 '19 at 10:23
  • Dude your code is too Dirty ...it has way too many leaks , unnecessary and very bad use of ```static``` – m3g4tr0n Sep 13 '19 at 10:26
  • and the root cause to your problem is using static variables. read this thread to know more https://stackoverflow.com/questions/11134686/static-variables-what-is-their-life-span – m3g4tr0n Sep 13 '19 at 10:32
  • I am fully aware it is not best in-class java code. No need to start some hate waves or down-voting just because you do not like what you see. Please. – HX_unbanned Sep 13 '19 at 10:39

1 Answers1

2

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.

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. 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. Like so:

Intent intent = new Intent(this, 3rdClass.class);    // this is your current Activity's reference.
currentActivity.startActivity(intent);
Abbas
  • 3,529
  • 5
  • 36
  • 64
  • Hmmmm. Can we move to the chat please, @Abbas? I am trying to implement the change, but it all ends with either ```Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference``` or ```Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference``` – HX_unbanned Sep 13 '19 at 11:10
  • @HX_unbanned https://chat.stackoverflow.com/rooms/199426/java-npe-when-trying-to-call-method-in-non-activity-class – Abbas Sep 13 '19 at 11:54
  • I have implemented Activity flow, but still got NPEs in the Fitness.* call... instance, activity and context is populated .. but still no good :( – HX_unbanned Sep 16 '19 at 14:12