后退按钮更新列表

时间:2016-10-25 16:31:52

标签: android android-fragments android-recyclerview

目前我正在创建一个聊天应用程序。启动应用程序时,会调用api来获取信息。在该调用中,创建for循环以从从API接收的JSON数组中创建对象。从那里调用一个将设置适配器和布局管理器的处理程序。

下面是它的样子:(注意它显示了帖子中的最后一条消息)

enter image description here

当您点击其中一个列表时,会打开一个类似的聊天。

enter image description here

当我输入信息并单击发送时,然后按后退按钮返回我的信息列表。它显示与之前相同的屏幕(不更新最后发送的消息)。当应用程序重新启动时,它会从API中提取并显示最后一条消息。

基本上如何在按下后退按钮时重建片段或再次调用API?

片段:

public class conversationsFragment extends Fragment {

private RecyclerView usersListView;

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

conversationRecyclerViewAdapter adapter;
Bitmap image;


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

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

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_conversations, container, false);

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


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

        String credentials = "ezhu:Ccare@123";
        String auth = "Basic "
                + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

        Log.e("Test", auth);




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



        String url  = "https://staging.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");



                    arrMessageData = new ArrayList<>();

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

                        if (object.get("messageType").equals("CONVERSATION")) {



                            Log.e("ConversationTest", object.getString("fromUser"));

                            MessageData msg3 = new MessageData();
                            msg3.setName((String) object.get("fromUser"));
                            msg3.setMessage((String) object.get("message"));
                            getImage((String) object.get("photo"));
                            msg3.setImage(image);
                            msg3.setRead(true);
                            msg3.setSubject((String) object.get("subject"));
                            msg3.setType((String) object.get("conversationDate"));
                            msg3.setId((Integer) object.get("conversationId"));

                            arrMessageData.add(msg3);
                        } else {

                        }




                        handler.sendEmptyMessage(1);

                    }



                } catch (Exception e) {

                }

            }


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


private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 1:
                adapter = new conversationRecyclerViewAdapter(getActivity().getBaseContext(), arrMessageData);
                usersListView.setAdapter(adapter);
                LinearLayoutManager layoutManager
                        = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
                usersListView.setLayoutManager(layoutManager);
                break;
            default:
                Log.d("TAG", msg.what + " ? ");
                break;
        }
    }
};

1 个答案:

答案 0 :(得分:1)

这应该做的工作

@Override 
public void onBackPressed() {
          if(adapter!=null)       
          adapter.notifyDataSetChanged();
 }