wake-up-neo.com

Ziehen Sie, um das Recycling-Android zu aktualisieren

Hallo, ich habe eine Aktivität mit Registerkarten und auf der ersten Registerkarte rufe ich Daten vom Server ab und zeige sie in einer Recyclingübersicht in den Kartenansichten. Zum Abrufen der Daten vom Server verwende ich die Volleybibliothek. Ich möchte den Pull zum Aktualisieren implementieren, um die Daten zu laden (wenn ich also Pulle, muss er die Anfrage an das Netzwerk stellen). Und ich möchte die Netzwerkanforderung auch deaktivieren, wenn ich zwischen Registerkarten wechsle (da beim Wechseln des Registerkartenfokus in meiner App damit begonnen wird, Daten abzurufen), möchte ich die Netzwerkanfrage nur einmal (wenn sich der Benutzer zum ersten Mal anmeldet) und dann andere Anfragen werden nur per Pull zum Aktualisieren bearbeitet. 

Hier ist mein Fragment, wo ich die Daten wiederverwendet habe und die Daten anzeigt:

public class Tab1History extends Fragment
{

private RecyclerView recyclerView;
private CespiteAdapter adapter;
UserSessionManager session;

private static final String URL_DATA = "http://mydata.php";

private List<CespiteOgg> cespiteOggList;

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

    View rootView = inflater.inflate(R.layout.tab1history, container, false);

    recyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
    recyclerView.setHasFixedSize(true);//every item of the RecyclerView has a fix size
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    cespiteOggList = new ArrayList<>();

    loadRecyclerViewData();

            return rootView;
}

private void loadRecyclerViewData()
{
    // Session class instance
    session = new UserSessionManager(getActivity());
    //get user data from session
    HashMap<String, String> user = session.getUserDetails();
    //get name
    String name = user.get(UserSessionManager.KEY_NAME);
    // get username
    final String usernameUtente = user.get(UserSessionManager.KEY_USERNAME);

    final ProgressDialog progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage("Carimento dati...");
    progressDialog.show();

    StringRequest stringRequest = new StringRequest(Request.Method.POST,
            URL_DATA,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    progressDialog.dismiss();
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        JSONArray array = jsonObject.getJSONArray("dates");

                        for(int i=0; i<array.length(); i++)
                        {
                            JSONObject o = array.getJSONObject(i);
                            CespiteOgg item = new CespiteOgg(
                                    o.getString("CodNumInventario"),
                                    o.getString("Nome"),
                                    o.getString("DtCatalogazione"),
                                    o.getString("CodIdA"),
                                    o.getString("username")
                            );
                            cespiteOggList.add(item);
                        }

                        adapter = new CespiteAdapter(cespiteOggList, getActivity());
                        recyclerView.setAdapter(adapter);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressDialog.dismiss();
                }
            })
            {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("Username", usernameUtente);
                    return params;
                }
            };

    RegisterRequest.getmInstance(getActivity()).addToRequestque(stringRequest);

}
}

Und es ist der Adapter:

public class CespiteAdapter extends RecyclerView.Adapter<CespiteAdapter.ViewHolder>
{


private List<CespiteOgg> cespiteOggList;
private Context context;

public CespiteAdapter(List<CespiteOgg> cespiteOggList, Context context) {

    this.cespiteOggList = cespiteOggList;
    this.context = context;
}

public class ViewHolder extends RecyclerView.ViewHolder
{

    public CardView cv;
    public TextView txtNumInventario;
    public TextView txtNomeCespite;
    public TextView txtDtCatalogazione;
    public TextView txtAula;
    public TextView txtNomeUser;


    ViewHolder(View itemView)
    {

        super (itemView);
        //cv = (CardView) itemView.findViewById(R.id.cardView);
        txtNumInventario = (TextView) itemView.findViewById(R.id.txtNumeroInventario);
        txtNomeCespite = (TextView) itemView.findViewById(R.id.txtNomeCespite);
        txtDtCatalogazione = (TextView) itemView.findViewById(R.id.txtDataCatalogazione);
        txtAula = (TextView) itemView.findViewById(R.id.txtAula);
        txtNomeUser= (TextView) itemView.findViewById(R.id.txtNomeUser);


    }
}



@Override
public CespiteAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{

    LayoutInflater inflater = LayoutInflater.from(parent.getContext());

    View cespiteView = inflater.inflate(R.layout.cespite_card_view, parent, false);

    return new ViewHolder(cespiteView);
}

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

    CespiteOgg cespiteOgg = cespiteOggList.get(position);

    holder.txtNumInventario.setText(cespiteOgg.getNumInventario());
    holder.txtNomeCespite.setText(cespiteOgg.getNomeCespite());
    holder.txtDtCatalogazione.setText(cespiteOgg.getDtCatalogazione());
    holder.txtAula.setText(cespiteOgg.getAula());
    holder.txtNomeUser.setText(cespiteOgg.getNomeUser());

}

@Override
public int getItemCount()
{

    return cespiteOggList.size();
}

}
28
arst3k

Sie können Android SwipeRefreshLayout widget anstelle von ProgressDialog verwenden.

Befolgen Sie die folgenden Schritte, um SwipeRefreshLayout in Ihr Tab1history-Fragment zu integrieren:

1. Fügen Sie in Ihrem Layout tab1historySwipeRefreshLayout als Stammlayout hinzu und platzieren Sie RecyclewrView darin.

