How to Load Json in Endless Recycler Veiw with Retrofit - android

I try to implement Endless Recycler View with my Json Response .
This is My Json Response Link
I Generate my models with jsonschema2pojo.org and I load the data in my recyclerview successfully .
But I need to implement endless recycler view :
This is my RecyclerAdapter :
public class AparatAdapter extends RecyclerView.Adapter<AparatAdapter.ViewHolder> {
private Context context;
private ArrayList<Categoryvideo> categoryVideos;
//=============================constructor
public AparatAdapter(Context context, ArrayList<Categoryvideo> categoryVideos) {
this.context = context;
this.categoryVideos = categoryVideos;
}
//=============================viewholder
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView txtTitle ,txtCount ,txtSender ,txtDate;
private ImageView imgRow;
public ViewHolder(View itemView) {
super(itemView);
txtTitle = (TextView)itemView.findViewById(R.id.txt_title_row);
txtCount = (TextView)itemView.findViewById(R.id.txt_count_dynamic_row);
txtSender = (TextView)itemView.findViewById(R.id.txt_sender_dynamic_row);
txtDate = (TextView)itemView.findViewById(R.id.txt_date_dynamic_row);
imgRow = (ImageView)itemView.findViewById(R.id.img_row);
}
}
//================================oncreateviewholder
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, parent,false);
return new ViewHolder(view);
}
//================================= onbindviewholder
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.txtTitle.setText(categoryVideos.get(position).getTitle());
holder.txtCount.setText(categoryVideos.get(position).getVisitCnt().toString());
holder.txtSender.setText(categoryVideos.get(position).getSenderName());
holder.txtDate.setText(categoryVideos.get(position).getSdate().toString());
Glide.with(holder.itemView.getContext()).load(categoryVideos.get(position).getSmallPoster())
.into(holder.imgRow);
}
//==================================getitemcount
#Override
public int getItemCount() {
return categoryVideos.size();
}
}
And This is the activity where i load the json in that with retrofit :
public class SargarmiActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private AparatAdapter adapter;
private LinearLayoutManager layoutManager;
private ArrayList<Categoryvideo> categoryvideos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sargarmi);
initViews();
}
//=================================================
private void initViews() {
recyclerView = (RecyclerView) findViewById(R.id.recycler_sargarmi);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(SargarmiActivity.this);
recyclerView.setLayoutManager(layoutManager);
sendRequest();
}
//=================================================
private void sendRequest() {
recyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(layoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount) {
loadMore();
}
});
getData();
}
//=======================================================
private void getData() {
//1
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.aparat.com/etc/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
//2
ApiInterface request = retrofit.create(ApiInterface.class);
//3
Call<JSONResponse> call = request.getJsonResponse();
//4
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
if (response.isSuccessful()) {
JSONResponse jsonResponse = response.body();
categoryvideos = new ArrayList<>(jsonResponse.getCategoryvideos());
adapter = new AparatAdapter(SargarmiActivity.this, categoryvideos);
recyclerView.setAdapter(adapter);
} else {
Toast.makeText(SargarmiActivity.this, "Error darim else onresponse", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Toast.makeText(SargarmiActivity.this, "Error darim onFailure()", Toast.LENGTH_SHORT).show();
}
});
}
//=============== Load more Endless =====================
private void loadMore() {
}
}
As you can see in json my pagination url embed in ui object . and i don't know what should i write in the loadmore() method in my activity.

When you download the initial load of categoryvideos, there is also an elementcalled: pagingForward. This contains the url for you to download the next 20 items.
So what you want to do is:
When downloading the first videos, fetch the pagingForward value
and store this somewhere.
When you call loadMore() you make another download with Retrofit
with the url.
Retrofit will download the objects and you will get another
pagingForward url that will then point to the next 20 items.
This can keep on going until there are no more objects to fetch
(Not sure how the API respons then, you need to check with the
persons who wrote the API)

