1

I am using Retrofit 2.0 to retrieve data from my api and using a recyclerView to display it.

My main activity has a tab layout and one of those tabs has the recyclerView and the fragment class for that tab is being used to retrieve the data and update the layout.

In my main layout I have a fab which makes a post (all posts are being retrieved in fragment class) and this fab has it's function of making the post in main activity.

So how can I refresh the layout when the fab's function is over and the post is successfully saved in my database?

Basically User clicks fab > Makes his post > Alert dialog closes > recyclerView should be refreshed with new data added.

My Fragment Class :

public class PostsRecentTab extends Fragment {

private static final String TAG = MainActivity.class.getSimpleName();

private RecyclerView feedView;
private ProgressDialog pDialog = MainActivity.pDialog;
LinearLayoutManager layoutManager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View v =  inflater.inflate(R.layout.tab_recent_posts, container, false);

    pDialog.setCancelable(false);
    layoutManager = new LinearLayoutManager(this.getContext());
    feedView = (RecyclerView) v.findViewById(R.id.feedView);

    requestData();

    return v;
}

public void requestData() {
    SocialHubAPI apiService = ApiClient.getClient().create(SocialHubAPI.class);

    pDialog.setMessage("Refreshing...");
    showDialog();

    Call<StatusResponse> call = apiService.getStatuses();
    call.enqueue(new Callback<StatusResponse>() {
        @Override
        public void onResponse(Call<StatusResponse> call, Response<StatusResponse> response) {
            int statusCode = response.code();
            List<Status> statuses = response.body().getStatuses();
            Log.d(TAG, "Status Code: " + statusCode);
            hideDialog();

            updateView(statuses);

        }

        @Override
        public void onFailure(Call<StatusResponse> call, Throwable t) {
            Log.e(TAG, t.toString());
        }
    });
}

private void updateView(List<Status> statuses) {

    StatusesAdapter adapter = new StatusesAdapter(statuses, R.layout.feed_item, getContext());
    feedView.setLayoutManager(layoutManager);
    feedView.setAdapter(adapter);
}

private void showDialog() {
    if (!pDialog.isShowing())
        pDialog.show();
}

private void hideDialog() {
    if (pDialog.isShowing())
        pDialog.dismiss();
}
}

My Fab On Click :

    FloatingActionButton postStatus = (FloatingActionButton) findViewById(R.id.postStatus);

    postStatus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Post Status");

            // Set up the input
            final EditText input = new EditText(MainActivity.this);
            // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
            input.setInputType(InputType.TYPE_CLASS_TEXT);
            builder.setView(input);

            // Set up the buttons
            builder.setPositiveButton("Post", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    postText = input.getText().toString();
                    processPost(postText, sessionManager.getToken());
                    Snackbar.make(view, "Status posted!", Snackbar.LENGTH_LONG).show();
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            builder.show();
        }
    });

Fab onClick calls this method :

protected void processPost(String postText, String token) {
    SocialHubAPI apiService = ApiClient.getClient().create(SocialHubAPI.class);

    pDialog.setMessage("Posting...");
    showDialog();

    final PostRequest postRequest = new PostRequest();
    postRequest.setStatus(postText);

    Call<PostResponse> call = apiService.postStatus(postRequest, token);
    call.enqueue(new Callback<PostResponse>() {
        @Override
        public void onResponse(Call<PostResponse> call, Response<PostResponse> response) {
            hideDialog();
            Toast.makeText(getApplicationContext(), "Status Posted Successfully!", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFailure(Call<PostResponse> call, Throwable t) {
            Log.e(TAG, t.toString());
        }
    });
}
Faraz Ali
  • 83
  • 1
  • 8

1 Answers1

0

You should invalidate your list in updateView(List<Status> statuses) instead of setting the adapter again. Instantiate adapter only in onCreate().

This function should be like this:

adapter.addNewStatutes(statuses)

in Adapter class

public void addNewStatutes(List<Status> statuses) 
{
     this.statuses.addAll(statuses);
     notifyDataSetChanged();
}

Also in onResponse use EventBus or Rx, because your view can be destroyed and this method can crash your app.


Added notifyDataSetChanged as per docs.

Aba
  • 2,307
  • 2
  • 18
  • 32
Piotr Badura
  • 1,574
  • 1
  • 13
  • 17