在非活动中使用Volley在空对象引用上获取getApplicationContext()' [英] getApplicationContext()' on a null object reference using volley in non-activity

查看:157
本文介绍了在非活动中使用Volley在空对象引用上获取getApplicationContext()'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

花时间尝试从android调用json,但是问题是上下文混乱,这是返回的错误

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)

我没有得到解决,我确定是针对上下文getContext或类似的,但无法构建一个

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

然后尝试解析JSON的类

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

推荐答案

您要将context设置为null,getContext返回该值.

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

尝试一下

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

此外,别忘了像在应用程序标记中一样将此Application添加到清单中

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

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

或者,由于在Android中是Application extends Context,因此您实际上不需要该变量...调用getApplicationContext()会返回Application对象.

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

用法-将Volley请求移至要建立网络连接的Activity,以更新该类中的视图和事物.

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

}

这篇关于在非活动中使用Volley在空对象引用上获取getApplicationContext()'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