Related

I am facing "No adapter attached; skipping layout" error

When I am writing the title of my question, then this site recommends me some answer but I can't find my answer that's why I am writing a new one. I am trying simple RecyclerView and it's run successfully but when I am fetching data from internet using volley library then I face this error
here is my code
BusinessActivity.java
public class BusinessActivity extends AppCompatActivity {
private final String URL = "https://api.myjson.com/bins/a44ec";
private JsonArrayRequest request;
private RequestQueue requestQueue;
private List<ArticleModel> articleList;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business);
articleList = new ArrayList<>();
recyclerView = findViewById(R.id.business_recyclerView);
jsonParse();
}
private void jsonParse() {
request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i=0;i<response.length();i++){
try {
jsonObject = response.getJSONObject(i);
ArticleModel article = new ArticleModel();
article.setTitle(jsonObject.getString("title"));
article.setAuthor(jsonObject.getString("author"));
article.setDescription(jsonObject.getString("description"));
article.setPublishedAt(jsonObject.getString("publishedAt"));
article.setUrlToImage(jsonObject.getString("urlToImage"));
articleList.add(article);
} catch (JSONException e) {
e.printStackTrace();
}
}
setRecyclerView(articleList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(BusinessActivity.this);
requestQueue.add(request);
}
private void setRecyclerView(List<ArticleModel> articleList) {
BusinessAdapter adapter = new BusinessAdapter(articleList,this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
}
BusinessAdapter.java
public class BusinessAdapter extends RecyclerView.Adapter<BusinessAdapter.MyViewHolder> {
private List<ArticleModel> articleModels;
private Context context;
RequestOptions options;
public BusinessAdapter(List<ArticleModel> articleModels, Context context) {
this.articleModels = articleModels;
this.context = context;
options = new RequestOptions().centerCrop().placeholder(R.drawable.ic_launcher_background).error(R.drawable.ic_launcher_background);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.category_row,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
ArticleModel articleModel = articleModels.get(position);
holder.title.setText(articleModel.getTitle());
holder.author.setText(articleModel.getAuthor());
holder.desc.setText(articleModel.getDescription());
holder.date.setText(articleModel.getPublishedAt());
Glide.with(context).load(articleModel.getUrlToImage()).apply(options).into(holder.image);
}
#Override
public int getItemCount() {
return articleModels.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView title,author,desc,date;
ImageView image;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title);
author = itemView.findViewById(R.id.author);
desc = itemView.findViewById(R.id.detail);
date = itemView.findViewById(R.id.date);
image = itemView.findViewById(R.id.image);
}
}
}
Error log
2020-04-01 00:15:53.117 8821-8821/com.atc.newsappproject E/RecyclerView: No adapter attached; skipping layout
2020-04-01 00:15:53.118 1752-1787/? E/storaged: getDiskStats failed with result NOT_SUPPORTED and size 0
How can I solve this?
Thank you.
This error usually happens when you don't set the RecyclerView when you create your Fragment or Activity. To fix this you need to:
Set your RecyclerView in onCreate instead of when you pick up result. You set it with an empty list.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business);
articleList = new ArrayList<>();
recyclerView = findViewById(R.id.business_recyclerView);
setRecyclerView(articleList);
jsonParse();
}
You create a setter in your Adapter
public void setArticles(ArrayList<ArticleModel> articles){
this.articles = articles;
notifyDataSetChanged();
}
Create private BusinessAdapter adapter; below private RecyclerView recyclerView;
Finally in your onResponse you call adapter.setArticles(articlesList);
Here is a link with a lot of solutions if you still got issue: recyclerview No adapter attached; skipping layout

why RecycleView items is not displayed?

