0

there are two fragments tabs.ill explain it in brief,in the first fragment tab I'm setting my image (grid view)as favourite and displaying that favourite image in second fragment tab using the room database...the problem is the favourite image is getting added after restarting the app.can anyone what should I do.i have tried on resume but it is not working when I switch the tab. everytime if I want to see the recent added image as favourites I have to restart the app...can anyone help?

firstfragment:

public class FirstFragment extends Fragment {
private GridViewAdapter adapter;
private GridView mGridView;
//ProgressBar myProgressBar;
ProgressDialog progressDialog;
ViewPager viewPager;
private static final String HI = "http://mapi.trycatchtech.com/v1/stylish_hair_cut_for_pubg/stylish_hair_cut_for_pubg_list";
public List<RetroPhoto> product_lists=new ArrayList<>();

private JsonArrayRequest request;
private RequestQueue requestQueue;
public static FavoriteDatabase favoriteDatabase;


private void populateGridView(List<RetroPhoto> spacecraftList) {
    //mGridView = findViewById(R.id.mGridView);
    mGridView = getView().findViewById(R.id.mGridView);
    adapter = new GridViewAdapter(getContext(), spacecraftList);
    mGridView.setAdapter(adapter);
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_first, container, false);
    return rootView;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    favoriteDatabase = Room.databaseBuilder(getContext(), FavoriteDatabase.class, "myfavdb").allowMainThreadQueries().build();

    //  myProgressBar= getView().findViewById(R.id.myProgressBar);
    progressDialog = new ProgressDialog(getContext());
    progressDialog.setMessage("Loading....");
    progressDialog.show();

    /*Create handle for the RetrofitInstance interface*/
    GetDataService myAPIService = RetrofitClientInstance.getRetrofitInstance().create(GetDataService.class);

    Call<List<RetroPhoto>> call = myAPIService.getAllPhotos();
    call.enqueue(new Callback<List<RetroPhoto>>() {

        @Override
        public void onResponse(Call<List<RetroPhoto>> call, Response<List<RetroPhoto>> response) {
            //        myProgressBar.setVisibility(View.GONE);
            progressDialog.dismiss();
            populateGridView(response.body());
            getData();
        }




        @Override
        public void onFailure(Call<List<RetroPhoto>> call, Throwable throwable) {
            //        myProgressBar.setVisibility(View.GONE);
            progressDialog.dismiss();
            Log.d("url", "error");
        }
    });}private void getData()
  {

request = new JsonArrayRequest(HI, new com.android.volley.Response.Listener<JSONArray>() {
    @Override
    public void onResponse(JSONArray response) {
        JSONObject ob;

        for (int i = 0; i <response.length(); i++) {
            try {

                ob = response.getJSONObject(i);
                RetroPhoto pr = new RetroPhoto(ob.getInt("id"),
                        ob.getString("image"),
                        ob.getString("thumb_image"));

                product_lists.add(pr);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        setupData(product_lists);
    }
}, new com.android.volley.Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(getContext(), "errrrrrrrrrr", Toast.LENGTH_LONG).show();

    }
});
requestQueue = Volley.newRequestQueue(getContext());
  requestQueue.add(request);
}
private void setupData(List<RetroPhoto> product_lists) {
    adapter = new GridViewAdapter(getContext(), product_lists);
    mGridView.setAdapter(adapter);
}}

second fragment:

public class SecondFragment extends Fragment  {
private RecyclerView rv;
private FavoriteAdapter adapter;
public static FavoriteDatabase favoriteDatabase;
ProgressDialog progressDialog;



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

    View rootView = inflater.inflate(R.layout.activity_favourites,container, false);
    return rootView;
}



@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);


    rv=(RecyclerView)getView().findViewById(R.id.rec);
    rv.setHasFixedSize(true);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));



}
public void getFavData() {

    List<FavoriteList> favoriteLists=FirstFragment.favoriteDatabase.favoriteDao().getFavoriteData();
    adapter=new FavoriteAdapter(favoriteLists,getContext());
    rv.setAdapter(adapter);
}