// tab1history.xml
<?xml version="1.0" encoding="utf-8"?>
<Android.support.v4.widget.SwipeRefreshLayout
    xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:id="@+id/swipe_container"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent">

        <Android.support.v7.widget.RecyclerView
            Android:id="@+id/my_recycler_view"
            Android:layout_width="match_parent"
            Android:layout_height="match_parent" />

</Android.support.v4.widget.SwipeRefreshLayout>

2. Verwenden Sie in Ihrem Tab1History-Fragment SwipeRefreshLayout wie folgt, um Daten vom Server zu laden:

// Tab1History.Java
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.view.LayoutInflater;
import Android.view.View;
import Android.view.ViewGroup;

import com.Android.volley.Request;
import com.Android.volley.Response;
import com.Android.volley.toolbox.StringRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Java.util.ArrayList;


public class Tab1History extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView recyclerView;
    private CespiteAdapter adapter;
    UserSessionManager session;

    private static final String URL_DATA = "http://mydata.php";

    private List<CespiteOgg> cespiteOggList;

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

        View rootView = inflater.inflate(R.layout.tab1history, container, false);


        recyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);//every item of the RecyclerView has a fix size
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        cespiteOggList = new ArrayList<>();


        // SwipeRefreshLayout
        mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
                Android.R.color.holo_green_dark,
                Android.R.color.holo_orange_dark,
                Android.R.color.holo_blue_dark);

        /**
         * Showing Swipe Refresh animation on activity create
         * As animation won't start on onCreate, post runnable is used
         */
        mSwipeRefreshLayout.post(new Runnable() {

            @Override
            public void run() {

                mSwipeRefreshLayout.setRefreshing(true);

                // Fetching data from server
                loadRecyclerViewData();
            }
        });

        return rootView;
    }

    /**
     * This method is called when swipe refresh is pulled down
     */
    @Override
    public void onRefresh() {

        // Fetching data from server
        loadRecyclerViewData();
    }

    private void loadRecyclerViewData()
    {
        // Showing refresh animation before making http call
        mSwipeRefreshLayout.setRefreshing(true);

        // Session class instance
        session = new UserSessionManager(getActivity());
        //get user data from session
        HashMap<String, String> user = session.getUserDetails();
        //get name
        String name = user.get(UserSessionManager.KEY_NAME);
        // get username
        final String usernameUtente = user.get(UserSessionManager.KEY_USERNAME);


        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                URL_DATA,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {

                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONArray array = jsonObject.getJSONArray("dates");

                            for(int i=0; i<array.length(); i++)
                            {
                                JSONObject o = array.getJSONObject(i);
                                CespiteOgg item = new CespiteOgg(
                                        o.getString("CodNumInventario"),
                                        o.getString("Nome"),
                                        o.getString("DtCatalogazione"),
                                        o.getString("CodIdA"),
                                        o.getString("username")
                                );
                                cespiteOggList.add(item);
                            }

                            adapter = new CespiteAdapter(cespiteOggList, getActivity());
                            recyclerView.setAdapter(adapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        // Stopping swipe refresh
                        mSwipeRefreshLayout.setRefreshing(false);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        // Stopping swipe refresh
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("Username", usernameUtente);
                return params;
            }
        };

        RegisterRequest.getmInstance(getActivity()).addToRequestque(stringRequest);

    }
}

Hoffe das wird richtig funktionieren.

65
Ferdous Ahamed

Quellcode

https://drive.google.com/open?id=1qjJ_to-1knVNaJB4T3U_L_p_YYNvgAeZ

APK

https://drive.google.com/open?id=1MxQZwjIXgR2jgDkUW1mbFrTLMSaQQisC

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {


    SwipeRefreshLayout mSwipeRefreshLayout;


        // SwipeRefreshLayout
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);

        mSwipeRefreshLayout.setOnRefreshListener(this);
//        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent,
                Android.R.color.holo_green_dark,
                Android.R.color.holo_orange_dark,
                Android.R.color.holo_blue_dark);

        /**
         * Showing Swipe Refresh animation on activity create
         * As animation won't start on onCreate, post runnable is used
         */
        mSwipeRefreshLayout.post(new Runnable() {

            @Override
            public void run() {

                if(mSwipeRefreshLayout != null) {
                    mSwipeRefreshLayout.setRefreshing(true);
                }
                // TODO Fetching data from server
                fetchContacts();
            }
        });



  @Override
    public void onRefresh() {
        fetchContacts();
    }
3
Keshav Gera

Android verfügt dazu über ein SwipeToRefresh - Widget. 


Diese Frage wurde bereits hier beantwortet How-to-Implement-Pull-Down-Refresh-in-Android und How-to-Implement-Android-Pull-to-Refresh

1
KG87

Pull zum Aktualisieren von ListView & RecyclerView-Beispiel In Android Studio - SwipeRefreshLayout.Ich hoffe, dass dieser Code richtig funktioniert. Sie können diesen Code ausprobieren.

Basic Pull To Refresh/SwipeRefreshLayout-XML-Code:

    <Android.support.v4.widget.SwipeRefreshLayout
        Android:id="@+id/simpleSwipeRefreshLayout"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content">

        < Add View's Here..../>
</Android.support.v4.widget.SwipeRefreshLayout>

Unten können Sie Code herunterladen, die endgültige Ausgabe sehen und eine schrittweise Erklärung des grundlegenden Pull-To-Beispiels erhalten. Holen Sie sich den vollständigen Code mit Beispiel https://abhiandroid.com/materialdesign/pulltorefresh

0
ItsJamez