I have a problem. When I use newsPojo at first - all displayed ok (but swipe to refresh is not work, when I use postAdapter.notifyDataSetChanged() - my items is not displayed. How can I fix it?
This is my Activity class
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private NewsApi newsApi;
private NewsPojo fromRetrofit;
private MainAdapter postAdapter;
#BindView(R.id.activity_main_swipe_to_refresh) SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
fromRetrofit = new NewsPojo();
fromRetrofit.setArticles(new ArrayList<Article>());
response();
initRecycleView();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
response();
swipeRefreshLayout.setRefreshing(false);
}
});
}
private void response() {
newsApi = RitApplication.getApi();
newsApi.getData().enqueue(new Callback<NewsPojo>() {
#Override
public void onResponse(Call<NewsPojo> call, Response<NewsPojo> response) {
fromRetrofit.getArticles().clear();
fromRetrofit = response.body();
postAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<NewsPojo> call, Throwable t) {
}
});
}
public void initRecycleView() {
recyclerView = findViewById(R.id.activity_main_recycle_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
postAdapter = new MainAdapter(fromRetrofit, new OnIteamClickListener() {
#Override
public void onItemClick(View itemView) {
}
}, getApplicationContext());
recyclerView.setAdapter(postAdapter);
}
}
Here you can see my Adapter class
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
private NewsPojo newsPojo;
private OnIteamClickListener listener;
private Context mContext;
public MainAdapter(NewsPojo newsPojo, OnIteamClickListener listener, Context mContext) {
this.newsPojo = newsPojo;
this.listener = listener;
this.mContext = mContext;
}
public void clear(){
newsPojo.getArticles().clear();
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_news, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(newsPojo.getArticles().get(position));
}
#Override
public int getItemCount() {
if (newsPojo != null) {
return newsPojo.getArticles().size();
} else {
return 0;
}
}
Why postAdapter.notifyDataSetChanged(); is not working?
I suggest the following:
Change the following lines:
fromRetrofit.getArticles().clear();
fromRetrofit = response.body();
postAdapter.notifyDataSetChanged();
For this:
postAdapter.cleanAddArticles(response.body());
and in the adapter add the following:
public void cleanAddArticles(NewsPojo newsPj){
this.newsPojo.getArticles().clear();
this.newsPojo.getArticles().addAll(newsPj.getArticles());
notifyDataSetChanged();
}
Note: Error depending on the circumstances must be going through object references.
When you get new values by calling response() method, then you must call initRecycleView() to set the new values to the adapter, then use notifyDataSetChanged()
#Override
public void onResponse(Call<NewsPojo> call, Response<NewsPojo> response) {
fromRetrofit.getArticles().clear();
fromRetrofit = response.body();
initRecycleView() //*** Add this.
postAdapter.notifyDataSetChanged();
}
}
first of check when you swipe refresh that time your postAdapter not getting null other wise your code is ok.
if you want to make one separate method for adapter like below..
private void setAdater(){
if (postAdapter==null) {
postAdapter = new MainAdapter(fromRetrofit, new OnIteamClickListener() {
#Override
public void onItemClick(View itemView) {
}
}, getApplicationContext());
recyclerView.setAdapter(postAdapter);
}
else{
postAdapter.notifyDataSetChanged();
}
}
and also check your from fromRetrofit object what value have. i think adapter not getting any value bacause only clear article but object has some value there for i think you make object null when getting data...
fromRetrofit=null;
fromRetrofit = response.body();

how parse JSON and set into in control. ListView or RecyclerView and click on that item can start another activity in android?

