无法访问VolleyRequest中的响应数据,尝试回调

时间:2016-10-12 09:08:59

标签: android-volley

我尝试过使用与我的片段类似的回调和其他人对回调的建议,但是我没有运气,我可能会做错回调。 JsonArrayRequest的onResponse方法中的Toast返回数组大小2.但是我在请求之外的toast上得到0。 consignment.class实现了parcelable

public class BackgroundTask{
String json_url;
Gson gson;
Type listType;
ProgressDialog pDialog;

ArrayList<Consignment>  arrayList = new ArrayList<>();
AppController appController;
ConsAdapter adapter;
Context context;
public BackgroundTask(Context context){
    this.context = context;
    listType = new TypeToken<List<Consignment>>(){}.getType();
    appController = AppController.getInstance();
    gson = new Gson();
}

public void  getAllCons(final GetAllConsListener callBack) {
    String tag_json_obj = "json_obj_req";
    //showProgressDialog();
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, json_url,null,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    callBack.onSuccess(response.toString());
                    //hideProgressDialog();
                    Toast.makeText(context, "Consignments:"+arrayList.size(), Toast.LENGTH_LONG).show();


                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //Toast.makeText(context, "Error...", Toast.LENGTH_SHORT).show();
            error.printStackTrace();
            //hideProgressDialog();
        }
    });


    appController.addToRequestQueue(jsonArrayRequest);
}

活动类:

public class GetConsActivity extends AppCompatActivity {
RecyclerView recyclerView;
ConsAdapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Consignment> arrayList;
TextView txtView;
BackgroundTask backgroundTask;
Type listType;
Gson gson;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_get_cons);
    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    gson = new Gson();
    listType = new TypeToken<ArrayList<Consignment>>(){}.getType();

    BackgroundTask backgroundTask = new BackgroundTask(GetConsActivity.this);
    backgroundTask.getAllCons(new GetAllConsListener() {
        @Override
        public void onSuccess(String response) {
            ArrayList<Consignment> list = parseResponse(response);
            updateUI(list);
            //Toast.makeText(GetConsActivity.this, "Consignments:"+arrayList.size(), Toast.LENGTH_LONG).show();

            Log.d("ONSUCCESS", "ARRAYSIZE: "+arrayList.size());

        }
    });


}

public ArrayList<Consignment> parseResponse(String response){
    ArrayList<Consignment> list = new ArrayList<>();
    try {
        JSONArray jsonArray = new JSONArray(response);

        Log.d("PARSE", "parseResponse: "+jsonArray.length());
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        for (int i = 0; i<jsonArray.length();i++){

            Consignment con = null;

            Log.d("PARSE", "parseID: "+jsonObject.getInt("conid"));
            con.setConid(jsonObject.getInt("conid"));

            Log.d("PARSE", "conID: "+con.getConid());
            con.setDescription(jsonObject.getString("description"));

            list.add(con);

        }
        Log.d("PARSED", "parsedResponse: "+list.size());

    } catch (JSONException e) {
        e.printStackTrace();
    }
    //arrayList =gson.fromJson(response,new TypeToken<ArrayList<Consignment>>(){}.getType());
    //updateUI(arrayList);
    return list;
}

public void updateUI(ArrayList<Consignment> consignments){
    this.arrayList = consignments;
    Log.d("UPDATE", "parseResponse: "+consignments.size());
    if (adapter == null) {
        adapter = new ConsAdapter(consignments,GetConsActivity.this);
        recyclerView.setAdapter(adapter);
    }else{
        adapter.setConsignments(consignments);
        adapter.notifyDataSetChanged();
    }
}

错误:

    D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000,  [1440x2560]-format:1
E/RecyclerView: No adapter attached; skipping layout
I/qtaguid: Untagging socket 51
D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 84 - 0, 0) vi=Rect(0, 84 - 0, 0) or=1
E/RecyclerView: No adapter attached; skipping layout
D/PARSE: parseResponse: 4
D/PARSE: parseID: 123456789
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.angel.createcon, PID: 26952
                  java.lang.NullPointerException: Attempt to invoke virtual method 'void com.angel.createcon.Consignment.setConid(int)' on a null object reference
                      at com.angel.createcon.GetConsActivity.parseResponse(GetConsActivity.java:80)
                      at com.angel.createcon.GetConsActivity$2.onSuccess(GetConsActivity.java:56)
                      at com.angel.createcon.BackgroundTask$2.onResponse(BackgroundTask.java:50)
                      at com.angel.createcon.BackgroundTask$2.onResponse(BackgroundTask.java:47)
                      at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
                      at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                      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:7331)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
I/Process: Sending signal. PID: 26952 SIG: 9
Application terminated.

1 个答案:

答案 0 :(得分:1)

所以我会对此进行一次尝试 - 让活动实现听众的方式有点奇怪,尽管我不认为这是个问题。我也不明白你为什么选择将列表类型保存到变量中 - 我之前没见过任何人这样做过。

然而,回答你关于吐司的问题及其原因0 - 如果你正在谈论getAllCons调用之后的吐司 - 因为该代码是在之前执行的回调代码。完成。

尝试这样的事情,看看它的作用。

public class BackgroundTask{

String json_url;
Gson gson;
Type listType;
Context context;

public BackgroundTask(Context context){
    this.context = context;
    listType = new TypeToken<List<Consignment>>(){}.getType();
    appController = AppController.getInstance();
    gson = new Gson();
}

public void  getAllCons(final GetAllConsListener callBack) {
    String tag_json_obj = "json_obj_req";
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, json_url,null,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    callBack.onSuccess(response.toString());
                    Toast.makeText(context, "Consignments:"+arrayList.size(), Toast.LENGTH_LONG).show();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });


    appController.addToRequestQueue(jsonArrayRequest);
}


public class GetConsActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    ConsAdapter adapter;
    RecyclerView.LayoutManager layoutManager;

    TextView txtView;
    BackgroundTask backgroundTask;
    Gson gson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_get_cons);
    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    gson = new Gson();

    BackgroundTask backgroundTask = new BackgroundTask(GetConsActivity.this);
    backgroundTask.getAllCons(new GetAllConsListener() {
        @Override
        public void onSuccess(String response) {
            List<Consignment> values = parseResponse(response);
            updateUI(values);
        }
    });

//code may execute here but callback is not yet complete.
}

public List<Consignment> parseResponse(String response){
    return gson.fromJson(response,listType);
}

private void updateUI(List<Consignment> consignments){
    if(adapter == null){
        adapter = new ConsAdapter(consignments)
        recyclerView.setAdapter(adapter);
    } else {
        adapter.consignments = consignments;
        adapter.notifyDataSetChanged();
    }
}