getApplicationContext()在空对象引用上

时间:2016-06-24 13:30:50

标签: android nullpointerexception android-volley android-context

我总是得到这个java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference 我运行我的应用程序时出错。我看到了其他答案,但我不明白如何使用这些答案,我理解上下文存在一些问题,因为没有调用Activity,所以我也尝试传递Activity上下文成功... 这是我的代码:

修改 我已经做了你的答案并且它已经工作了,所以我删除了这个因为我认为它已经解决了。由于你的答案,我更新了代码(上下文作为参与者的距离类>到MySingleton类......)

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


            }
        });
    }

}

公共班级距离{

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

}

这是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)

6 个答案:

答案 0 :(得分:11)

public class Distance extends Application

不要随意扩展类,只是因为您认为它会清除编译器错误。您在此处没有有效的Application子类,并且您没有正确使用它。

第1步:从extends Application移除Distance

步骤2:让getDistance()Context作为参数,并将其与MySingleton

一起使用

第3步:将MainActivity getApplicationContext()传递给getDistance() Context

答案 1 :(得分:0)

这实际上不是答案,而只是一个想法。

我遇到了同样的问题(这就是我遇到的问题的方式),而我的问题实际上非常简单。在设置Singleton中的私有上下文之前,我试图设置RequestQueue。

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

此外,在发现此问题之前,我确保上下文作为参数传递时不为null。这意味着问题必须出在MySingleton代码中。

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

因此,我只是在分享我的问题,希望它可以为您带来一些想法。祝你好运。

答案 2 :(得分:0)

对于使用flutter的Firebase Cloud Messaging(FCM)时遇到此错误的人,pubspec.yaml中可能有一个引起问题的软件包。

就我而言,keyboard_visibility是导致与FCM发生冲突的人。我不得不将其替换为flutter_keyboard_visibility

答案 3 :(得分:0)

私有上下文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();
    }
}

答案 4 :(得分:0)

对于 kotlin,你可以使用这个:

requireNotNull(this.activity).application

答案 5 :(得分:-2)

就像之前的回答(CommonsWare)一样,并把它放在:

Context context; // before onCreate in MainActivity

context = getApplicationContext();  // in onCreate in MainActivity