how parse JSON and set into in control. ListView or RecyclerView and click on that item can start another activity in android?
http://beta.json-generator.com/api/json/get/VJ9snXcFG
Supose we print all titles in list view using json (beta.json-generator.com/api/json/get/VJ9snXcFG).Next first title will be click open first url in json(beta.json-generator.com/api/json/get/VJ9snXcFG) ,second title will be click open second url on json (beta.json-generator.com/api/json/get/VJ9snXcFG) and so on
To parse JSON use retrofit. Here is a great example: https://square.github.io/retrofit/
To the RecyclerView add an onClicklistener in the onBindViewHolder function and start your activity there.
Example:
Json has data like this:
[{"id":302,"latitude":-23.725,"longitude":34.2773,"place":"Panda Mozambik null"},{"id":312,"latitude":46.7681,"longitude":20.8186,"place":"Kondoros Magyarország null"},{"id":322,"latitude":8,"longitude":3,"place":"rr"}]
Data class:
public class Data {
public int id;
public String place;
public float longitude;
public float latitude;
public Data(){}
}
NetAPI
public interface NetApi {
#GET("/")
Call<List<Data>> getData();
}
in Activity:
private Retrofit retrofit;
private NetApi netApi;
private RecyclerView recyclerView;
ItemAdapter adapter;
public List<Data> items = new ArrayList<Data>();
private static final String ENDPOINT_ADDRESS = "https://endpoint.com/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
retrofit = new Retrofit.Builder().baseUrl(ENDPOINT_ADDRESS).client(new OkHttpClient.Builder().build()).addConverterFactory(GsonConverterFactory.create()).build();
netApi = retrofit.create(NetApi.class);
initRecycleView()
getData();
}
public void getData() {
netApi.getData().enqueue(new Callback<List<Data>>() {
#Override
public void onResponse(Call<List<Data>> call, Response<List<Data>> response) {
if (response.isSuccessful()) {
Log.d(TAG, response.body().toString());
items = new ArrayList<Data>((response.body()));
adapter.update(items);
} else {
Toast.makeText(MainActivity.this, "Error: " + response.message(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<List<Data>> call, Throwable t) {
}
});
}
private void initRecycleView() {
recyclerView = (RecyclerView) view.findViewById(R.id.MainRecyclerView);
adapter = new ItemAdapter();
recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
recyclerView.setAdapter(adapter);
}
ItemAdapter something like this:
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemViewHolder> {
public final List<Data> items;
public ItemAdapter() {
items = new ArrayList<>();
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView =
LayoutInflater.from(parent.getContext()).
inflate(R.layout.item_recyclerview, parent, false);
ItemViewHolder viewHolder = new ItemViewHolder(itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
Data item = items.get(position);
holder.longitude.setText(Float.toString(item.longitude));
holder.latitude.setText(Float.toString(item.latitude));
holder.place.setText(item.place);
holder.place.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(),"Clicked",Toast.LENGTH_LONG).show();
}
});
}
public void addItem(Data item) {
items.add(item);
notifyItemInserted(items.size() - 1);
}
#Override
public int getItemCount() {
return items.size();
}
public void update(List<Data> itemsrec) {
items.clear();
items.addAll(itemsrec);
notifyDataSetChanged();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
TextView place;
TextView longitude;
TextView latitude;
public ItemViewHolder(View itemView) {
super(itemView);
place = (TextView) itemView.findViewById(R.id.place);
longitude = (TextView) itemView.findViewById(R.id.longitude);
latitude = (TextView) itemView.findViewById(R.id.latitude);
}
}
}

Recyclerview not display vediothumbnail

