0

I have made a View Pager along with some fragments and in those fragments i have used recycler view to show the Dynamic data fetched from the internet .I have used a Pull to Refresh also for my fragment .Sometimes due to slow internet connection when my fragment page gets loaded then it shows an awkard behaviour with my recycler view data..The data gets loaded in recycler view but it is scrollable behind my phone screen and a Recycler View "still" image is shown at the front without the scroll effect .Hence i am not able to function my Recycler view properly .When i try to scroll the page which is formed at the back is scrolled and the front page is "Still". What might be the issue???

Fragment File

  package com.global.market;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class Asia extends Fragment implements SwipeRefreshLayout.OnRefreshListener{

  //  ProgressDialog pDialog;
    private RecyclerView mRecyclerView;
    //private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private CountryDataAdapter adapter;
    private ArrayList<CountriesData> data;
    private SwipeRefreshLayout swipe;

    public Asia(){

    }
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

       // setContentView(R.layout.countrydata);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.countrydata, container, false);
     //   pDialog = new ProgressDialog(this.getContext(), ProgressDialog.THEME_HOLO_LIGHT);
        //mRecyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view1);
        mRecyclerView = (RecyclerView)v.findViewById(R.id.my_recycler_view1);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
        // loadJSON();



        swipe=(SwipeRefreshLayout)v.findViewById(R.id.swipe_refresh_layout);
        swipe.setOnRefreshListener(this);
        swipe.setColorSchemeColors(R.color.b, R.color.p, R.color.g, R.color.o);
        swipe.post(new Runnable() {
                       @Override
                       public void run() {
                           swipe.setRefreshing(true);
                           loadRetro();
                       }
                   }
        );


        return v;
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    @Override
    public void onCreateOptionsMenu(
            Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main, menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_refresh) {
            boolean x=isNetworkAvailable();
            if(x)
//            pDialog.setMessage("Please wait...");
//            pDialog.setCancelable(false);
//            pDialog.show();
      //      swipe.setRefreshing(true);
            {
                loadRetro();
                return true;
            }
             else Toast.makeText(getActivity(), "No Internet Connection!",
                    Toast.LENGTH_SHORT).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    @Override
    public void onRefresh(){
    //    swipe.setRefreshing(true);
        loadRetro();
        //pDialog.dismiss();
    }

    public void loadRetro(){

        swipe.setRefreshing(true);
//        pDialog.setMessage("Please wait...");
//        pDialog.setCancelable(false);
//        pDialog.show();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.appuonline.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        jsonrequest request = retrofit.create(jsonrequest.class);
        Call<JsonResponse> call = request.getJSON();
        call.enqueue(new Callback<JsonResponse>() {
            @Override
            public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {

                try{
                JsonResponse jsonResponse = response.body();
                data = new ArrayList<>(Arrays.asList(jsonResponse.getData()));
                adapter = new CountryDataAdapter(data);
                mRecyclerView.setAdapter(adapter);
//                    if (pDialog.isShowing())
//                        pDialog.dismiss();
                swipe.setRefreshing(false);
                }catch (Exception e){}

            }

            @Override
            public void onFailure(Call<JsonResponse> call, Throwable t) {
                try{
                    Log.d("Error1", "no connection");
                swipe.setRefreshing(false);}
                catch(Exception e){}
            }
        });
    }
}

Do tell me if some other code is required for further clarification

This is my Screenshot .

Fragment Page

The content which you can see in the above screenshot sometimes becomes "still" and the whole content as it is becomes active at the back of this page and the front page content does not works .

Samarth Kejriwal
  • 1,168
  • 2
  • 15
  • 30

1 Answers1

2

You set new Adapter in onRefresh method again which is not recommended. try to add new Items in your adapter with method like this:

In your onCreateView initilize your Adapter with something like this:

adapter = new MyAdapter(getActivity());

Also put this method inside your adapter:

public void addItems(List<Object> newList){
       //put this method in your adapter
       adapterList = newList;
       notifyDatasetChanged();
       //it's better to call notifyItemRangeInserted()
}

And in your pull to refresh when new data comes add it your adapter. something like this:

adapter.addItems(your_new_fetch_list_data);

Also use this design pattern for retrofit may help you your code become cleaner.

Community
  • 1
  • 1
Amir
  • 16,067
  • 10
  • 80
  • 119
  • Should i make my adapter globally defined in my above code.Will it work? – Samarth Kejriwal Aug 07 '16 at 06:32
  • I have added the data in the adapter through the constructor of the adapter.So how will i make a new method to add items in the adapter. – Samarth Kejriwal Aug 07 '16 at 06:42
  • @samarthkejriwal instead of passing newData through constructor create public method in your adapter call it **addItems** and pass data to it. – Amir Aug 07 '16 at 06:44
  • Its a Fragment Activity so how will i define a new adapter with this statement- adapter = new MyAdapter(getActivity()).;... It is giving me error because it wants to accept an ArrayList type argument. – Samarth Kejriwal Aug 07 '16 at 06:59
  • define custom adapter. http://stackoverflow.com/questions/38796775/add-image-to-item-spinner#comment64963961_38796775 – Amir Aug 07 '16 at 07:05
  • Well i have defined my custom adapter ..But not getting whether the problem is solved or not.Evrything is working fine.But the problem which i was facing was happening only in case of slow connection.Now i dont know it still persists or not..Evrything is working fine till now – Samarth Kejriwal Aug 07 '16 at 07:36
  • @samarthkejriwal I don't understand what's your problem in slow connection. In slow connection it's takes awhile to fetch data so you should display progressbar while getting data. – Amir Aug 07 '16 at 07:41
  • Actually it was taking my main content to the back and was displaying a "still" page in front .I guessed that it might have been due to slow connection but now you gave me a solution.It is working fine till now.In case of any further problem i will tell you.Can i contact you on gmail?? – Samarth Kejriwal Aug 07 '16 at 08:28
  • @samarthkejriwal you can Ask on SO and many experts are ready to answer to your question. – Amir Aug 07 '16 at 08:30
  • I am still facing the same problem.I have made the changes that you said.But still the problem exists. – Samarth Kejriwal Aug 15 '16 at 06:55
  • @samarthkejriwal explain what is your problem is. Also if this is not related to this thread you can open new Thread. – Amir Aug 15 '16 at 06:58
  • I havve used a View pager in my app.I have used fragments for every page.My fragment consist of a Recycle view with cards.Sometimes what happens is that when i slide my viewpager then my content of that fragment gets at the back and a "still" page of that fragment gets visible in the front so i am not able to sroll my content.When i try to scroll ,the content at the back ,starts scrolling.Means two Recycler view contents are formed on my fragment which are overlapping each other .The front content is "still" and inactive while the back content is active. – Samarth Kejriwal Aug 15 '16 at 07:04
  • ViewPager cache your pages and it destroy it (it's cache 3 page by default). So when you go to another page ( ex. if you have 4 page and you go to 4 it assume you dont need 1 page so it destroy it) I should call you service again or do proper things in your code. – Amir Aug 15 '16 at 07:17