getApplicationContext()' on a null object reference using volley in non-activity

拟墨画扇 提交于 2019-12-24 16:34:16

问题


Take time trying to call a json from android, but the problem is the confusion of context, this is the error returned me

    02-09 19:48:05.494 16350-16350/com.example.cesar.mybankaccess E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cesar.mybankaccess, PID: 16350
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at restful.dao.PatronSingleton.getRequestQueue(PatronSingleton.java:37)
at restful.dao.PatronSingleton.<init>(PatronSingleton.java:25)
at restful.dao.PatronSingleton.getInstance(PatronSingleton.java:30)
at restful.dao.Cliente.dologin(Cliente.java:84)
at restful.RestfulOperacional.dologin(RestfulOperacional.java:22)
at com.example.cesar.mybankaccess.view.Login.dologin(Login.java:118)
at com.example.cesar.mybankaccess.view.Login.access$100(Login.java:30)
at com.example.cesar.mybankaccess.view.Login$2.onClick(Login.java:67)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)

I do not get fix, i'm sure is for context getContext or similar, but can't build one

public class RestfulOperacional {
    Cliente cliente;

    public RestfulOperacional() {
        cliente = new Cliente();
    }

    public Object dologin(String s, String s1) {
        return cliente.dologin(s, s1);
    }
}

And Class on try parse JSON

public class Cliente extends Application {
    private String URL_JSON;
    private static Context context;
    private static Cliente instance = null;

    public Cliente(Context context) {
        this.context = context;
    }

    public Cliente() {

    }


    @Override
    public void onCreate() {
        super.onCreate();
        context = getContext();
    }

    public static Context getContext() {
        return context;
    }
    public static Cliente getInstance(Context context) {
        if (instance == null) {
            instance = new Cliente(context);
        }
        return instance;
    }
    public Cliente dologin(String s, String s1) {
        URL_JSON = Constantes.URL_JSON + Constantes.URL_API_CLIENTE + Constantes.URL_API_CLIENTE_LOGIN;
        // Mapeo de los pares clave-valor
        HashMap<String, String> parametros = new HashMap();
        parametros.put("nif", s);
        parametros.put("claveSeguridad", s1);
        JsonObjectRequest jsArrayRequest = new JsonObjectRequest(
                Request.Method.POST,
                URL_JSON,
                new JSONObject(parametros),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.i("Json", response.toString());
                        // Manejo de la respuesta
                        //notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                });
        PatronSingleton.getInstance(getContext()).addToRequestQueue(jsArrayRequest);
        return null;
    }
}

回答1:


You are setting context to null and getContext returns that value.

Try this

public class Cliente extends Application {

    protected static Cliente sInstance;
    private RequestQueue mRequestQueue;

    @Override
    public void onCreate() {
        super.onCreate();

        mRequestQueue = Volley.newRequestQueue(this);
        sInstance = this;
    }

    public synchronized static Cliente getInstance() {
        return sInstance;
    }

    public RequestQueue getRequestQueue() {
        return mRequestQueue;
    }
}

Also, don't forget to add this Application to your Manifest like so in the application tag

<application
        android:name=".Cliente"
        android:allowBackup="true"
        ....

Alternatively, since Application extends Context in Android, you really don't need that variable... calling getApplicationContext() returns the Application object.


Usage -- move the Volley request to the Activity where you want to make the network connection in order to update the views and things in that class.

public class MainActivity extends AppCompatActivity {

    private static String URL_JSON = "http://my.server.com/login";

    private ArrayAdapter<String> adapter;
    private ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // use android:id="@android:id/list" in ListView XML
        lv = (ListView) findViewById(android.R.id.list);

        // Simple adapter to show strings
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
        lv.setAdapter(adapter);

        doLogin("username?", "password?");
    }

    private void doLogin(String s, String s1) {

        HashMap<String, String> parametros = new HashMap<String, String>();
        parametros.put("nif", s);
        parametros.put("claveSeguridad", s1);

        JsonObjectRequest req = new JsonObjectRequest(
                Request.Method.POST,
                URL_JSON,
                new JSONObject(parametros),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.i("Json", response.toString());
                        // Manejo de la respuesta
                        adapter.add(response.toString());
                        adapter.notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Volley", error.getMessage());
                    }
                });

        // Start the request
        Cliente.getInstance().getRequestQueue().add(req);
    }

}



回答2:


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

It looks like this code is essentially creating a loop, where you are always setting instance to null.



来源:https://stackoverflow.com/questions/35300928/getapplicationcontext-on-a-null-object-reference-using-volley-in-non-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!