i am working and i want to display a video in recyclerview from server its geting data not displaying video thumbnail its showing only text and displaing error thumbnail i dont know where i am wrong please review my code and tell me where i am wrong ,
myActivity
public class TestingActivity extends AppCompatActivity {
private List<TestingModel> listiIems;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testingactivity);
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView_test);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
listiIems = new ArrayList<>();
//Calling method to get data
getData();
}
//This method will get data from the web api
private void getData() {
String Data_Url="http://www.example.com/vedio.json";
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Loading Data", "Please wait...", false, false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Data_Url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
TestingModel item = new TestingModel();
JSONObject json = null;
try {
json = array.getJSONObject(i);
item.setUrl_image(json.getString("audio"));
item.setTest_name(json.getString("txt"));
} catch (JSONException e) {
e.printStackTrace();
}
listiIems.add(item);
}
//Finally initializing our adapter
adapter = new TestingAdapter(listiIems, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
Model
public class TestingModel {
public String getUrl_image() {
return url_image;
}
public void setUrl_image(String url_image) {
this.url_image = url_image;
}
public String getTest_name() {
return test_name;
}
public void setTest_name(String test_name) {
this.test_name = test_name;
}
private String url_image;
private String test_name;
}
Adapter
public class TestingAdapter extends RecyclerView.Adapter<TestingAdapter.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
String url;
//List of superHeroes
List<TestingModel> listItems;
public TestingAdapter(List<TestingModel> listItems, Context context) {
super();
//Getting all the superheroes
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.testing_list, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
TestingModel items = listItems.get(position);
imageLoader = CustomVolleyRequest1.getInstance(context).getImageLoader();
imageLoader.get(items.getUrl_image(), ImageLoader.getImageListener(holder.imageView, R.drawable.placeholder, android.R.drawable.ic_dialog_alert));
holder.imageView.setImageUrl(items.getUrl_image(), imageLoader);
holder.textViewName.setText(items.getTest_name());
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
url = listItems.get(position).getUrl_image();
Log.e("urlis","==>"+url);
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public NetworkImageView imageView;
public TextView textViewName;
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.testingimage);
textViewName = (TextView) itemView.findViewById(R.id.texting_text);
}
}
}
help me
First of all, Check in adapter. Are you getting url is image or video. If url is contain image then need to check in ImageLoader Library. you can better use with glide and picasso.
Its very easy to use picasso. You can found picasso from this link
http://square.github.io/picasso/
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
If your url contain video then you have to create thumbnail from url using Thumnail Util
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(filePath,
Thumbnails.MINI_KIND); imageview.setBitmapImage(thumb);

Endless Scrolling in RecyclerView: How should I implement this?

