0

So basically I have two tabs in a ViewPager and TabLayout to store two fragments in a tab view.

Thing is, I am using a card view in a recycler view and the card view has like a Like Button. Basically when the user clicks the button, it should appear on the next tab - but it doesn't. It is only when the user comes out of the entire page and goes back onto it and selects that tab does the selected card view is displayed. I checked my database and it is doing what it should be, but it is the recycler view that doesn't update.

This is my code for liking the contents in a card view:

 IN CUSTOM ADAPTER CLASS
 holder.likebutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Database database = new Database(fragment.getContext());
                database.likeContent(userID, contentID, name);
            }
        });

DATABASE CLASS
public void likeContent(int userID, int contentID, String name){
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(USER_ID, userID);
    contentValues.put(CONTENT_ID, contentID);
    contentValues.put(NAME, name);
    sqLiteDatabase.insert(DB_TABLE_NAME, null, contentValues);
}

BACKGROUND CLASS
public void showFavourites(final ArrayList<Integer> likes){
        theURL = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        requestQueue = Volley.newRequestQueue(fragment.getActivity());
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
                (theURL, new Response.Listener<JSONArray>(){
                    @Override
                    public void onResponse(JSONArray jsonArray) {
                        try {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                ...
                                adapter.notifyDataSetChanged();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener(){

                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                    }
                }
                );
        requestQueue.add(jsonArrayRequest);
    }

SECOND TAB CLASS
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.likes, container, false);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.rlikes);
        recyclerView.setHasFixedSize(true);
        list = new ArrayList<UserInfo>();
        adapter = new CAdapter(list, SecondTab.this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(adapter);
        conditionNames = new ArrayList<>();
        Background = new Background(SecondTab.this, list, adapter);
        inputs = new ArrayList<>();
        populate();
        return rootView;
    }

    public void populate(){
        background.showFavourites(inputs);
    }

So after I click the like button in the Custom Adapter Class it updates in the database but it doesn't update the recyclerview in the second tab.

EDIT: My pager adapter:

public class TabAdapter extends FragmentPagerAdapter{

    String tabNames[] = new String[] {"Current", "Likes"};
    Context context;

    public PodcastGUITabAdapter(FragmentManager fragmentManager, Context context){
        super(fragmentManager);
        this.context = context;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                return new CurrentTab();
            case 1:
                return new LikesTab();
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return tabNames.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return tabNames[position];
    }

}

What am I missing?

  • post pager adapter code. Most likely you need to return a new instance of fragment in getItem function. – vipul mittal Mar 07 '16 at 22:09
  • @vipulmittal, I have edited my question to include the `getItem()` function – Lukazs Pioetrszci Mar 07 '16 at 22:45
  • Put the code related to populating list from onCreate to onResume. Also if that not works check http://stackoverflow.com/questions/10024739/how-to-determine-when-fragment-becomes-visible-in-viewpager – vipul mittal Mar 07 '16 at 23:14

1 Answers1

0

I had the same problem and solved it using Broadcasts.

I registered BroadcastReceiver in both tabs.

Then after updating the database I send a broadcast and it gets received by both tabs and in onReceive method I reload the data into recycler view.

How to use Broadcasts (all this code goes into YourFragementClass):

First you need to declare a broadcast:

public static final String BROADCAST_NAME = "com.yourapp.broadcast_name";

Sending a broadcast:

getContext().sendBroadcast(new Intent(BROADCAST_NAME));

Registering a broadcast receiver:

private static IntentFilter broadcastIntentFilter = new IntentFilter(BROADCAST_NAME);
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override public void onReceive(Context context, Intent intent) {
            YourFragmentClass.this.refreshRecyclerAdapter();
        }
    };
private boolean broadcastReceiverRegistered = false;

Also you need to unregister and reregister receiver in onDestroy() and onResume():

    @Override
    public void onResume() {
        super.onResume();
        getActivity().registerReceiver(broadcastReceiver, broadcastIntentFilter);
        broadcastReceiverRegistered = true;
    }

    @Override
    public void onDestroy() {
        if(broadcastReceiverRegistered) {
            getActivity().unregisterReceiver(broadcastReceiver);
            broadcastReceiverRegistered = false;
        }
        super.onDestroy();
    }

You should implement YourFragmentClass.this.refreshRecyclerAdapter(); method something like this:

private void refreshRecyclerAdapter() {
        List<Items> items = getYourItems();
        ItemsRecyclerAdapter adapter = new ItemsRecyclerAdapter(getActivity(), items);
        mRecyclerView.setAdapter(adapter);
    }
jdabrowski
  • 1,805
  • 14
  • 21