Renboy
Renboy

Reputation: 451

My recyclerview inside a fragment is not updating no matter what I do

It's been a week now and I'm really desperate for a solution since I need to present an update to my client within this week. So, I have a recyclerview inside a fragment which is populated with data fetched from the web service using volley library. If a new data is added to the database, I want the recyclerview to reload/update to implemented the changes or the newly added ones. Now, I have tried numerous ways but failed to achieve what I need. I have tried the following:

-notifyDataSetChanged() on my adapter inside a handler, inside onclick

-adapter.notifyItemRangeChanged(0, adapter.getItemCount());

-recyclerView.invalidate() inside a handler as well - detach and attach current fragment

-Also tried the below code. Well, it works because it refreshes the whole activity and returns to the initial fragment which is the first page

Intent intent = getActivity().getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
    | Intent.FLAG_ACTIVITY_NO_ANIMATION);
    getActivity().overridePendingTransition(0, 0);
    getActivity().finish();

    getActivity().overridePendingTransition(0, 0);
    startActivity(intent);

fragment class

public class AddPlaylist extends Fragment {

RecyclerView recyclerView;
RecyclerAdapter adapter;
String[] id,title;
ArrayList<String> artist;
TextView text;

CreatePlaylist createPlaylist;

private CoordinatorLayout coordinatorLayout;
private FloatingActionButton fab;
 View view;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     view = inflater.inflate(R.layout.addplaylist, container, false);

    coordinatorLayout = (CoordinatorLayout) view.findViewById(R.id
            .coordinatorLayout);

    fab = (FloatingActionButton) view.findViewById(R.id.fab);

    text = (TextView) view.findViewById(R.id.text);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showInputDialog();
        }
    });

    id = getArguments().getStringArray("id");
    title = getArguments().getStringArray("title");

    artist = new ArrayList<String>(Arrays.asList(title));

    recyclerView= (RecyclerView) view.findViewById(R.id.my_recycler_view);
    adapter = new RecyclerAdapter("addplaylist", id, artist, getActivity());
    recyclerView.setAdapter(adapter);
    recyclerView.invalidate();
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    adapter.notifyItemRangeChanged(0, adapter.getItemCount());

    final Handler mHandler = new Handler();

    mHandler.post(new Runnable() {

        @Override
        public void run() {

            adapter.notifyDataSetChanged();
            adapter.notifyItemRangeChanged(0, adapter.getItemCount());
            recyclerView.invalidate();

            Fragment frg = null;
            frg = getFragmentManager().findFragmentByTag("playlist");
            Bundle bundle = new Bundle();
            AddPlaylist addPlaylist = new AddPlaylist();
            bundle.putStringArray("id", JsonArray.ids);
            bundle.putStringArray("title", JsonArray.titles);
            addPlaylist.setArguments(bundle);
            final FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.detach(addPlaylist);
            ft.attach(addPlaylist);
            ft.commit();

        }
    });

    return view;
}

protected void showInputDialog() {

    // get prompts.xml view
    LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
    View promptView = layoutInflater.inflate(R.layout.input_dialog, null);
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
    alertDialogBuilder.setView(promptView);

    final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
    // setup a dialog window
    alertDialogBuilder.setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    //text.setText("Hello, " + editText.getText());
                    createPlaylist.createPlaylist(editText.getText().toString());

                    /*Intent intent = getActivity().getIntent();
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
                            | Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    getActivity().overridePendingTransition(0, 0);
                    getActivity().finish();

                    getActivity().overridePendingTransition(0, 0);
                    startActivity(intent);*/
                    /*Bundle bundle = new Bundle();
                    Collections collections = new Collections();
                    AddPlaylist addPlaylist = new AddPlaylist();
                    bundle.putStringArray("id", JsonArray.ids);
                    bundle.putStringArray("title", JsonArray.titles);
                    bundle.putString("fragment", "addfragment");
                    addPlaylist.setArguments(bundle);
                    Fragment frg = null;
                    frg = getFragmentManager().findFragmentByTag("playlist");
                    final FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.detach(collections);
                    ft.attach(frg);
                    ft.commit();*/



                    /*getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                        }
                    });*/

                    /*FragmentManager fragmentTransaction = getFragmentManager();
                    android.app.FragmentTransaction transaction = fragmentTransaction.beginTransaction();
                    Bundle bundle = new Bundle();
                    AddPlaylist addPlaylist = new AddPlaylist();
                    bundle.putStringArray("id", JsonArray.ids);
                    bundle.putStringArray("title", JsonArray.titles);
                    addPlaylist.setArguments(bundle);
                    transaction.addToBackStack("xyz");
                    transaction.add(R.id.containerView, addPlaylist);
                    //transaction.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK);
                    transaction.commit();*/

                    adapter.notifyItemRangeChanged(0, adapter.getItemCount());
                }
            })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });

    // create an alert dialog
    AlertDialog alert = alertDialogBuilder.create();
    alert.show();
}

@UiThread
protected void dataSetChanged() {
    adapter.notifyDataSetChanged();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    id = getArguments().getStringArray("id");
    title = getArguments().getStringArray("title");

    artist = new ArrayList<String>(Arrays.asList(title));

    adapter = new RecyclerAdapter("addplaylist", id, artist, getActivity());
    adapter.notifyDataSetChanged();
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try{
        createPlaylist = (CreatePlaylist) activity;
    }catch(Exception e) {

    }
}

public interface CreatePlaylist{

     void createPlaylist(String name);

    }
}

Sorry for the messy code. This is what I have all tried.

Upvotes: 4

Views: 7144

Answers (1)

Marius Kaunietis
Marius Kaunietis

Reputation: 704

That happens, because your adapter "gets lost". First, you create adapter. That's good. Then you get new data. What you do is create yet another adapter, and change data in second adapter, which is not attached to your RecyclerView.

It's not most elegant solution, but it will work. Change these lines in onActivityResult:

 artist = new ArrayList<String>(Arrays.asList(title));

adapter = new RecyclerAdapter("addplaylist", id, artist, getActivity());

to

List<String> newArtist = new ArrayList<String>(Arrays.asList(title));
artist.clear();
artist.addAll(newArtist);
adapter.notifyDataSetChanged();

As your List artist is object, when you pass it to your Recycler adapter, and you update same instance, same List, so you don't need to create new adapter, because adapter still has access to same instance. Think of it like a Bucket of water. You can empty the bucket, or fill it, but the bucket remains the same.

Upvotes: 4

Related Questions