updated json data not showing in android

Viewed 111

retrieve json data from my server. first time showing the data in my app. but while updating new data, it's not showing. only showing the old data.. while i'm clearing cache from the app, then it's showing the updated data. but i want to show real-time data in same time. what i have to do? please help me.

RecyclerViewAdapter.java

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
    private Context mContext ;
    private List<Anime> mData ;
    RequestOptions option;

    public RecyclerViewAdapter(Context mContext, List<Anime> mData) {
        this.mContext = mContext;
        this.mData = mData;

        // Request option for Glide
        option = new RequestOptions().centerCrop().placeholder(R.drawable.loading_shape).error(R.drawable.loading_shape);
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view ;
        LayoutInflater inflater = LayoutInflater.from(mContext);
        view = inflater.inflate(R.layout.anime_row_item,parent,false) ;
        final MyViewHolder viewHolder = new MyViewHolder(view) ;
        viewHolder.view_container.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent(mContext, Read.class);
                i.putExtra("news_title",mData.get(viewHolder.getAdapterPosition()).getName());
                i.putExtra("news_description",mData.get(viewHolder.getAdapterPosition()).getDescription());
                i.putExtra("anime_studio",mData.get(viewHolder.getAdapterPosition()).getAuthor());
                i.putExtra("anime_category",mData.get(viewHolder.getAdapterPosition()).getCategorie());
                i.putExtra("anime_img",mData.get(viewHolder.getAdapterPosition()).getImage_url());

                mContext.startActivity(i);

            }
        });

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        holder.post_title.setText(mData.get(position).getName());
        holder.date.setText(mData.get(position).getDate());
        holder.author.setText(mData.get(position).getAuthor());
        holder.cat_name.setText(mData.get(position).getCategorie());

        // Load Image from the internet and set it into Imageview using Glide
        Glide.with(mContext).load(mData.get(position).getImage_url()).apply(option).into(holder.thumbnail);

    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        TextView post_title ;
        TextView date ;
        TextView author ;
        TextView cat_name;
        ImageView thumbnail;
        LinearLayout view_container;

        public MyViewHolder(View itemView) {
            super(itemView);

            view_container = itemView.findViewById(R.id.container);
            post_title = itemView.findViewById(R.id.post_title);
            cat_name = itemView.findViewById(R.id.cat_name);
            date = itemView.findViewById(R.id.date);
            author = itemView.findViewById(R.id.author);
            thumbnail = itemView.findViewById(R.id.thumbnail);

        }
    }
}

Home.java

public class Home extends Fragment {

    private final String JSON_URL = "https://mywebsite.org/news/api.php";
    private JsonArrayRequest request ;
    private RequestQueue requestQueue ;
    private List<Anime> lstAnime ;
    private RecyclerView recyclerView ;
    ProgressBar loading;

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

        loading = (ProgressBar)root.findViewById(R.id.bar);
        loading.setMax(100);
        lstAnime = new ArrayList<>() ;
        recyclerView = root.findViewById(R.id.recyclerviewid);

        jsonrequest();

        return root;
    }

    private void jsonrequest() {

        request = new JsonArrayRequest(JSON_URL, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                loading.setVisibility(View.GONE);
                JSONObject jsonObject  = null ;

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

                    try {
                        jsonObject = response.getJSONObject(i) ;
                        Anime anime = new Anime() ;
                        anime.setName(jsonObject.getString("title"));
                        anime.setDescription(jsonObject.getString("description"));
                        anime.setDate(jsonObject.getString("date"));
                        anime.setCategorie(jsonObject.getString("category"));
                        anime.setAuthor(jsonObject.getString("admin"));
                        anime.setImage_url(jsonObject.getString("thumbnail"));
                        lstAnime.add(anime);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                setuprecyclerview(lstAnime);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                    //This indicates that the request has either time out or there is no connection
                    Toast.makeText(getActivity(), "TimeOut...! No Internet",
                            Toast.LENGTH_LONG).show();

                } else if (error instanceof AuthFailureError) {
                    // Error indicating that there was an Authentication Failure while performing the request
                    Toast.makeText(getActivity(), "Failed To Receive Data",
                            Toast.LENGTH_LONG).show();

                } else if (error instanceof ServerError) {
                    //Indicates that the server responded with a error response
                    Toast.makeText(getActivity(), "Our Server Under Maintenance",
                            Toast.LENGTH_LONG).show();
                } else if (error instanceof NetworkError) {
                    //Indicates that there was network error while performing the request
                    Toast.makeText(getActivity(), "Network Not Responding",
                            Toast.LENGTH_LONG).show();
                } else if (error instanceof ParseError) {
                    // Indicates that the server response could not be parsed
                    Toast.makeText(getActivity(), "Please Reload Again!",
                            Toast.LENGTH_LONG).show();
                }
            }
        });

        requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(request);
    }

    private void setuprecyclerview(List<Anime> lstAnime) {

        RecyclerViewAdapter myadapter = new RecyclerViewAdapter(getActivity(),lstAnime);
        recyclerView.setAdapter(myadapter);

        // grid columns is 2
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 2);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                // 0 is first one and 9 is first one all of others are 2 columns
                if (position == 0 || position == 9) {
                    return 2;
                }
                return 1;}
        });
        recyclerView.setItemAnimator(null);
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(myadapter);
        recyclerView.setLayoutManager(manager);
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);

    }

}

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipeContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        tools:context=".fragments.Home"
        android:orientation="vertical">

        <!-- TODO: Update blank fragment layout -->

        <ProgressBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:id="@+id/bar"/>

            <androidx.recyclerview.widget.RecyclerView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/recyclerviewid">

            </androidx.recyclerview.widget.RecyclerView>
    </LinearLayout>

</androidx.core.widget.NestedScrollView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

Sorry for my bad English. Thanks in advance.

1 Answers

Notify your recycler view using notifyDataSetChanged in your jsonrequest() method.Clear cache using requestQueue.getCache().clear(); Check the below code:

public class Home extends Fragment {

    private final String JSON_URL = "https://mywebsite.org/news/api.php";
    private JsonArrayRequest request ;
    private RequestQueue requestQueue ;
    private List<Anime> lstAnime ;
    private RecyclerView recyclerView ;
    ProgressBar loading;
    RecyclerViewAdapter myadapter;
    **SwipeRefreshLayout swipeRefreshLayout;**
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);

        loading = (ProgressBar)root.findViewById(R.id.bar);
        loading.setMax(100);
        lstAnime = new ArrayList<>() ;
        recyclerView = root.findViewById(R.id.recyclerviewid);

        jsonrequest();
        setuprecyclerview(lstAnime);
         **swipeRefreshLayout=view.findViewById(R.id.swipeContainer);
            swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh()
                {
                    jsonrequest();
                    myAdapter.notifyDataSetChanged();
                    swipeRefreshLayout.setRefreshing(false);
                }
            });**
        return root;
    }

    private void jsonrequest() {

        request = new JsonArrayRequest(JSON_URL, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                loading.setVisibility(View.GONE);
                JSONObject jsonObject  = null ;

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

                    try {
                        jsonObject = response.getJSONObject(i) ;
                        Anime anime = new Anime() ;
                        anime.setName(jsonObject.getString("title"));
                        anime.setDescription(jsonObject.getString("description"));
                        anime.setDate(jsonObject.getString("date"));
                        anime.setCategorie(jsonObject.getString("category"));
                        anime.setAuthor(jsonObject.getString("admin"));
                        anime.setImage_url(jsonObject.getString("thumbnail"));
                        lstAnime.add(anime);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if(myadapter != null)
                myadapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                    //This indicates that the request has either time out or there is no connection
                    Toast.makeText(getActivity(), "TimeOut...! No Internet",
                            Toast.LENGTH_LONG).show();

                } else if (error instanceof AuthFailureError) {
                    // Error indicating that there was an Authentication Failure while performing the request
                    Toast.makeText(getActivity(), "Failed To Receive Data",
                            Toast.LENGTH_LONG).show();

                } else if (error instanceof ServerError) {
                    //Indicates that the server responded with a error response
                    Toast.makeText(getActivity(), "Our Server Under Maintenance",
                            Toast.LENGTH_LONG).show();
                } else if (error instanceof NetworkError) {
                    //Indicates that there was network error while performing the request
                    Toast.makeText(getActivity(), "Network Not Responding",
                            Toast.LENGTH_LONG).show();
                } else if (error instanceof ParseError) {
                    // Indicates that the server response could not be parsed
                    Toast.makeText(getActivity(), "Please Reload Again!",
                            Toast.LENGTH_LONG).show();
                }
            }
        });

        requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.getCache().clear();//add this line
        requestQueue.add(request);
    }

    private void setuprecyclerview(List<Anime> lstAnime) {

         myadapter = new RecyclerViewAdapter(getActivity(),lstAnime);
        recyclerView.setAdapter(myadapter);

        // grid columns is 2
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 2);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                // 0 is first one and 9 is first one all of others are 2 columns
                if (position == 0 || position == 9) {
                    return 2;
                }
                return 1;}
        });
        recyclerView.setItemAnimator(null);
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(myadapter);
        recyclerView.setLayoutManager(manager);
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);

    }

}

Also in your recyclerviewadapter.java add this line to recycler adapter constructor:

   public RecyclerViewAdapter(Context mContext, List<Anime> mData) {
    this.mContext = mContext;
    this.mData = mData;
    this.notifyDataSetChanged();
    // Request option for Glide
    option = new RequestOptions().centerCrop().placeholder(R.drawable.loading_shape).error(R.drawable.loading_shape);
}

Remove your nested scrollview from your xml file:

  <?xml version="1.0" encoding="utf-8"?>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/swipeContainer"
 android:layout_width="match_parent"
 android:layout_height="match_parent">
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        tools:context=".fragments.Home"
        android:orientation="vertical">

        <!-- TODO: Update blank fragment layout -->

        <ProgressBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:id="@+id/bar"/>

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/recview">
        </androidx.recyclerview.widget.RecyclerView>
    </LinearLayout>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
Related