recyclerview sometimes get data on scroll, sometimes not - android

I have a recyclerview that gets the first 10 items, when I scroll it down sometimes it gets the others, sometimes not:
item 22
item 21
item 20
item 19
item 18
item 17
item 16
item 15
item 14
item 13
usually it stops at item 13. (not getting the onscroll items)
but sometimes it works and get the others (12,11,10,9,8,7,6,5,4,3,2,1...)
my scroll code:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (isLastItemDisplaying(recyclerView)) {
getData();
}
}
});
get data:
private void getData() {
requestQueue.add(getDataFromServer(requestCount, user_id));
}
getdata server
private JsonArrayRequest getDataFromServer(String requestCount, String user_id) {
//Initializing ProgressBar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar1);
//Displaying Progressbar
progressBar.setVisibility(View.VISIBLE);
requestCount = requestCount + "&user=" + user_id;
//JsonArrayRequest of volley
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL + String.valueOf(requestCount),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
parseData(response);
//Hiding the progressbar
progressBar.setVisibility(View.GONE);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
//If an error occurs that means end of the list has reached
Toast.makeText(UserAreaActivity.this, "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
//Returning the request
return jsonArrayRequest;
}
check last item
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
any ideas why it works sometimes and why not?
----------------------------> edit
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
//Imageloader to load image
private ImageLoader imageLoader;
private final Context context;
//List to store all posts
List<Posts> Posts;
//Constructor of this class
public CardAdapter(List<Posts> Post, Context context){
super();
//Getting all
this.Posts = Post;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.posts_list, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Posts post = Posts.get(position);
holder.post = post;
//Loading image from url
//imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
//Showing data on the views
//holder.imageView.setImageUrl(post.getImageUrl(), imageLoader);
Picasso.with(context).load(post.getImageUrl()).into(holder.imageView);
holder.textViewName.setText(post.getName());
holder.textViewPublisher.setText(post.getPublisher());
holder.setIsRecyclable(false);
}
#Override
public int getItemCount() {
return Posts.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
//Views
public ImageView imageView;
public TextView textViewName;
public TextView textViewPublisher;
public Posts post;
public ImageView ProfilePic;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.imageViewHero);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
textViewPublisher = (TextView) itemView.findViewById(R.id.textViewPublisher);
}
#Override
public void onClick(View v) {
//...
}
}
}
}
----------------------------------------- edit 2
private JsonArrayRequest getDataFromServer(String requestCount, String user_id) {
//Initializing ProgressBar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar1);
//Displaying Progressbar
progressBar.setVisibility(View.VISIBLE);
requestCount = requestCount + "&user=" + user_id;
//JsonArrayRequest of volley
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL + String.valueOf(requestCount),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
parseData(response);
//Hiding the progressbar
progressBar.setVisibility(View.GONE);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
//If an error occurs that means end of the list has reached
Toast.makeText(UserAreaActivity.this, "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
//Returning the request
return jsonArrayRequest;
}
//This method will get data from the web api
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
requestQueue.add(getDataFromServer(requestCount, user_id));
//Incrementing the request counter
//requestCount++;
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Creating the object
Posts PostObj = new Posts();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
//Adding data to the object
PostObj.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
PostObj.setName(json.getString(Config.TAG_NAME));
PostObj.setPublisher(json.getString(Config.TAG_PUBLISHER));
requestCount = PostObj.setId(json.getString(Config.TAG_ID));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding object to the list
listPosts.add(PostObj);
}
//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
}

Have you try with ? :
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
// instead of findLastCompletelyVisibleItemPosition
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}

Related

int android.support.v7.widget.GridLayoutManager.getItemCount()' on a null object reference

