19

I allways get this java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference error while I run my app. I saw other answers but I didn't understand how to use those answer, I understood that there is some problem withe the context because there isn't call by Activity, so I also tried to pass the Activity context with no success... this is my code:

EDIT I already did your answers and it'snt worked, so I deleted this becuase I thought it'snt the solution. Due to yours answers I updated the code(with context as parmerter to the Distance class >to MySingleton class...)

public class MainActivity extends AppCompatActivity {

    private Button b;
    private TextView t;
    private LocationManager locationManager;
    private LocationListener listener;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        t = (TextView) findViewById(R.id.textView);
        b = (Button) findViewById(R.id.button);

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);


        listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.d("Co", "onLocationChanged");
                Distance distance=new Distance();
                t.setText("\n " + location.getLongitude() + " " + location.getLatitude()+"\n "+distance.getDistance(location));

                Location l2=new Location("");
                
                //float distance=location.distanceTo(l2);
                Log.d("Co", String.valueOf(distance));
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle)   {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(i);
            }
        };

        configure_button();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 10: {
                configure_button();
                Log.d("Co", "premmsioenChecks");

            }
            break;
            default:
                break;
        }
    }

    public void configure_button(){
        // first check for permissions
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
                        ,10);
                Log.d("Co", "premmsioen");

            }
            return;
        }
        // this code won't execute IF permissions are not allowed, because in the line above there is return statement.
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //noinspection MissingPermission


                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
                Log.d("Co", "onClick");
                Location l2=new Location("");
                

            }
        });
    }

}


public class Distance   {

static  String url = "";
static String result="";

public  String getDistance(Location location,Context context) {

    Log.d("app","getDistance");






            String origins=location.getLatitude()+","+location.getLongitude();
            
            url="https://maps.googleapis.com/maps/api/distancematrix/json?&origins="+origins+"&destinations="+destinations;
            Log.d("URL",url);
            JsonObjectRequest jsObjRequest = new JsonObjectRequest

                    (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            Log.d("app","onRespone");

                            String distance=getText(response);
                            if (distance.contains("Error")) {
                                result=distance;
                                return;
                            }
                            else {
                                if (distance.contains("km")) {
                                    int meters = Integer.parseInt(distance.replaceAll("[\\D]", "")) * 1000;
                                   result= "The distance is " + meters + " meters";
                                    return;
                                }
                                Log.d("7", String.valueOf(Integer.parseInt(distance.replaceAll("[\\D]", ""))));

                                result= "The distance is " + distance;
                            }



                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.d("app","Error Respone");

                        }
                    }
                    );
            MySingleton.getInstance(context).addToRequestque(jsObjRequest);
    return result;
        }




public  String getText(JSONObject response)
{
    String  text="";
    try {

        JSONArray rows = response.getJSONArray("rows");
        Log.d("1", rows.toString());
        if(rows.toString().contains("[]"))  return text="Error";
        JSONObject elements = rows.getJSONObject(0);
        Log.d("2", elements.toString());
        rows = elements.getJSONArray("elements");
        Log.d("3", rows.toString());
        elements  = rows.getJSONObject(0);
        Log.d("4", elements.toString());
        Log.d("Error1","Error is @"+elements.getString("status"));
        if( elements.getString("status").contains("OK"))
        {
            JSONObject d = elements.getJSONObject("distance");
            Log.d("5", d.toString());
            text = d.getString("text");
        }
        else {
            Log.d("Error2", elements.getString("status"));
            text = "Error-" + elements.getString("status");
        }

    }
    catch (JSONException e)
    {
        text="Some error ocuerd";
    }
    return text;
}


}


public class MySingleton {
    private static MySingleton mInstance;
    private RequestQueue requestQueue;
    public static Context mCtx;
    private MySingleton(Context context)
    {
        mCtx=context;
        requestQueue= getRequestQueue();
    }

