【问题标题】:Volley AppController class object returning nullVolley AppController 类对象返回 null
【发布时间】:2015-12-27 11:08:29
【问题描述】:

我正在制作一个应用程序,该应用程序生成一个JsonObjectRequest,并使用 Android 版 Volley Networking Library 从一个 URL 检索 JSON 数据。

AppController.java

public class AppController extends AppCompatActivity {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mInstance = this;
    }

    public static synchronized AppController getInstance(){
        return mInstance;
    }

    public RequestQueue getRequestQueue(){
        if(mRequestQueue == null){
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }
}

MainActivity.class 中的方法

private void makeJSONObjectRequest() {

        showDialog();

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
                urlJsonObj, (String) null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());

                try {

                    //Parsing JSON Object response
                    String name = response.getString("name");
                    String email = response.getString("email");
                    JSONObject phone = response.getJSONObject("phone");
                    String home = phone.getString("home");
                    String mobile = phone.getString("mobile");

                    jsonResponse = "";
                    jsonResponse += "Name: " + name + "\n\n";
                    jsonResponse += "Email: " + email + "\n\n";
                    jsonResponse += "Home: " + home + "\n\n";
                    jsonResponse += "Mobile: " + mobile + "\n\n";

                    txtResponse.setTag(jsonResponse);

                }

                catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }

                hideDialog();
            }
        },

        new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                VolleyLog.d(TAG+"Error:"+ volleyError.getMessage());
                Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_SHORT).show();
                hideDialog();
            }
        });

        /*THE ERROR OCCURS HERE! */
        //adding request to the RequestQueue
        AppController.getInstance().addToRequestQueue(jsonObjReq);
    }

它给出了以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.h8pathak.volleyjson.AppController.addToRequestQueue(com.android.volley.Request)' on a null object reference

我怎样才能纠正这个代码?

【问题讨论】:

    标签: java android networking android-volley


    【解决方案1】:

    您的AppController class 需要扩展 Application 类而不是 AppCompatActivity 类。

    并记得更新您的清单。 IE。使用&lt;application&gt; 标记的名称属性在您的AndroidManifest.xml 中添加此类。

    <application
            android:name=".AppController"/>
    

    【讨论】:

      【解决方案2】:

      我认为你应该像这样创建“AppController”:

      public class AppController {
      
          private static AppController mInstance;
      
          private RequestQueue mRequestQueue;
      
          private static Context mCtx;
      
          private AppController(Context context){
              mCtx = context;
              mRequestQueue = getRequestQueue();
          }
      
          public static synchronized AppController getInstance(Context context) {
              if (mInstance == null) {
                  mInstance = new AppController(context);
              }
              return mInstance;
          }
      
          public RequestQueue getRequestQueue() {
              if (mRequestQueue == null) {
                  mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
              }
              return mRequestQueue;
          }
      
          public <T> void addToRequestQueue(@NonNull final Request<T> request) {
              getRequestQueue().add(request);
          }
      
          public <T> void addToRequestQueueWithTag(@NonNull final Request<T> request, String tag) {
              request.setTag(tag);
              getRequestQueue().add(request);
          }
      }
      

      和 MainActivity.class

      //adding request to the RequestQueue
      AppController.getInstance(this).addToRequestQueue(jsonObjReq);
      

      【讨论】:

        【解决方案3】:

        您不能像 Singleton 那样使用 ActivityActivity 是您的应用程序的屏幕,在您的应用程序使用期间它可能处于不同的状态。您也在泄漏它,因为您保留了对它的静态引用。出于您的目的,如果您需要上下文,请扩展 Application 而不是 AppCompatActivity,并将其注册到您的清单中。

        【讨论】:

          【解决方案4】:

          不要忘记初始化RequestQueue 对象。您需要在 onCreate 方法中初始化 RequestQueue,如示例中所示:
          (否则当您调用request.add(jsonObjectRequest) 时,应用程序将尝试引用null 对象)

          RequestQueue request;
          
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              //request qwe
              request= Volley.newRequestQueue(this);
          }
          

          【讨论】:

            猜你喜欢
            • 2020-02-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-06-12
            • 1970-01-01
            • 1970-01-01
            • 2015-10-05
            • 1970-01-01
            相关资源
            最近更新 更多