here getItemCount() not null, but here getlayoutmanager is null. plz help me to solved this. i'm trying to loadmore data when user scroll down recyclerview at end of scrolling load another data so on. This Error occurred in adapter.
here getLayoutManager() is get null:
final GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
My Adapter code:
public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mCtx;
private ImageView link;
private boolean isLoading;
private List<Image> imageList;
private int visibleThreshold = 5;
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private int lastVisibleItem, totalItemCount;
private OnLoadMoreListener onLoadMoreListener;
public ImageAdapter(RecyclerView recyclerView, List<Image> imageList, Context mCtx) {
this.imageList = imageList;
this.mCtx = mCtx;
final GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
Log.d(TAG, "Tj_getItemCount" + getItemCount());
Log.d(TAG, "Tj_linearLayoutManager" + gridLayoutManager);
totalItemCount = gridLayoutManager.getItemCount();
lastVisibleItem = gridLayoutManager.findLastVisibleItemPosition();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.onLoadMoreListener = mOnLoadMoreListener;
}
#Override
public int getItemViewType(int position) {
return imageList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.list_items, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_loading, parent, false);
LoadingViewHolder vh1 = new LoadingViewHolder(view);
return vh1;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof ViewHolder) {
final Image image = imageList.get(position);
final String imgUrl = image.getThumb();
link.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ViewImage.class);
intent.putExtra("URL", imgUrl);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(intent);
}
});
Glide.with(mCtx).load(imgUrl).into(link);
} else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return imageList == null ? 0 : imageList.size();
}
public void setLoaded() {
isLoading = false;
}
private class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
LoadingViewHolder(View view) {
super(view);
progressBar = view.findViewById(R.id.progressBar1);
}
}
class ViewHolder extends RecyclerView.ViewHolder {
ViewHolder(View v) {
super(v);
link = v.findViewById(R.id.link);
}
}
}
My Activity code:
public class MainActivity extends AppCompatActivity {
//the URL having the json data https://api.unsplash.com/search/photos?query=canada&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c
// private static final String JSON_URL = "https://api.unsplash.com/photos/random?count=25&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c";
// private static final String JSON_URL = "https://api.unsplash.com/photos/?client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c";
int i = 2;
Image hero;
String query;
List<Image> imageList;
RecyclerView listView;
private static String JSON_URL;
private static final String TAG = "Tj";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//initializing listview and hero list
listView = findViewById(R.id.listView);
imageList = new ArrayList<>();
Intent intent = getIntent();
query = intent.getStringExtra("category");
JSON_URL = "https://api.unsplash.com/search/photos?query=" + query + "&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c&page=1";
Log.d(TAG, "Query" + JSON_URL);
loadHeroList();
}
private void loadHeroList() {
//getting the progressbar
final ProgressBar progressBar = findViewById(R.id.progressBar);
//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);
//creating a string request to send request to the url
StringRequest jsonArrayRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
// JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
// Request.Method.GET,
// JSON_URL,
// null,
// new Response.Listener<JSONArray>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named hero inside the object
//so here we are getting that json array
JSONArray heroArray = obj.getJSONArray("results");
//now looping through all the elements of the json array
for (int i = 0; i < heroArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject jsonObject = heroArray.getJSONObject(i);
JSONObject jsonObject1 = jsonObject.getJSONObject("urls");
//creating a hero object and giving them the values from json object
hero = new Image(jsonObject.getString("id"),
jsonObject.getString("color"),
jsonObject1.getString("full"));
//adding the hero to herolist
imageList.add(hero);
}
//creating custom adapter object
final ImageAdapter adapter = new ImageAdapter(listView, imageList, getApplicationContext());
listView.setHasFixedSize(true);
// use a grid layout manager
listView.setLayoutManager(new GridLayoutManager(MainActivity.this, 2));
//adding the adapter to listview
listView.setAdapter(adapter);
adapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
if (imageList.size() <= 20) {
imageList.add(null);
adapter.notifyItemInserted(imageList.size() - 1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
imageList.remove(imageList.size() - 1);
adapter.notifyItemRemoved(imageList.size());
JSON_URL = "https://api.unsplash.com/search/photos?query=" + query + "&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c&page=" + i;
Log.d(TAG, "QueryLoadMore" + JSON_URL);
i++;
StringRequest jsonArrayRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named hero inside the object
//so here we are getting that json array
JSONArray heroArray = obj.getJSONArray("results");
//now looping through all the elements of the json array
for (int i = 0; i < heroArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject jsonObject = heroArray.getJSONObject(i);
JSONObject jsonObject1 = jsonObject.getJSONObject("urls");
//creating a hero object and giving them the values from json object
hero = new Image(jsonObject.getString("id"),
jsonObject.getString("color"),
jsonObject1.getString("full"));
//adding the hero to herolist
imageList.add(hero);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
//adding the string request to request queue
requestQueue.add(jsonArrayRequest);
// imageList.add(hero);
// }
adapter.notifyDataSetChanged();
adapter.setLoaded();
}
}, 5000);
} else {
Toast.makeText(MainActivity.this, "Loading data completed", Toast.LENGTH_SHORT).show();
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(jsonArrayRequest);
}
}
You never set any kind of LayoutManager to your listView.
You must set the layout manager before creating your custom adapter object.
You can set it by calling: recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns)); Then you are able to get it later in your ImageAdapter class.

When i scroll my recyclerview, image change it's position continuously and repeating images

Image before scroll - Image After Scroll
I'm trying to develop application like wallpaper app when i select any category then open it and when i scroll this RecyclerView that time load page 2 images from api and so on but when i scroll RecyclerView image change it's position and load duplicate of it. plz help me to solved this.
My Adapter :
public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mCtx;
private ImageView link;
private boolean isLoading;
private List<Image> imageList;
private int visibleThreshold = 4;
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private int lastVisibleItem, totalItemCount;
private OnLoadMoreListener onLoadMoreListener;
public ImageAdapter(RecyclerView recyclerView, List<Image> imageList, Context mCtx) {
this.mCtx = mCtx;
this.imageList = imageList;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager gridLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = gridLayoutManager.getItemCount();
lastVisibleItem = gridLayoutManager.findLastVisibleItemPosition();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
// }
});
}
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.onLoadMoreListener = mOnLoadMoreListener;
}
#Override
public int getItemViewType(int position) {
return imageList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.list_items, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_loading, parent, false);
LoadingViewHolder vh1 = new LoadingViewHolder(view);
return vh1;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof ViewHolder) {
final Image image = imageList.get(position);
final String imgUrl = image.getThumb();
link.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ViewImage.class);
intent.putExtra("URL", imgUrl);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(intent);
}
});
Glide.with(mCtx).load(imgUrl).into(link);
} else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return imageList.size();
}
public void setLoaded() {
isLoading = false;
}
private class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
LoadingViewHolder(View view) {
super(view);
progressBar = view.findViewById(R.id.progressBar1);
}
}
class ViewHolder extends RecyclerView.ViewHolder {
ViewHolder(View v) {
super(v);
link = v.findViewById(R.id.link);
}
}
}
My Activity :
public class MainActivity extends AppCompatActivity {
int i = 1;
String query;
List<Image> imageList;
RecyclerView listView;
ImageAdapter adapter;
private static String JSON_URL;
private static final String TAG = "Tj";
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//initializing listview and hero list
listView = findViewById(R.id.listView);
imageList = new ArrayList<>();
Intent intent = getIntent();
query = intent.getStringExtra("category");
JSON_URL = "https://api.unsplash.com/search/photos?query=" + query +
"&client_id=xxxxx&page=" + i;
Log.d(TAG, "Query " + JSON_URL);
loadHeroList();
}
private void loadHeroList() {
//getting the progressbar
progressBar = findViewById(R.id.progressBar);
//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);
//creating a string request to send request to the url
StringRequest jsonArrayRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named hero inside the object
//so here we are getting that json array
JSONArray heroArray = obj.getJSONArray("results");
//now looping through all the elements of the json array
for (int i = 0; i < heroArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject jsonObject = heroArray.getJSONObject(i);
JSONObject jsonObject1 = jsonObject.getJSONObject("urls");
//creating a hero object and giving them the values from json object
Image hero = new Image(jsonObject.getString("id"),
jsonObject.getString("color"),
jsonObject1.getString("full"));
//adding the hero to herolist
imageList.add(hero);
listView.setHasFixedSize(true);
// use a grid layout manager
listView.setLayoutManager(new GridLayoutManager(MainActivity.this, 2));
}
//creating custom adapter object
adapter = new ImageAdapter(listView, imageList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
//Load More Pages Start Here
adapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
loadMoreData();
}
});
//Complete for Load More Pages
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(jsonArrayRequest);
}
private void loadMoreData() {
imageList.add(null);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
adapter.notifyItemInserted(imageList.size() - 1);
imageList.remove(imageList.size() - 1);
adapter.notifyItemRemoved(imageList.size());
i++;
Log.d(TAG, "ILoadMore " + i);
String JSON_URL_LoadMore = "https://api.unsplash.com/search/photos?query=" + query + "&client_id=xxxxx&page=" + i;
Log.d(TAG, "QueryLoadMore " + JSON_URL_LoadMore);
StringRequest jsonArrayRequestLoadMore = new StringRequest(Request.Method.GET, JSON_URL_LoadMore,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named hero inside the object
//so here we are getting that json array
JSONArray heroArray = obj.getJSONArray("results");
//now looping through all the elements of the json array
for (int i = 0; i < heroArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject jsonObject = heroArray.getJSONObject(i);
JSONObject jsonObject1 = jsonObject.getJSONObject("urls");
//creating a hero object and giving them the values from json object
Image hero = new Image(jsonObject.getString("id"),
jsonObject.getString("color"),
jsonObject1.getString("full"));
//adding the hero to herolist
imageList.add(hero);
adapter.notifyItemInserted(imageList.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
//adding the string request to request queue
requestQueue.add(jsonArrayRequestLoadMore);
adapter.notifyDataSetChanged();
adapter.setLoaded();
}
}, 5000);
}
}
Override
#Override
public long getItemId(int position) {
return position;
}
And use
Picasso.with(context)
.load(getImgUrl)
.placeholder(R.drawable.user_placeholder)
.fit()
.into(imageView);
Or else
To retain and restore recyclerview position on scrolling, please try below link.
https://panavtec.me/retain-restore-recycler-view-scroll-position

