How to load more when i using RecyclerView and Retrofit?

5.9k views Asked by At

I want to develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts and when user scrolling on RecyclerView show more 10 posts and go to end! I am amateur and I write below codes, but I don't know to read more data when scrolling to end and show off my data! (I want to show any 10 posts in any pages). API link : API_LINK

public NewAdapter(List<Doc> docs, int rowLayout, Context context) {
    this.docs = docs;
    this.rowLayout = rowLayout;
    this.context = context;
}

@Override
public NewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    v = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
    return new NewViewHolder(v);
}

@Override
public void onBindViewHolder(final NewViewHolder holder, final int position) {
    doc = docs.get(position);
    holder.tvTitle.setText(doc.getHeadline().getMain());
    holder.tvDate.setText(doc.getPubDate());
    holder.tvDescription.setText(doc.getSnippet());
    if (docs.get(position).getMultimedia().size() > 0) {
        Glide.with(context).load(url + doc.getMultimedia().get(0).getUrl())
                .thumbnail(0.5f)
                .placeholder(R.drawable.ic_close_black_24dp)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .error(R.drawable.ic_close_black_24dp)
                .into(holder.ivPoster);
    }
    holder.newLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, WebViewActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            intent.putExtra("web_url", docs.get(position).getWebUrl());       
            context.startActivity(intent);
        }
    });
}

@Override
public int getItemCount() {
    return docs == null ? 0 : docs.size();
}

public class NewViewHolder extends RecyclerView.ViewHolder {
    LinearLayout newLayout;
    TextView tvTitle;
    TextView tvDescription;
    TextView tvDate;
    ImageView ivPoster;

    public NewViewHolder(View itemView) {
        super(itemView);
        newLayout = (LinearLayout) itemView.findViewById(R.id.new_layout);
        tvDate = (TextView) itemView.findViewById(R.id.tvDate);
        tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
        tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
        ivPoster = (ImageView) itemView.findViewById(R.id.ivPoster);
    }
}

MainActivity

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    newDocs = (List<Doc>) getIntent().getSerializableExtra("Doc");
    change = getIntent().getBooleanExtra("change", false);
    init();
    setToolbar();
    setContent();

    //Xét điều kiện thay đổi
    if (change) {
        if (newDocs.size() > 0) {
            Toast.makeText(MainActivity.this, "Data", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "Empty", Toast.LENGTH_SHORT).show();
        }
        setRecycleView(newDocs);
    }
    getData();


}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

private void setToolbar() {
    setSupportActionBar(toolbar);
}

//Function xác nhận dữ liệu trả về id
private void init() {
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    mRecyclerView = (RecyclerView) findViewById(R.id.new_recycler_view);
    refreshLayout = (SwipeRefreshLayout) findViewById(R.id.srlMain);
    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    navigationView = (NavigationView) findViewById(R.id.nav_view);
}


private void setContent() {

    toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();
    navigationView.setNavigationItemSelectedListener(this);
    refreshLayout.setOnRefreshListener(this);

    //Set Recyclerview
    mRecyclerView.setNestedScrollingEnabled(false);
    final LinearLayoutManager mLayoutManager;
    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));

}

    //Function lấy dữ liệu RecyclerView

private void setRecycleView(List<Doc> list) {
    newAdapter = new NewAdapter(list, R.layout.new_listitems, MainActivity.this);
    newAdapter.notifyDataSetChanged();
    mRecyclerView.setAdapter(newAdapter);

}

//Function nhận dữ liệu
private void getData() {
    APIinterface apiSevice = APIClient.getClient().create(APIinterface.class);
    Call<Resonpe> call = apiSevice.getHotNew(API_KEY);
    call.enqueue(new Callback<Resonpe>() {
        @Override
        public void onResponse(Call<Resonpe> call, Response<Resonpe> response) {
            if (response.isSuccessful()) {
                docs = response.body().getNewResponse().getDocs();
                if (!change) {
                    setRecycleView(docs);
                }
            } else {
                Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<Resonpe> call, Throwable t) {
            Toast.makeText(MainActivity.this, "Internet is not connected", Toast.LENGTH_SHORT).show();
        }
    });
}

//Function tạo phần OptionMenu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    MenuItem searchItem = menu.findItem(R.id.action_search);
    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

    return super.onCreateOptionsMenu(menu);
}

//Function xử lý sự kiên click items của Option
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onRefresh() {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            refreshLayout.setRefreshing(false);
            if (change) {
                setRecycleView(newDocs);
            } else {
                setRecycleView(docs);
            }
        }
    }, 2500);

}

// Function xử lý sự kiên click items của NavigationView
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    newDocs = new ArrayList<>();
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    if (id == R.id.nav_camera) {
        for (Doc doc : docs) {
            if (doc.getNewDesk().equals("Sport")) {
                newDocs.add(doc);
            }
        }
    } else if (id == R.id.nav_gallery) {
        for (Doc doc : docs) {
            if (doc.getNewDesk().equals("Fashion")) {
                newDocs.add(doc);
            }
        }
    } else if (id == R.id.nav_slideshow) {
        for (Doc doc : docs) {
            if (doc.getNewDesk().equals("Arts")) {
                newDocs.add(doc);
            }
        }
    } else if (id == R.id.nav_manage) {
        for (Doc doc : docs) {
            if (doc.getNewDesk().equals("None")) {
                newDocs.add(doc);
            }
        }
    }

    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra("Doc", (Serializable) newDocs);
    intent.putExtra("change", true);
    startActivity(intent);
    finish();

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
1

There are 1 answers

1
taman neupane On BEST ANSWER

you can check out this code path tutorial. without any use of external library. Just simply a class. And you can define how many items you want in one page and at the center of page i.e. at 5-6 items you can load more data and notifyDatasetChange to recycler view adapter. please go through this link.

https://github.com/codepath/android_guides/wiki/Endless-Scrolling-with-AdapterViews-and-RecyclerView