Home > Software engineering >  How to swipe to update json data in android studio?
How to swipe to update json data in android studio?

Time:10-27

When my server updates new data, and the user swipes to reload, it's not working for me. I have fragment_home.xml and Home.java to show the data. Now, how I can do that? my XML file is working well, but I don't understand what to do in java? Can you please post an answer by editing my code to better understand?

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>

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);

    }

}

Sorry for my bad English. Thanks in advance.

CodePudding user response:

If you want to update data in your App as soon as the data gets updated on server then you should use Web-Sockets instead of API, because an API only give response when you hit it with correct credentials.

CodePudding user response:

I don't see a place where you initialize the SwipeRefreshLayout contained in your xml file. Your fragment should implement SwipeRefreshLayout.OnRefreshListener and override the onRefresh() method in order to trigger your network request. Also don't forget to dismiss the SwipeRefreshLayout loader when the network request is done using swipeRefreshLayout.setRefreshing(boolean)

You can view the documentation for more details: https://developer.android.com/training/swipe

Here is your fragment with SwipeRefreshLayout implemented.

public class Home extends Fragment implements SwipeRefreshLayout.OnRefreshListener{

    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;

    private SwipeRefreshLayout swipeRefreshLayout; //declare SwipeRefreshLayout

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

        swipeRefreshLayout = (SwipeRefreshLayout)root.findViewById(R.id.swipeContainer);
        swipeRefreshLayout.setOnRefreshListener(this);  //add refresh listener

        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) {
                swipeRefreshLayout.setRefreshing(false); //Dismiss SwipeRefreshLayout loader
                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) {
                swipeRefreshLayout.setRefreshing(false); //Dismiss SwipeRefreshLayout loader

                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);

    }


    @Override
    public void onRefresh() {
        //Whatever is here will be executed when the user swipe to refresh
        jsonrequest(); 
    }
}
  • Related