Home > OS >  new json data is not showing in android
new json data is not showing in android

Time:10-28

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.

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