I want to code endless scrolling with Adapters & RecyclerViews and I'm fetching my items with Volley from JSON. Though I have read these guides (Codepath and github), I'm finding it difficult to apply it to my own scenario.
The url of my json has these format: https://example.com/json/items?page=1, https://example.com/json/items?page=2, https://example.com/json/items?page=3 etc.
Below are the codes I'm using:
MainActivity
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
private int number = 1;
//Creating a list of videos
private List<VideoItems> mVideoItemsList;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate called");
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.video_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
// This method was copied from codepath (above url)
// Add the scroll listener
recyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(layoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Add whatever code needed to append new items of the list
customLoadMoreDataFromApi(page);
}
});
//Initializing the videolist
mVideoItemsList = new ArrayList<>();
adapter = new VideoAdapter(mVideoItemsList, this);
recyclerView.setAdapter(adapter);
if (NetworkCheck.isAvailableAndConnected(this)) {
//Calling method to get data
getData();
} else {
//Codes for building Alert Dialog
alertDialogBuilder.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(mContext)) {
alertDialogBuilder.show();
} else {
getData();
}
}
});
alertDialogBuilder.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialogBuilder.show();
}
}
public int getNumber() {
return number++;
}
public void setNumber(int number) {
this.number = number;
}
// This method was copied from codepath (above is url)
// Append more data into the adapter
// This method probably sends out a network request and appends new data items to your adapter;
public void customLoadMoreDataFromApi (int offset) {
// Send an API request to retrieve appropriate data using the offset value as a parameter.
// Deserialize API request and then construct new objects to append to the adapter.
// Add the new objects to the data source for adapter
mVideoItemsList.addAll(moreVideos);
// For efficiency purpose, notify the adapter of the only elements inserted that got changed
// curSize will be equal to the index of the first element inserted because the list is 0-indexed
int curSize = adapter.getItemCount();
adapter.notifyItemRangeChanged(curSize, mVideoItemsList.size() - 1);
}
//This method will get data from the web api
private void getData(){
Log.d(TAG, "getData called");
//Codes for Showing progress dialog
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigVideo.GET_URL + getNumber(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
VideoItems videoItem = new VideoItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
videoItem.setVideo_title(jsonObject.getString(ConfigVideo.TAG_VIDEO_TITLE));
videoItem.setVideo_body(jsonObject.getString(ConfigVideo.TAG_VIDEO_BODY));
} catch (JSONException w) {
w.printStackTrace();
}
mVideoItemsList.add(videoItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
if (mProgressDialog != null){
mProgressDialog.dismiss();
Log.d(TAG, "mProgress dialog dismissed");
}
}
}
EndlessRecyclerViewScrollListener
The link to the code is EndlessRecyclerViewScrollListener.
In the one in my project, I have deleted all the codes that concerns GridLayoutManager and StaggeredGridLayoutManager since I won't be needing them.
VideoAdapter
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.ViewHolder>{
private ImageLoader imageLoader;
private Context mContext;
//List of videos
private List<VideoItems> mVideoItems;
public VideoAdapter(List<VideoItems> videoItems, Context context) {
super();
// Getting all videos
this.mVideoItems = videoItems;
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.video_summ, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
VideoItems videoList = mVideoItems.get(position);
holder.videoTitle.setText(videoList.getVideo_title());
holder.videoBody.setText(videoList.getVideo_body());
}
#Override
public int getItemCount(){
//Return the number of items in the data set
return mVideoItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public NetworkImageView videoImage;
public TextView videoTitle, videoBody;
public ViewHolder (View videoView) {
super(videoView);
videoTitle = (TextView) videoView.findViewById(R.id.video_title);
videoBody = (TextView) videoView.findViewById(R.id.video_body);
}
}
}
VideoItems
public class VideoItems {
private String video_title;
private String video_body;
public String getVideo_title() {
return video_title;
}
public void setVideo_title(String video_title) {
this.video_title = video_title;
}
public String getVideo_body() {
return video_body;
}
public void setVideo_body(String video_body) {
this.video_body = video_body;
}
}
I don't know if you could give me tips on how I could implement it to my RecyclerView. Thanks in advance.
You have to implement own listener to the adapter you are binding to recyclerview.
First create a interface like this,
public interface OnLoadMoreListener {
void onLoadMore();
}
In your recyclerview's adapter set this,
adapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
//get your items here based on the pagination count
}
});
Your modified video adapter
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.ViewHolder>{
private ImageLoader imageLoader;
private Context mContext;
//List of videos
private List<VideoItems> mVideoItems;
private int totalItemCount = 0,lastVisibleItem = 0,int visibleThreshold = 5;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
public VideoAdapter(List<VideoItems> videoItems, Context context, RecyclerView recyclerview) {
super();
// Getting all videos
this.mVideoItems = videoItems;
this.mContext = context;
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView
.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView,
int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = layoutManager.getItemCount();
lastVisibleItem = layoutManager.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
public void setLoaded() {
loading = false;
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
#Override
public ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.video_summ, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
VideoItems videoList = mVideoItems.get(position);
holder.videoTitle.setText(videoList.getVideo_title());
holder.videoBody.setText(videoList.getVideo_body());
}
#Override
public int getItemCount(){
//Return the number of items in the data set
return mVideoItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public NetworkImageView videoImage;
public TextView videoTitle, videoBody;
public ViewHolder (View videoView) {
super(videoView);
videoTitle = (TextView) videoView.findViewById(R.id.video_title);
videoBody = (TextView) videoView.findViewById(R.id.video_body);
}
}
}
While initializing the adapter send recyclerview object
adapter = new VideoAdapter(mVideoItemsList, this, recyclerView );
Once you get your next set of items, increment your pagecount, notifyDataSetChanged() and call this
adapter.setLoaded();
Hope this will help you!

Categories

Resources