@Override
public void onResume() {
    this.getFavData();
    super.onResume();
}}
Wini
  • 115
  • 14

2 Answers2

0

Where are you putting these two Fragments, in an Activity or a Fragment? Are you using ViewPager for tabs?

I am suspecting the second fragment is instantiated before you select a favorite image, that's why it never gets updated. If this is the case, calling getFavData() inside onResume() won't help.

One of the approach is to call SecondFragment.getFavData() in your main fragment/activity after favorite image is set.

Try adding this in second fragment:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if(isVisibleToUser) {
        getFavData();
    }
}
Yang Liu
  • 1,300
  • 10
  • 14
  • hi yang liu...yes im using view pager..and where should I put SecondFragment.getFavData() in firstfragment??wherever I put this getfavdata is showing error – Wini Nov 25 '19 at 08:49
  • do you have any idea about what we can do in second fragment??? – Wini Nov 25 '19 at 09:04
  • I will edit my post and add some code for you to try. – Yang Liu Nov 25 '19 at 09:08
  • thanks yang liu ....ill wait for your post...actually im referring this blog "https://uniqueandrocode.com/add-to-favourites-and-display-favourites-in-recyclerview/" see this if it helps you – Wini Nov 25 '19 at 09:10
  • it worked for few images...not all...what should I do????...and also I have a doubt in first fragment that some of favourite button already clicked even I have not pressed that yet...any help for this too??? – Wini Nov 25 '19 at 09:15
  • the images that I want them to display now its not display other images are displaying that I don't want to display – Wini Nov 25 '19 at 09:18
  • setUserVisibleHint got deprecated – Wini Nov 25 '19 at 09:19
  • hey did you found out? – Wini Nov 25 '19 at 09:47
0

As you mentioned you are using viewpager to put the two fragments, you need to call getFavData in onResume() and setUserVisibleHint(boolean isVisibleToUser). onResume() is called in the first time when the fragment is created, and the setUserVisibleHint() is called when the the page in viewpager is shown or hidden.

Weibo
  • 1,042
  • 8
  • 18
  • setUserVisibleHint got deprecated – Wini Nov 25 '19 at 09:19
  • hey im using this method "https://uniqueandrocode.com/add-to-favourites-and-display-favourites-in-recyclerview/" – Wini Nov 25 '19 at 09:22
  • hey did you found out? – Wini Nov 25 '19 at 09:47
  • @Wini yes, just checked out the latest doc, setUserVisileHint() is deprecated. you can use `setMaxLifecycle` instead of the `setUserVisibleHint()`, please refer [here](https://stackoverflow.com/questions/57885849/in-androidx-fragment-app-fragment-setuservisiblehint-is-deprecated-and-not-exec). By the way, I am a little confused that, the blog you are referring is nothing to do with fragment. – Weibo Nov 25 '19 at 10:43
  • I referring that blog just for add to favourite purpose actually my images is first fragment and I want to set those images as favourite and display it at second fragment that's why ..it seem those images are getting selected which I haven't marked as favourite..everything is so confusing ill try setmaxlifecycle let you know soon weibo – Wini Nov 25 '19 at 10:49
  • @Wini are you using FragmentPage? if so, just checkout [here](https://developer.android.com/reference/androidx/fragment/app/FragmentPagerAdapter) or do some search by key world `setMaxLifecycle` in github, good luck. – Weibo Nov 25 '19 at 10:55
  • setMaxLifecycle doesnt present in override method – Wini Nov 25 '19 at 10:58
  • `setMaxLifecycle` is not the method of Fragment.class, please checkout the android development doc [here](https://developer.android.com/reference/androidx/fragment/app/FragmentPagerAdapter). – Weibo Nov 25 '19 at 11:01
  • I don't think it's a good idea that I add the code for you. Please read the doc carefully and google something. I believe you will find out the solution. – Weibo Nov 25 '19 at 11:09