简体   繁体   中英

Show limited items in RecyclerView

Please Bear my English

I have total 3000 entries in my database and I want to show all those entries in my recyclerView.

Code for my recyclerView :

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_complaint_reg );

    swipe = (SwipeRefreshLayout) findViewById( R.id.swipe_refresh_complaint );
    swipe.setOnRefreshListener(complaintReg.this );

    swipe.post( new Runnable() {
        @Override
        public void run() {
            swipe.setRefreshing( true );

            fetchdata();
        }
    } );


}
public void  fetchdata(){
    swipe.setRefreshing( true );
    new AsyncLogin().execute();
    swipe.setRefreshing( false );
}

@Override
public void onRefresh() {
    fetchdata();
}


private class AsyncLogin extends AsyncTask<String,Void,String> {
    ProgressDialog pdloding = new ProgressDialog(complaintReg.this);
    HttpURLConnection conn;
    URL url = null;

    @Override
    protected void onPreExecute(){
        super.onPreExecute();

        pdloding.setMessage( "\tLoading.." );
        pdloding.setCancelable( false );
        pdloding.show();
    }

    @Override
    protected String doInBackground(String... strings) {
        try {
            url = new URL("http://localhost/SearchComp.php");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }


        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {

                return ("unsuccessful");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }


    }

    @Override
    protected void onPostExecute(String result){
        Log.e( TAG,"result"+result );

        pdloding.dismiss();
        List<dataRegComplaint> data = new ArrayList<>(  );
        pdloding.dismiss();
        if(result.equals( "No complaint assgin" )){
            Toast.makeText( complaintReg.this, "No Complaint Assign", Toast.LENGTH_SHORT ).show();
        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    dataRegComplaint fishData = new dataRegComplaint(
                            json_data.getString("cust_name"),
                            json_data.getString("CatName"),
                            json_data.getString("site_Name"),
                            json_data.getString( "SrcName" ));
                    data.add(fishData);

                    Log.e( TAG, "DATA reesult :"+data );
                }
                // cAdapter.notifyDataSetChanged();
                // Setup and Handover data to recyclerview
                Register_complaints = (RecyclerView)findViewById(R.id.Reg_Complaint_List);
                Reg_Adapter = new Register_Adapter(complaintReg.this,data);
                Register_complaints.setAdapter(Reg_Adapter);
                Register_complaints.setLayoutManager(new LinearLayoutManager(complaintReg.this));
            } catch (JSONException e) {
            }

        }
    }

}

Code for my Adapter :

public class Register_Adapter extends RecyclerView.Adapter<Register_Adapter.MyHolder> {
private Context context;
List<dataRegComplaint> data = Collections.emptyList();
static int total;
View v;

public Register_Adapter(complaintReg complaintReg,List<dataRegComplaint> data) {
this.context = complaintReg;
this.data = data;
}

@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.container_register, viewGroup, false);
    return new MyHolder( v );
}

@Override
public void onBindViewHolder(@NonNull MyHolder myHolder, int i) {
    final dataRegComplaint current=data.get(i);
    myHolder.client.setText(current.getClientName());
    myHolder.location.setText("Reason: " + current.getAddress());
    myHolder.product.setText("Client   : " + current.getProduct());
    myHolder.category.setText("Location: " + current.getCategory());

}

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

public class MyHolder extends RecyclerView.ViewHolder{
    TextView client,location,product,category;
    Button complaint_register;
    public MyHolder(@NonNull View itemView) {

        super( itemView );

        client = (TextView) itemView.findViewById( R.id.textclient );
        location = (TextView) itemView.findViewById( R.id.textlocation );
        product  = (TextView) itemView.findViewById( R.id.textproduct );
        category = (TextView) itemView.findViewById( R.id.textcategory );
        complaint_register = (Button) itemView.findViewById( R.id.button_register );
    }
}
}

So whenever i try to show all entries in my recyclerview the app crashes because it can't load all items at once.

So can anyone help me out in this situation.

download the project here and follow below mention steps.

  1. Movie.java -> replace with your ModelClass

  2. PaginationAdapter -> replace with your adapter[include left methods in PaginationAdapter(check the adapter)]

  3. PaginationScrollListener -> Keep this as same[no changes]

in mainActivity.java

  1. loadFirstPage() -> call this method after you fetch the data from your server to your app.

  2. List movies = Movie.createMovies(adapter.getItemCount());

    you will find this line of code inside loadFirstPage() method. in this, Movie -> ModelClass & createMovies() -> static method that gives your 10 items at a time. you can increase count in for-loop

xml

  1. item_list.xml -> your recyclerview row xml

  2. item_progress.xml -> keep as same

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM