数据仅在单步执行时正确更新

时间:2017-02-22 21:21:13

标签: android json api android-asynctask android-recyclerview

目前,当我运行应用程序时,回收站视图在登录时显示数据。当应用程序重新编译并再次运行但使用其他人登录时,将显示先前的人员数据。

即使在进行API令牌调用之后也是如此。但是,当使用调试器并单步执行时,调试器会显示正确的信息,当我运行整个程序时,应用程序会显示正确的信息。

似乎我必须通过调试器为我的应用程序显示正确的数据。

这是片段。

public class allFragment extends Fragment {


private RecyclerView usersListView;


ArrayList<MessageData> arrMessageData; //= new ArrayList<MessageData>();


allRecyclerViewAdapter adapter;

SwipeRefreshLayout refreshLayout;

ProgressDialog pd;


public allFragment() {
    // Required empty public constructor
}

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

    new Load().execute(null, null, null);


}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_all, container, false);

    usersListView = (RecyclerView) rootView.findViewById(R.id.allListView);


    pd = ProgressDialog.show(getActivity(), "Loading messages",
            "Loading...", true);

    //new Load().execute(null, null, null);

    refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeRefreshLayout);

    refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            // Your code to refresh the list here.
            // Make sure you call swipeContainer.setRefreshing(false)
            // once the network request has completed successfully.
            new Load().execute(null, null, null);
        }
    });



    return rootView;

}

class Load extends AsyncTask<Void, Void, Void> {

    ProgressDialog pd;

    private Context context;

    @Override
    protected Void doInBackground(Void... params) {


        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new BasicAuthInterceptor()).addNetworkInterceptor(new StethoInterceptor()).build();



        SharedPreferences settings = PreferenceManager
                .getDefaultSharedPreferences(getActivity());
        String auth_token_string = settings.getString("token", ""/*default value*/);
        String auth_token_type = settings.getString("tokenType", "");
        String userId = settings.getString("userId", "");

        Log.i("prefs", auth_token_string);


        String url = "https://vitalengine.com/portal-api/api/user/inbox/list?userId=" +
                userId +
                "&folderId=-1&tagId=0&page=1&itemPerPage=1000&showMsgInFolder=false";


        Request request = new Request.Builder().url(url)
                .addHeader("Authorization", auth_token_type + " " + auth_token_string)
                .addHeader("user-tz", "-330")
                //.addHeader("Content-Type", "application/json")
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // Log.i(TAG, "call api error");
                Log.e("Volley", e.toString());
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) {

                try {
                    if (!response.isSuccessful())
                        throw new IOException("Unexpected code " + response);
                    final String body = response.body().string();


                    JSONObject Jobject = new JSONObject(body);


                    JSONObject sub = Jobject.getJSONObject("response");
                    JSONArray Jarray = sub.getJSONArray("inboxMsgList");

                    Log.e("Array", String.valueOf(Jarray.length()));

                    arrMessageData = new ArrayList<>();

                    int i = 0;
                    Log.i("Orginal Count ", "All: " + Jarray.length());
                    while (i < Jarray.length()) {

                        // for (i = 0; i < Jarray.length(); i++) {
                        JSONObject object = Jarray.getJSONObject(i);


                        MessageData msg3 = new MessageData();
                        msg3.setName((String) object.get("fromUser"));
                        msg3.setMessage((String) object.get("message"));
                        // added null check
                        //if (object.getString("toUser").equals(null))
                            msg3.setToUser(object.getString("toUser"));

                        msg3.setRead((Integer) object.get("isRead"));
                        msg3.setPhotoURL((String) object.get("photo"));


                        if (object.get("messageType").equals("CONVERSATION")) {
                            msg3.setType("conversation");

                            msg3.setSubject((String) object.get("subject"));
                            msg3.setId((Integer) object.get("conversationId"));

                        } else if (object.get("messageType").equals("MESSAGE")) {
                            msg3.setType("message");
                            msg3.setId((Integer) object.get("conversationId"));
                            msg3.setType((String) object.get("messageType"));

                            // added message type referral.
                        } else if (object.get("messageType").equals("REFERRALS")) {
                            msg3.setType("referral");
                            msg3.setPatient((String) object.get("patient"));
                            msg3.setId((Integer) object.get("referralId"));
                        }

                        arrMessageData.add(msg3);
                        handler.sendEmptyMessage(1);
                        i++;
                    }
                    Log.i("Expected Count ", "All: " + arrMessageData.size());

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }


        });
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(getActivity());
        pd.setMessage("loading");
        pd.show();
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if (pd != null) {
            pd.dismiss();
        }
    }
}

@Override
public void onResume() {
    super.onResume();
    new Load().execute(null, null, null);
}

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 1:
                adapter = new allRecyclerViewAdapter(getActivity().getBaseContext(), arrMessageData);
                usersListView.setAdapter(adapter);
                LinearLayoutManager layoutManager
                        = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
                usersListView.setLayoutManager(layoutManager);

                refreshLayout.setRefreshing(false);

                pd.dismiss();
                break;
            default:
                Log.d("TAG", msg.what + " ? ");
                break;
        }
    }
};

}

0 个答案:

没有答案