android - 空对象引用上的 getApplicationContext()

标签 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 上下文但没有成功...... 这是我的代码:

编辑 我已经回答了你的问题,但没有用,所以我删除了这个,因为我认为这不是解决方案。由于您的回答,我更新了代码(将上下文作为 Distance 类的参数 > 到 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("");
                

            }
        });
    }

}


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

}

这是日志

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)

最佳答案

public class Distance extends Application

不要随意扩展类,只是因为您认为它会清除编译器错误。您没有有效的 Application在这里创建子类,而您没有正确使用它。

第 1 步:删除 extends Application来自 Distance .

第 2 步:拥有 getDistance()拿个Context作为参数,并让它与 MySingleton 一起使用

第 3 步:拥有 MainActivity通过 getApplicationContext()进入getDistance()作为 Context

关于android - 空对象引用上的 getApplicationContext(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38014663/

相关文章:

android - 在 Android M 上通过 wifi 请求

java - Android Volley 访问 http 响应头域

Android 改造添加 header 和 HttpLoggingInterceptor

android - 保存 Canvas 然后恢复,这是为什么呢?

java - 使用局部类变量处理句柄/线程

安卓停止线程

android - 使用 JSoup 解析 NullPointerException

Android - 使用数据绑定(bind)的条件文本值

android - 从 Activity 传递时获取对象为 null

android - 如何解决错误 : null in volley library?