getApplicationContext()'在非活动中使用齐射的空对象引用

时间:2016-02-09 19:50:01

标签: android json android-volley

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

    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或类似的,但不能构建一个

public class RestfulOperacional {
    Cliente cliente;

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

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

Class on try解析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;
    }
}

2 个答案:

答案 0 :(得分:8)

您将上下文设置为null,getContext返回该值。

试试这个

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添加到您的清单中

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

或者,从Android中的Application extends Context开始,你真的不需要那个变量......调用getApplicationContext()会返回Application对象。

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

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

}

答案 1 :(得分:-1)

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

看起来这段代码实际上是在创建一个循环,你总是将实例设置为null。