How to make recyclerview with two view and progress bar at bottom?

I have an app in which condition is something like that i have to show server data with google add at random number with progress bar at bottom when user scroll up I want to show progress bar at bottom of recyclerview which will send server request for more data to set viewType I declare int type variable namely viewType and setting view type in activity. but it does not work. Please help
code of model:-
private String email;
private String phone;
public int getViewType() {
return viewType;
}
public void setViewType(int viewType) {
this.viewType = viewType;
}
private int viewType;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
activity code:-
private List<Contact> contacts;
Contact contact;
private ContactAdapter contactAdapter;
private Random random;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contacts = new ArrayList<>();
random = new Random();
sendRequesttoServerForDeals();
//find view by id and attaching adapter for the RecyclerView
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
contactAdapter = new ContactAdapter(recyclerView, contacts, getApplicationContext());
//set load more listener for the RecyclerView adapter
contactAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
contacts.add(null);
contactAdapter.notifyItemInserted(contacts.size() - 1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
contacts.remove(contacts.size() - 1);
contactAdapter.notifyItemRemoved(contacts.size());
sendRequesttoServerForMoreDeals();
}
}, 3000);
}
});
}
/**
* Method is called to send server request for manual deals.
*/
public void sendRequesttoServerForDeals() {
JSONObject jsonObject = new JSONObject();
String dealListUrl = "http://156.222.16.1156:8985/ireward/rest/json/metallica";
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, dealListUrl.trim(), jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("MainActivity", "Server success response::" + response);
String resultCode = "resultcode";
try {
int nResultCodeFromServer = Integer.parseInt(response.getString(resultCode.trim()));
if (nResultCodeFromServer == ConstantInt.TRANSACTION_SUCCESS) {
JSONArray getJsonArray = response.optJSONArray(CResponseKey.DEAL_ARRAY.trim());
contacts.clear();
for (int i = 0; i < getJsonArray.length(); i++) {
try {
JSONObject getJsonObj = getJsonArray.getJSONObject(i);
contact = new Contact();
contact.setEmail(getJsonObj.getString(CResponseKey.DEAL_NAME.trim()));
contact.setPhone(getJsonObj.getString(CResponseKey.DEAL_DETAIL.trim()));
contact.setViewType(0);
contacts.add(contact);
} catch (Exception e) {
e.printStackTrace();
}
}
int arrayCount = getJsonArray.length();
Log.e("Mainactivity", "ArrayCount::" + arrayCount);
Contact contact = new Contact();
contact.setViewType(1);
contacts.add(arrayCount,contact);
Contact contact1 = new Contact();
contact.setViewType(2);
contacts.add(3,contact);
recyclerView.setAdapter(contactAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("MainActivity", "Server error response::" + error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
jsonRequest.setRetryPolicy(new DefaultRetryPolicy(ConstantInt.INITIAL_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonRequest);
}
/**
* Method is called to send server request for manual deals.
*/
public void sendRequesttoServerForMoreDeals() {
JSONObject jsonObject = new JSONObject();
String dealListUrl = "http://156.222.16.1156:8985/ireward/rest/json/metallica";
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, dealListUrl.trim(), jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("MainActivity", "Server success response::" + response);
String resultCode = "resultcode";
try {
int nResultCodeFromServer = Integer.parseInt(response.getString(resultCode.trim()));
if (nResultCodeFromServer == ConstantInt.TRANSACTION_SUCCESS) {
JSONArray getJsonArray = response.optJSONArray(CResponseKey.DEAL_ARRAY.trim());
for (int i = 0; i < getJsonArray.length(); i++) {
try {
JSONObject getJsonObj = getJsonArray.getJSONObject(i);
contact = new Contact();
contact.setEmail(getJsonObj.getString(CResponseKey.DEAL_NAME.trim()));
contact.setPhone(getJsonObj.getString(CResponseKey.DEAL_DETAIL.trim()));
contact.setViewType(0);
contacts.add(contact);
} catch (Exception e) {
e.printStackTrace();
}
}
contactAdapter.notifyDataSetChanged();
contactAdapter.setLoaded();
int arrayCount = getJsonArray.length();
Log.e("Mainactivity", "ArrayCount::" + arrayCount);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("MainActivity", "Server error response::" + error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
jsonRequest.setRetryPolicy(new DefaultRetryPolicy(ConstantInt.INITIAL_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonRequest);
}
code of adapter
private OnLoadMoreListener onLoadMoreListener;
private boolean isLoading;
private Context activity;
private List<Contact> contacts;
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
public ContactAdapter(RecyclerView recyclerView, List<Contact> contacts, Context activity) {
this.contacts = contacts;
this.activity = activity;
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.onLoadMoreListener = mOnLoadMoreListener;
}
#Override
public int getItemViewType(int position) {
return contacts.get(position).getViewType();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case 0:
View v = inflater.inflate(R.layout.item_recycler_view_row, parent, false);
viewHolder = new UserViewHolder(v);
break;
case 1:
View v1 = inflater.inflate(R.layout.item_loading, parent, false);
viewHolder = new LoadingViewHolder(v1);
break;
case 2:
View view = inflater.inflate(R.layout.add, parent, false);
viewHolder = new AdView(view);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()){
case 0:
Contact contact = contacts.get(position);
UserViewHolder userViewHolder = (UserViewHolder) holder;
userViewHolder.phone.setText(contact.getEmail());
userViewHolder.email.setText(contact.getPhone());
break;
case 1:
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
break;
case 2 :
AdView adView = (AdView) holder;
adView.textView.setText("Ad");
break;
}
}
#Override
public int getItemCount() {
return contacts.size();
}
public void setLoaded() {
isLoading = false;
}
private class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public LoadingViewHolder(View view) {
super(view);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
}
}
private class UserViewHolder extends RecyclerView.ViewHolder {
public TextView phone;
public TextView email;
public UserViewHolder(View view) {
super(view);
phone = (TextView) view.findViewById(R.id.txt_phone);
email = (TextView) view.findViewById(R.id.txt_email);
}
}
private class AdView extends RecyclerView.ViewHolder {
TextView textView;
public AdView(View view) {
super(view);
textView = (TextView) view.findViewById(R.id.text);
}
}

How to fetch data from json in android and display in RecyclerView?

I am making an android app to fetch JSON data from URL and then showing it in a RecyclerView.
My JSON data
[{"email":"abc#gmail.com","photo":"http:\/\/www.example.com\/x.jpg","bookname":"one","price":"30","num":"3","avg":"3.9","author":"none"}]
but only bookname and photo keys values are fetching. Other parameters are empty but my code is correct because if it is wrong than even bookname shouldn't fetch.
My code is:
public class dashBoard extends AppCompatActivity {
private List<myDash> dash;
private Toolbar mToolbar;
Button read;
//Creating Views
int temp=0;
float starts=0;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public String ratenumS,numberS;
public String bookName,price,rating;
private RequestQueue requestQueue;
String mail_one;
private int requestCount = 1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dash_bord);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing our superheroes list
dash = new ArrayList<>();
requestQueue = Volley.newRequestQueue(this);
getDash();
//Adding an scroll change listener to recyclerview
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
getDash();
}
});
//initializing our adapter
adapter = new dashCard(dash, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
private JsonArrayRequest getDataFromDash(int requestCount) {
//Initializing ProgressBar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar3);
//Displaying Progressbar
progressBar.setVisibility(View.VISIBLE);
setProgressBarIndeterminateVisibility(true);
SharedPreferences pre = PreferenceManager.getDefaultSharedPreferences(dashBoard.this);
mail_one = pre.getString("mail2", "DEFAULT VALUE");
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest("http://www.example.com/getDash.php?page="+ String.valueOf(requestCount )+"&email="+mail_one,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
parseData(response);
//Hiding the progressbar
progressBar.setVisibility(View.GONE);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
if(temp==0) {
Toast.makeText(dashBoard.this, "No More Items Available "+bookName+"book "+price+" "+ratenumS+" "+numberS+" "+mail_one, Toast.LENGTH_SHORT).show();
temp++;
}
}
}
//Returning the request
return jsonArrayRequest;
}
private void getDash() {
//Adding the method to the queue by calling the method getDataFromServer
requestQueue.add(getDataFromDash(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
myDash dash1 = new myDash();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
dash1.setImageUrl(json.getString("photo"));
dash1.setBook_name(json.getString("bookname"));
dash1.setNo_down(json.getString("download"));
dash1.setBook_price(json.getString("price"));
dash1.setStar_num(json.getString("num"));
dash1.setAvg_rate(Float.parseFloat(json.getString("avg")));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the superhero object to the list
dash.add(dash1);
}
//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
}
Does anybody have any idea why this code is not working?
My dashCard Activity.
public class dashCard extends RecyclerView.Adapter<dashCard.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
//List to store all superheroes
List<myDash> secDash1;
//Constructor of this class
public dashCard(List<myDash> secDash1, Context context){
super();
//Getting all superheroes
this.secDash1 = secDash1;
this.context = context;
}
//In
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.dash_bord, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final myDash secDash = secDash1.get(position);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(secDash.getImageUrl(),ImageLoader.getImageListener(holder.imageView, R.drawable.image, android.R.drawable.ic_dialog_alert));
holder.imageView.setImageUrl(secDash.getImageUrl(), imageLoader);
holder.bookName.setText(secDash.getBook_name());
holder.price.setText(secDash.getBook_price());
holder.numberD.setText(secDash.getStar_num());
//holder.rate.setText(Float.toString(secDash.getAvg_rate()));
holder.download.setText(secDash.getNo_down());
// holder.star.setRating(secDash.getAvg_rate());
}
public int getItemCount() {
return secDash1.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
//Views
public NetworkImageView imageView;
public TextView bookName;
public TextView price;
public TextView numberD;
public TextView rate;
RatingBar star;
public TextView download;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.dashImage);
bookName = (TextView) itemView.findViewById(R.id.bookName4);
price = (TextView) itemView.findViewById(R.id.priceDash);
numberD = (TextView) itemView.findViewById(R.id.numberDash);
rate = (TextView) itemView.findViewById(R.id.ratenumDash);
star = (RatingBar) itemView.findViewById(R.id.rateDash);
download = (TextView) itemView.findViewById(R.id.download);
}
}
}
I think problem at:
dash1.setNo_down(json.getString("download"));
Your json has not download key for get value. When code run over this line, an exception has occurred and program go to catch block, other properties will never be assigned data.
I recommend that check json key are exist before get its value.
You dont have "download" as key in json because of that an exception is thrown which causes other keys to not assigned

Set last position when scroll load more recycleview

I am trying to implement load more recycleview It's working fine but when scroll recycleview at that time always first item is top of the view, I want next scrollable item at the top, How can I solve this problem, Please help me
MainActivity.java
public class MainActivity extends AppCompatActivity {
private int page_no = 0;
private RecyclerView mRecyclerView;
private ArrayList<NotificationBean> mUsers = new ArrayList<>();
private UserAdapter mUserAdapter;
private NotificationBean mNotificationBean;
private int loadMoreArrayListSize;
public int arrayListSize;
// private LinearLayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsers = new ArrayList<>();
mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
// mLayoutManager = new LinearLayoutManager(this);
// mRecyclerView.setLayoutManager(mLayoutManager);
getData(MainActivity.this, page_no, "4");
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUserAdapter = new UserAdapter();
mUserAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
Log.e("haint", "Load More");
mUsers.add(null);
mUserAdapter.notifyItemInserted(mUsers.size() - 1);
//Load more data for reyclerview
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Log.e("haint", "Load More 2");
//Remove loading item
mUsers.remove(mUsers.size() - 1);
mUserAdapter.notifyItemRemoved(mUsers.size());
//Load data
page_no++;
//callAPI(1);
// Log.d("arrTemp Position: : ", String.valueOf(arrTemp));
getData(MainActivity.this, page_no, "4");
// mLayoutManager.scrollToPositionWithOffset(mUsers.size() - 10, 0);
Log.v("LoadMoreListener arsize", Integer.toString(mUsers.size()));
loadMoreArrayListSize = arrayListSize - mUsers.size();
Log.v("loadMoreArrayListSize", Integer.toString(loadMoreArrayListSize));
}
}, 5000);
}
});
}
static class UserViewHolder extends RecyclerView.ViewHolder {
public ImageView imgView;
public TextView txtComment, txtParamLink, txtTitle, txtVideoId;
public UserViewHolder(View itemView) {
super(itemView);
txtComment = (TextView) itemView.findViewById(R.id.txtComment);
txtParamLink = (TextView) itemView.findViewById(R.id.txtParamLink);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
txtVideoId = (TextView) itemView.findViewById(R.id.txtVideoId);
imgView = (ImageView) itemView.findViewById(R.id.imgView);
}
}
static class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public LoadingViewHolder(View itemView) {
super(itemView);
progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
}
}
class UserAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private OnLoadMoreListener mOnLoadMoreListener;
private boolean isLoading;
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
public UserAdapter() {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (mOnLoadMoreListener != null) {
mOnLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.mOnLoadMoreListener = mOnLoadMoreListener;
}
#Override
public int getItemViewType(int position) {
return mUsers.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.notification_item, parent, false);
return new UserViewHolder(view);
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_loading_item, parent, false);
return new LoadingViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof UserViewHolder) {
NotificationBean user = mUsers.get(position);
UserViewHolder userViewHolder = (UserViewHolder) holder;
// userViewHolder.tvName.setText(user.getName());
// userViewHolder.tvEmailId.setText(user.getEmail());
userViewHolder.txtComment.setText(Integer.toString(user.getComment()));
userViewHolder.txtParamLink.setText(user.getPermalink());
userViewHolder.txtTitle.setText(user.getTitle());
userViewHolder.txtVideoId.setText(user.getVideoid());
if (user.getImage() != null) {
Glide.with(MainActivity.this).load(user.getImage()).placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher).dontAnimate().into(userViewHolder.imgView);
}
} else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return mUsers == null ? 0 : mUsers.size();
}
public void setLoaded() {
isLoading = false;
}
}
private void getData(Context context, final int posts_per_page, final String type) {
// final ProgressDialog pDialog = new ProgressDialog(this);
// pDialog.setMessage("Loading...");
// pDialog.show();
RequestQueue queue = Volley.newRequestQueue(context);
// StringRequest sr = new StringRequest(Request.Method.POST, "http://asiatube.info/sgtube/api/ws.php", new Response.Listener<String>() {
StringRequest sr = new StringRequest(Request.Method.POST, "http://steanrewards.com/api/ws.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray jArray;
JSONArray jsonArray = null;
JSONObject jsonObject = null;
try {
jArray = new JSONArray(response);
JSONObject jObj = jArray.getJSONObject(0);
int code = jObj.getInt("code");
if (code == 0) {
Log.d("allcount:: :: ::", String.valueOf(jObj.optInt("allcount")));
if (jObj.has("result")) {
jsonArray = jObj.getJSONArray("result");
Log.d("EVENTLIST ARRAY=", jsonArray.length() + "");
if (jsonArray != null && jsonArray.length() > 0) {
// arrTemp = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
mNotificationBean = new NotificationBean();
mNotificationBean.id = jsonObject.getString("id");
mNotificationBean.permalink = jsonObject.getString("permalink");
mNotificationBean.image = jsonObject.getString("image");
mNotificationBean.title = jsonObject.getString("title");
mNotificationBean.videotype = jsonObject.getString("videotype");
mNotificationBean.videoid = jsonObject.getString("videoid");
mNotificationBean.desc = jsonObject.getString("desc");
mNotificationBean.author_url = jsonObject.getString("author_url");
mNotificationBean.like = jsonObject.getString("like");
mNotificationBean.unlike = jsonObject.getString("unlike");
mNotificationBean.comment = jsonObject.getInt("comment");
//arrTemp.add(mNotificationBean);
mUsers.add(mNotificationBean);
Log.v("ArrayList Size:: :: ", Integer.toString(mUsers.size()));
mRecyclerView.setAdapter(mUserAdapter);
mUserAdapter.notifyDataSetChanged();
mUserAdapter.setLoaded();
}
Log.v("mUsers Size:: :: ", Integer.toString(mUsers.size()));
arrayListSize = mUsers.size();
}
//mAdapter.notifyDataSetChanged();
// mAdapter = new NotificationAdapter(mArrayList);
// pDialog.dismiss();
}
} else {
// pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Check internet connection", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("posts_per_page", Integer.toString(posts_per_page));
params.put("type", type);
// params.put("fromsite", fromsite);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
sr.setRetryPolicy(new DefaultRetryPolicy(
15000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(sr);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp" />
</LinearLayout>
When you are loading you must be knowing the position of top element of new loaded items. just call:
recyclerView.scrollToPosition(position);
And you can use it whenever you want to show specific item on current view, just call this function with their list position. For example you are loading new item after every 80 items so, position of newly loaded item will be 80 so you can call:
recyclerView.scrollToPosition(80);
Just keep on updating this position as you load more and more items.
although,recyclerView.scrollToPosition(position); is a quick fix i would suggest you don't use it, genrally this happens when you do setAdapter() again after the pagination, you need to call notifyDataSetChanged after the new data is got

Categories

Resources