    public RequestQueue getRequestQueue() {
        if(requestQueue==null) {
            requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return requestQueue;
    }
    public static synchronized MySingleton getInstance(Context context)
    {
        if(mInstance==null)
        {
            mInstance=new MySingleton(context);
        }
        return mInstance;
    }
    public <T> void addToRequestque(Request<T> request)
    {
        requestQueue.add(request);
    }

}

and this is the logcat

06-24 16:19:26.771 25300-25300/com.example.elicahi.gateor D/Co: onClick
06-24 16:19:27.556 25300-25300/com.example.elicahi.gateor D/Co: onLocationChanged

06-24 16:19:27.579 25300-25300/com.example.elicahi.gateor D/AndroidRuntime: Shutting down VM
06-24 16:19:27.579 25300-25300/com.example.elicahi.gateor E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.example.elicahi.gateor, PID: 25300
                                                                            java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                                                at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:107)
                                                                                at com.example.elicahi.gateor.MySingleton.getRequestQueue(MySingleton.java:24)
                                                                                at com.example.elicahi.gateor.MySingleton.<init>(MySingleton.java:19)
                                                                                at com.example.elicahi.gateor.MySingleton.getInstance(MySingleton.java:32)
                                                                                at com.example.elicahi.gateor.Distance.getDistance(Distance.java:79)
                                                                                at com.example.elicahi.gateor.MainActivity$1.onLocationChanged(MainActivity.java:54)
                                                                                at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:285)
                                                                                at android.location.LocationManager$ListenerTransport.-wrap0(LocationManager.java)
                                                                                at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:230)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Fluffeh
  • 33,228
  • 16
  • 67
  • 80

7 Answers7

18
public class Distance extends Application

Do not randomly extend classes, just because you think that it will clear up a compiler error. You do not have a valid Application subclass here, and you are not using it properly.

Step #1: Remove extends Application from Distance.

Step #2: Have getDistance() take a Context as a parameter, and have it use that with MySingleton

Step #3: Have MainActivity pass getApplicationContext() into getDistance() as the Context

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I already did that but I removed it from my code here. Anyway, I tried this agin and I got the same error –  Jun 24 '16 at 13:45
  • Hey, I updated my code, like you answered me...what the problem is? I still get the same error –  Jun 24 '16 at 13:56
  • @user5209063: You are going to need to determine how you are passing `null` into the `MySingleton` constructor. – CommonsWare Jun 24 '16 at 13:59
  • Sorry but I didnt understood what you wtore. I pass my MainActivty context , how it's null? –  Jun 24 '16 at 14:02
  • @user5209063: I have no idea. If you follow the instructions in my answer, it cannot be `null`. However, you claim to get the same error, which means it must be `null`. I cannot help you further. – CommonsWare Jun 24 '16 at 14:03
  • Thanks, I have no idea what happend but I just add this Log Log.d("MySingleton",context.toString()); at the start of Distance class, and comiled it and it worked...weird, anyway Thanks a lot –  Jun 24 '16 at 14:08
  • You should put code for clerification... – J. M. Feb 21 '22 at 02:55
1

for kotlin, you can use this:

requireNotNull(this.activity).application
erhan
  • 31
  • 4
0

Do it like the previous answer says (CommonsWare) and put:

Context context; // before onCreate in MainActivity

context = getApplicationContext();  // in onCreate in MainActivity
kabirbaidhya
  • 3,264
  • 3
  • 34
  • 59
munja777
  • 109
  • 1
  • 2
  • It is far better to pass in as a parameter rather than declaring it as a field that may or may not be null. This would not really add anything. – Ben Neill Oct 27 '17 at 01:53
0

This is not really an answer, but just an idea.

I was having the same problem (that's how I got to this question) and my problem was actually very simple. I was trying to set RequestQueue before setting my private Context in my Singleton.

  private MySingleton(Context context) {
    ctx = context; // queue = getRequestQueue();    <--- queue first but it needs context.
    queue = getRequestQueue();    // ctx = context;   <--- ctx being set here. queue can't find context.
 }

public synchronized static MySingleton getInstance(Context context) {
    if (instance == null) {
        instance = new MySingleton(context);
    }
    return instance;
}

private RequestQueue getRequestQueue() {
    if (queue == null) {
        queue = Volley.newRequestQueue( ctx.getApplicationContext() ); // <--- Here is the crash;
    }
    return queue;
}

Also, before finding this problem I made sure that the context was not null when being passed as a parameter. That means the problem had to be somewhere in MySingleton code.

// This code is run before MySingleton.getInstance() wherever it is in your app;
Context testParameter = getBaseContext();
Log.d("DEBUG_CONTEXT", testParameter.toString() );

So I'm just sharing my problem and hoping it could bring you some ideas. Good luck.

0

For someone who is getting this error when using flutter Firebase Cloud Messaging (FCM), there might be one package in pubspec.yaml that is causing the problem.

For my case keyboard_visibility was the one causing conflict with FCM. I had to replace it with flutter_keyboard_visibility.

BYISHIMO Audace
  • 585
  • 1
  • 8
  • 18
0

private Context mContext;

private Activity mActivity;

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    if (getActivity() == null) {
        return;
    }
    else
        {
        mActivity = getActivity();
    }
}
Mazhar Iqbal
  • 813
  • 7
  • 7
0

I was having this issue and realized I was running the defaultPreview on the emulator and not the actual app.

durkester
  • 21
  • 4