简体   繁体   中英

I can't solve null object reference

I am in complex trouble that i can't solve. 在此处输入图片说明 I have two classes named ActivityA and ActivityB.

ActivityB uses method in ActivityA named "A".

So "A" has to be static.

In "A" uses function named "ShowSuccessDialog"

and it also has to be static.

When I start the App, there is an error that

"non-static variable this cannot be referenced from a static context"

I have tried to replace ActivityA.this with getContext(), getActivity()

But it doesn't work.

I googled and found making instance could be help,

But i don't have any clue about it.

Please solve this problem

在此处输入图片说明 ************************** added & edited ************************** I will add more information.

My app is consist of 1 main activity and 3 fragment

ActivityA is a mainActivity that has connecting bluetooth, sending and receiving data.

ActivityB is a fragment that needs data receiving through bluetooth

ActivityC is a fragment that receiving and sending data and has another functions.

I have tried to define bluetooth functions on the activity and use bluetooth fuctions by refering activity.

So ActivityA is MainActivity, ActivityB is fragmentB

A is connecting function, and B is receiving Data.

I am not good at programming, So this is the best what i can do.

So I want to solve this problem by editing little. ;(

IMO it is not good practice to do something like this. But for learning how to do it you can do something like this:

1- Change the method ShowSuccessDialog signature and the body like this:

private static void ShowSuccessDialog(Context context) {
     new AlertDialog.Builder(context);
}

2- In method A :

private void A() {
    ShowSuccessDialog(ActivityA.this);
}

3- In ActivityB call the method like this:

ShowSuccessDialog(ActivityB.this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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