I have fragments with RecyclerView in my activity, But whenever I start the fragment, the RecyclerView is already scrolled to the bottom. To load more item, user have to scroll a little bit upwards and then scroll back to the bottom, And when more items load, RecyclerView is again scrolled to the new bottom.
Here is the code in fragment.
public class FavouriteFragment extends Fragment{
public RecyclerView recyclerView ;
public RecyclerView.Adapter adapter ;
public LinearLayoutManager layoutManager ;
int pastVisiblesItems, visibleItemCount, totalItemCount;
Constants constants;
ArrayList<CardSetterGetter> arrayList;
private List<CardSetterGetter> imagelist;
int start ;
public int end ;
boolean loading = true ;
int totalcount ;
ArrayList<String> imageNameArray ;
String androidId;
String categoryName ;
String cateGoryFlag = "false";
String url;
String tagname = "";
ArrayList<String> title ;
ProgressBar progressBar ;
TextView errormsg ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//to hide search
setHasOptionsMenu(true);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.search);
item.setVisible(false);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.favourite_fragment,container,false);
arrayList = new ArrayList<CardSetterGetter>();
imageNameArray = new ArrayList<String>();
start = 0;
end = start + 2 ;
imagelist = new ArrayList<CardSetterGetter>();
recyclerView = (RecyclerView)view.findViewById(R.id.recyclerview);
progressBar = (ProgressBar)view.findViewById(R.id.progressBar);
errormsg = (TextView) view.findViewById(R.id.error);
getdata();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if(dy > 0)
{
visibleItemCount = layoutManager.getChildCount();
totalItemCount = layoutManager.getItemCount();
pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();
int i = visibleItemCount + pastVisiblesItems ;
System.out.println(i);
System.out.println(totalItemCount);
if(loading) {
if (i == totalItemCount) {
loading = false ;
start = arrayList.size() ;
end = arrayList.size() + 2 ;
requestWithSomeHttpHeaders2(start,end);
new Handler().postDelayed(new Runnable() { // This thread runs in the UI
#Override
public void run() {
loading = true;
}
},2000);
}
}
}
}
});
requestWithSomeHttpHeaders2(start, end);
return view ;
}
public void requestWithSomeHttpHeaders2(int s , int e) {
RequestQueue queue = Volley.newRequestQueue(getActivity());
url = "my url";
StringRequest postRequest = new StringRequest(Request.Method.GET, url ,
new Response.Listener<String> ()
{
#Override
public void onResponse(String response) {
try {
progressBar.setVisibility(View.GONE);
JSONObject jsonObject = new JSONObject(response);
JSONArray payload = jsonObject.getJSONArray("Payload");
JSONObject MetaData = jsonObject.getJSONObject("MetaData");
System.out.println(response);
totalcount = MetaData.getInt("TotalCount");
System.out.println("200" + " " + totalcount);
System.out.println("payload length"+payload.length());
int i ;
for(i =0 ; i < payload.length() ; i++)
{
System.out.println(payload.getJSONObject(i).getString("image_title"));
System.out.println(payload.getJSONObject(i).getString("image_title"));
System.out.println(payload.getJSONObject(i).getString("image_file"));
System.out.println(payload.getJSONObject(i).getString("image_description"));
System.out.println(payload.getJSONObject(i).getString("image_category"));
System.out.println(payload.getJSONObject(i).getString("image_tags"));
System.out.println(payload.getJSONObject(i).getString("id"));
System.out.println(payload.getJSONObject(i).getString("favourite"));
String newString = payload.getJSONObject(i).getString("image_file").replace("original_image", "thumbnail");
CardSetterGetter all = new CardSetterGetter(payload.getJSONObject(i).getString("image_file"),
payload.getJSONObject(i).getString("image_title"),
payload.getJSONObject(i).getString("image_description"),
payload.getJSONObject(i).getString("image_category"),
payload.getJSONObject(i).getString("image_tags"),
payload.getJSONObject(i).getString("id"),
payload.getJSONObject(i).getString("favourite"));
System.out.println("i value is " + i);
arrayList.add(all);
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
adapter = new RecyclerViewAdapter(getActivity(),arrayList,imageNameArray,totalItemCount);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
//adapter.notifyItemInserted(arrayList.size() - 1);
if (end >= totalcount)
{
int index = totalcount -1 ;
recyclerView.scrollToPosition(index);
}
else {
recyclerView.scrollToPosition(end);
}
}
};
handler.post(r);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("error" + e);
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("ERROR","error => "+error.toString());
// definitions.setText("check your internet connection");
NetworkResponse networkResponse = error.networkResponse;
// Log.e("Volley", "Error. HTTP Status Code:"+networkResponse.statusCode);
if (networkResponse != null) {
Log.e("Volley", "Error. HTTP Status Code:"+networkResponse.statusCode);
}
if (error instanceof TimeoutError) {
Log.e("Volley", "TimeoutError");
}else if(error instanceof NoConnectionError){
Log.e("Volley", "NoConnectionError");
} else if (error instanceof AuthFailureError) {
Log.e("Volley", "AuthFailureError");
} else if (error instanceof ServerError) {
Log.e("Volley", "ServerError");
} else if (error instanceof NetworkError) {
Log.e("Volley", "NetworkError");
} else if (error instanceof ParseError) {
Log.e("Volley", "ParseError");
}
}
}
);
queue.add(postRequest);
}
public void getdata(){
try {
SharedPreferences sharedPref = getActivity().getSharedPreferences("mobileId" , Context.MODE_PRIVATE);
androidId = sharedPref.getString("mobileId" , "");
sharedPref = getActivity().getSharedPreferences("categoryInfo" , Context.MODE_PRIVATE);
categoryName = sharedPref.getString("categoryName" , "");
cateGoryFlag = sharedPref.getString("categoryFlag" , "");
tagname = sharedPref.getString("tagname" , "");
}catch (Exception e){
}
}
}
I tried removing if else part of the code, but that made the recyclerView scroll to the top whenever user reach the bottom of the recyclerView.
Please tell me if you need more of the code or code of RecyclerViewAdapter.
I fixed a similar problem by providing the correct orientation to the layout manager. I would change your code to something like:
public RecyclerView.Adapter adapter ;
adapter = new RecyclerViewAdapter(getActivity(),arrayList,imageNameArray,totalItemCount);
recyclerView.setHasFixedSize(true);
//This line should do the trick:
//first parameter is the context
//second parameter is the orientation
//third parameter is used for reverse layout (if you need to show items from last to first)
layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
//probably better to use notifyDataSetChanged to let the adapter know you just initialized it (instead of notifying a single element)
adapter.notifyDataSetChanged();
Not sure why you provide the total item count to the adapter as well, but that's outside the scope of the question and surely doesn't give any problems.
EDIT:
Now that you posted the whole fragment code, I am seeing at least a couple problems:
- the RecyclerView initialization should not be in a runnable, but in the onCreateView or some starting function. You just need to set the manager and the adapter once.
- You provide imageNameArray to your adapter, but where are you inserting new items into it? If you want your RecyclerView to scroll down to the last inserted item, you first need to add an item to the ArrayList, then notify the insertion at that position, something like this:
int position = imageNameAray.size();
imageNameArray.add(item);
adapter.notifyItemInserted(position); //this makes the view update the item in that position, making the recycler to scroll there
Related
I am using Laravel API with paginated data in Android...
I want to get auto paginated data.
e.g. data on first page load first and when I scroll down, next pages load continously!
You can use laravel default pagination method instate of get rows.
For example i want show users list:
//instate of :
$users = User::get();
//Use :
$users = User::paginate();
more info at : laravel site
https://laravel.com/docs/5.5/pagination
You can do so easily using the LengthAwarePaginator
protected function paginate(Collection $collection)
{
$rules = [
'per_page' => 'integer|min:2|max:50',
];
Validator::validate(request()->all(), $rules);
$page = LengthAwarePaginator::resolveCurrentPage();
$perPage = 15;
if (request()->has('per_page')) {
$perPage = (int) request()->per_page;
}
$results = $collection->slice(($page - 1) * $perPage, $perPage)->values();
$paginated = new LengthAwarePaginator($results, $collection->count(), $perPage, $page, [
'path' => LengthAwarePaginator::resolveCurrentPath(),
]);
$paginated->appends(request()->all());
return $paginated;
}
Make sure you import all the namespaces needed,
You can go ahead and paginate the collection thus
$collection = $this->paginate($collection);
Hope this helps
On Laravel Side
// Get Collection
$query = SomeModel::where('some_thing', "5")
->paginate(10);
return Response::json(array(
'some_result' => $query,
));
On Android Side (Retrofit Call)
#FormUrlEncoded
#POST
Call<JsonObject> getActions(
#Url String url);
On Android Side (Activity/Fragment)
public class NewTemplateActivity
extends AppCompatActivity {
// Recycler View
private SomeActionListAdapter someActionsAdapter;
private List<SomesomeActionListModel> listSomeActionModel;
private RecyclerView rv;
private Boolean isScrolling = false;
private int currentItems, totalItems, scrollOutItems;
private int pageNumber = 1;
private Boolean firstLoad = true;
private Boolean firstSearch = false;
private LinearLayoutManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
// Init Recycler View
rv = findViewById(R.id.f_list_rv_list);
rv.setHasFixedSize(true);
listSomeActionModel = new ArrayList<>();
someActionsAdapter = new SomeActionListAdapter(
mContext,
listSomeActionModel);
manager = new LinearLayoutManager(mContext);
rv.setLayoutManager(manager);
rv.setAdapter(someActionsAdapter);
}
private void getSomeAction(
String url) {
if (firstLoad || firstSearch) {
listSomeActionModel.clear();
}
// Retrofit Call
Call<JsonObject> call = RetrofitClientLaravel.getInstance(mContext)
.discussGetApi()
.getSomeAction(url);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(
Call<JsonObject> call,
Response<JsonObject> response) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(new Gson().toJson(response.body()));
// Get The Relevant Array
JSONObject jsonObject2 = jsonObject.getJSONObject("some_result");
JSONArray returnArray = jsonObject2.getJSONArray("data");
onScrolled();
if (!returnArray.isNull(0)) {
for (int l = 0; l < returnArray.length(); l++) {
if (returnArray.length() > 0) {
// Get The Json Object
JSONObject returnJSONObject = returnArray.getJSONObject(l);
// Get Details
String id = returnJSONObject.optString("SomesomeAction_id");
// Populate The Array List
listSomeActionModel.add(new SomesomeActionListModel(id));
}
}
}
if (firstLoad || firstSearch) {
someActionsAdapter = new SomeActionListAdapter(
mContext,
listSomeActionModel);
rv.setAdapter(someActionsAdapter);
}
someActionsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(
Call<JsonObject> call,
Throwable t) {
}
});
}
public void onScrolled() {
rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(
RecyclerView recyclerView,
int newState) {
super.onScrollStateChanged(
recyclerView,
newState);
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isScrolling = true;
}
}
#Override
public void onScrolled(
RecyclerView recyclerView,
int dx,
int dy) {
super.onScrolled(
recyclerView,
dx,
dy);
currentItems = manager.getChildCount();
totalItems = manager.getItemCount();
scrollOutItems = manager.findFirstVisibleItemPosition();
if (isScrolling && (currentItems + scrollOutItems == totalItems)) {
isScrolling = false;
firstLoad = false;
firstSearch = false;
Toast.makeText(
mContext,
"Loading More...",
Toast.LENGTH_SHORT)
.show();
pageNumber++;
getSomeAction(Env.LARAVEL_MAIN_URL +
"/api/get_SomesomeActions" +
"?page=" +
pageNumber);
}
}
});
}
}
I am trying to implement pagination in recyclerview to load more chat messages when the user scrolls to top , this is achieved by sending the last message time i.e coversations[0] time to the API , but when the new list is added the old List gets repeated many times . I think this is because i am not updating the time properly , What is the correct way to achieve this?
This is the code i am using, first time i am setting the flag to false and time as empty.
getConvoData(k, " ", "", false);
private String last_msg_time = " ";
private Boolean flag = false;
rv_convo.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (!recyclerView.canScrollVertically(-1)) {
if (conversations != null) {
String time = last_msg_time;
getConvoData(k, " ", time, true);
}
}
}
});
this is the method for fetching conversation Data
private void getConvoData(final String k, final String new_message, final String last_time, final boolean flag) {
final String token1 = Global.shared().tb_token;
final String url = "https://app.aer.media/v2/message_router/_getChat";
final JSONObject jsonBody = new JSONObject();
final ProgressDialog progressDialog = new ProgressDialog(this);
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
final JSONObject data = jObj.getJSONObject("data");
conversations = data.getJSONArray("conversation");
JSONObject for_chat = data.getJSONObject("for_chat");
JSONArray jsonArr_chat = new JSONArray();
jsonArr_chat.put(for_chat);
params = (RelativeLayout.LayoutParams) rv_convo.getLayoutParams();
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
if (!flag) {
convobeans = gson.fromJson(conversations.toString(), convType);
last_msg_time = conversations.getJSONObject(0).getString("time");
Log.d("OldList", convobeans.toString());
adapter = new ChatDetailsAdapter(forChatBeen, convobeans, ChatDetailsActivity.this, forChatBeansList, image, name, initials, new_message, bitmap);
// Collections.reverse(convobeans);
rv_convo.setAdapter(adapter);
rv_convo.smoothScrollToPosition( rv_convo.getAdapter().getItemCount() - 1);
adapter.notifyDataSetChanged();
rv_convo.setNestedScrollingEnabled(true);
} else {
newConvo = gson.fromJson(conversations.toString(), convType);
last_msg_time = conversations.getJSONObject(0).getString("time");
if (newConvo != null && newConvo.size() > 0) {
Log.d("newList", newConvo.toString());
convobeans.addAll(0, newConvo);
adapter.notifyItemChanged(0, newConvo.size());
}
}
}
}
}
Depending on the flag I am updating the list and updating the time as well but the list gets repeated in the RecyclerView due to the previous time being passed , how do I update the time optimally and fetch the new list each time?
This code is used to fetch the data when the user scroll down in a recylerview. Just analyze this code you will get the basic idea.
rvCategory.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy > 0) {
visibleItemCount = mLinearLayoutManager.getChildCount();
totalItemCount = mLinearLayoutManager.getItemCount();
pastVisiblesItems = mLinearLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
loading = false;
fetchData();
}
}
}
}
});
Function FetchData()
private void fetchData() {
String url = EndPoints.location + "getMobileData.php?lastData=" + lastData;
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
lastData = response.getString("last");
JSONArray jArray = response.getJSONArray("response");
if (jArray.length() == 0) {
//Empty condition
} else {
for (int i = 0; i < jArray.length(); i++) {
//Append the chat with the Dataobject of your modelAnd swap the recylerview view with new data
//Example
}
adapter.swap(rvHomeModel.createHomeList(DataPathsHome, true));
}
} catch (JSONException e) {
e.printStackTrace();
}
loading = true;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
loading = true;
Toast.makeText(CategoryView.this, "No internet connection", Toast.LENGTH_LONG).show();
}
});
// Add a request (in this example, called stringRequest) to your RequestQueue.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
}
Create a function called swap in your adapter class that accept the new dataset
public void swap(List<rvHomeModel> list) {
//Check your previouse dataset used in adapter is empty or not
if (rvHomeModels!= null) {
rvHomeModels.clear();
rvHomeModels.addAll(list);
} else {
rvHomeModels = list;
}
notifyDataSetChanged();
}
At server
1. Get the previous value
2. Do the database operation and get the chats id < of previous
2. Create a JSON Object contain
{
last:last_chat_id,
response:{
//Your chat
}
}
This is not a perfect solution for this question. But you will get the basic idea about what you are looking for.
I have a problem with the endless scroll. Every time it loads more data, it returns to the top view. What I want is the RecyclerView to stay in the last position when it loads new data.
I am trying to implement this code https://github.com/codepath/android_guides/wiki/Endless-Scrolling-with-AdapterViews-and-RecyclerView
here is the endless scroll code
public abstract class EndlessRecyclerViewScrollListener extends RecyclerView.OnScrollListener{
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 30;
// The current offset index of data you have loaded
private int currentPage = 0;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 0;
// True if we are still waiting for the last set of data to load.
private boolean loading = true;
// Sets the starting page index
private int startingPageIndex = 0;
RecyclerView.LayoutManager mLayoutManager;
public EndlessRecyclerViewScrollListener(LinearLayoutManager layoutManager) {
this.mLayoutManager = layoutManager;
}
public int getLastVisibleItem(int[] lastVisibleItemPositions) {
int maxSize = 0;
for (int i = 0; i < lastVisibleItemPositions.length; i++) {
if (i == 0) {
maxSize = lastVisibleItemPositions[i];
}
else if (lastVisibleItemPositions[i] > maxSize) {
maxSize = lastVisibleItemPositions[i];
}
}
return maxSize;
}
// This happens many times a second during a scroll, so be wary of the code you place here.
// We are given a few useful parameters to help us work out if we need to load some more data,
// but first we check if we are waiting for the previous load to finish.
#Override
public void onScrolled(RecyclerView view, int dx, int dy) {
int lastVisibleItemPosition = 0;
int totalItemCount = mLayoutManager.getItemCount();
if (mLayoutManager instanceof LinearLayoutManager) {
lastVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
}
// If the total item count is zero and the previous isn't, assume the
// list is invalidated and should be reset back to initial state
if (totalItemCount < previousTotalItemCount) {
this.currentPage = this.startingPageIndex;
this.previousTotalItemCount = totalItemCount;
if (totalItemCount == 0) {
this.loading = true;
}
}
// If it’s still loading, we check to see if the dataset count has
// changed, if so we conclude it has finished loading and update the current page
// number and total item count.
if (loading && (totalItemCount > previousTotalItemCount)) {
loading = false;
previousTotalItemCount = totalItemCount;
}
// If it isn’t currently loading, we check to see if we have breached
// the visibleThreshold and need to reload more data.
// If we do need to reload some more data, we execute onLoadMore to fetch the data.
// threshold should reflect how many total columns there are too
if (!loading && (lastVisibleItemPosition + visibleThreshold) > totalItemCount) {
currentPage++;
onLoadMore(currentPage, totalItemCount, view);
loading = true;
}
}
// Call this method whenever performing new searches
public void resetState() {
this.currentPage = this.startingPageIndex;
this.previousTotalItemCount = 0;
this.loading = true;
}
// Defines the process for actually loading more data based on page
public abstract void onLoadMore(int page, int totalItemsCount, RecyclerView view);
}
OnCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.booking_fragment, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.bookingRecyclerView);
linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
scrollListener = new EndlessRecyclerViewScrollListener(linearLayoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to the bottom of the list
if(CurrentStatus.equals("notSearch")){
if (current < Integer.parseInt(TP)) {
current++;
loadMoreBookings(sort);
}
else if(current == Integer.parseInt(TP)){
Toast.makeText(getActivity(),"No More Data to Load", Toast.LENGTH_SHORT).show();
}
}else{
if (current < Integer.parseInt(TP)) {
current++;
searchMoreBookings(search, sort);
}
else if(current == Integer.parseInt(TP)){
Toast.makeText(getActivity(),"No More Data to Be Load", Toast.LENGTH_SHORT).show();
}
}
}
LoadMoreBookings
private void loadMoreBookings(final String sort){
CurrentStatus = "notSearch";
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Please Wait While Retrieving Data");
progressDialog.setCancelable(false);
progressDialog.show();
StringRequest requesting = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String JSONString) {
progressDialog.dismiss();
try{
JSONObject jsonTP = new JSONObject(JSONString);
JSONArray jsonArrayB = jsonTP.getJSONArray("Data");
for(int i = 0; i < jsonArrayB.length(); i++){
JSONObject o = jsonArrayB.getJSONObject(i);
Booking list = new Booking(
o.getString("bookID"),
o.getString("userEmail"),
o.getString("paymentMethod"),
o.getString("paymentStatus"),
o.getString("totalPrice"),
o.getString(String.valueOf("securityCode")),
o.getString(String.valueOf("travelDate")),
o.getString("paymentID"),
o.getString("userFN"),
o.getString("userLN"),
o.getString(String.valueOf("createdAt")),
o.getString("tTM"),
o.getString("messageToCustomer"),
o.getString("messageFromMerchant"),
o.getString("wCN"),
o.getString("wLocation"),
o.getString("wWebsite")
);
listBooking.add(list);
count++;
}
Toast.makeText(getActivity(), "Data : "+count, Toast.LENGTH_SHORT).show();
adapter = new BookingAdapter(listBooking,getActivity());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
loadMoreBookings(sort);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getActivity().getApplicationContext(), "Failed To Retrieve Data. Please Try Again.",Toast.LENGTH_LONG).show();
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
String user = getActivity().getIntent().getStringExtra("username");
params.put("username", user);
params.put("currentpage", String.valueOf(current));
params.put("sorting", sort);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(requesting);
}
set adapter in onCreateView()
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.booking_fragment, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.bookingRecyclerView);
linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new BookingAdapter(listBooking,getActivity());
recyclerView.setAdapter(adapter);
scrollListener = new EndlessRecyclerViewScrollListener(linearLayoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to the bottom of the list
if(CurrentStatus.equals("notSearch")){
if (current < Integer.parseInt(TP)) {
current++;
loadMoreBookings(sort);
}
else if(current == Integer.parseInt(TP)){
Toast.makeText(getActivity(),"No More Data to Load", Toast.LENGTH_SHORT).show();
}
}else{
if (current < Integer.parseInt(TP)) {
current++;
searchMoreBookings(search, sort);
}
else if(current == Integer.parseInt(TP)){
Toast.makeText(getActivity(),"No More Data to Be Load", Toast.LENGTH_SHORT).show();
}
}
}
don't set adapter every time just notify the adapter item inserted at position.
private void loadMoreBookings(final String sort){
CurrentStatus = "notSearch";
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Please Wait While Retrieving Data");
progressDialog.setCancelable(false);
progressDialog.show();
StringRequest requesting = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String JSONString) {
progressDialog.dismiss();
try{
JSONObject jsonTP = new JSONObject(JSONString);
JSONArray jsonArrayB = jsonTP.getJSONArray("Data");
for(int i = 0; i < jsonArrayB.length(); i++){
JSONObject o = jsonArrayB.getJSONObject(i);
Booking list = new Booking(
o.getString("bookID"),
o.getString("userEmail"),
o.getString("paymentMethod"),
o.getString("paymentStatus"),
o.getString("totalPrice"),
o.getString(String.valueOf("securityCode")),
o.getString(String.valueOf("travelDate")),
o.getString("paymentID"),
o.getString("userFN"),
o.getString("userLN"),
o.getString(String.valueOf("createdAt")),
o.getString("tTM"),
o.getString("messageToCustomer"),
o.getString("messageFromMerchant"),
o.getString("wCN"),
o.getString("wLocation"),
o.getString("wWebsite")
);
listBooking.add(list);
adapter.notifyItemInserted(count);
count++;
}
Toast.makeText(getActivity(), "Data : "+count, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
loadMoreBookings(sort);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getActivity().getApplicationContext(), "Failed To Retrieve Data. Please Try Again.",Toast.LENGTH_LONG).show();
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
String user = getActivity().getIntent().getStringExtra("username");
params.put("username", user);
params.put("currentpage", String.valueOf(current));
params.put("sorting", sort);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(requesting);
}
I have a recycler view in which I load some data from the server when user scroll to bottom I want to show a progress bar and send another request to the server for more data. I have tried below code but it not able to load more data from the server. please help
private RecyclerView mRecyclerView;
private List<User> mUsers = new ArrayList<>();
private UserAdapter mUserAdapter;
private static String sz_RecordCount;
private static String sz_LastCount;
private final int m_n_DefaultRecordCount = m_kDEFAULT_RECORD_COUNT;
private static final int m_kDEFAULT_RECORD_COUNT = 5;
private ArrayList<CDealAppDatastorage> s_oDataset;
private String TAG = MainActivity.class.getSimpleName();
private CDealAppDatastorage item;
private static int arrayCount;
private Context context;
private PreferenceHelper m_oPreferenceHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
m_oPreferenceHelper = new PreferenceHelper(context);
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
int intialLastCount = 0;
sz_LastCount = String.valueOf(intialLastCount);// increment of last count...
s_oDataset = new ArrayList<>();// making object of Arraylist
//initial request for data
initalDealListing();
mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
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());
//sending request to server for more data
moreDealsRequest();
mUserAdapter.notifyDataSetChanged();
mUserAdapter.setLoaded();
}
}, 5000);
}
});
}
private void initalDealListing() {
String m = "9565656565";
String p = "D55A8077E0208A5C5B25176608EF84BD";
// 3. build jsonObject
try {
final JSONObject jsonObject = new JSONObject();// making object of Jsons.
jsonObject.put("agentCode", m.trim());// put mobile number
jsonObject.put("pin", p.trim());// put password
jsonObject.put("recordcount", sz_RecordCount.trim());// put record count
jsonObject.put("lastcountvalue", sz_LastCount.trim());// put last count
Log.e("CAppList:", sz_RecordCount);
Log.e("Capplist:", sz_LastCount);
Log.d(TAG, "Server Request:-" + jsonObject.toString());
final String m_DealListingURL = APIStorage.IREWARDS_URL + APIStorage.DEALLISTING_URL;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "Server Response:-" + response);
try {
int nResultCodeFromServer = Integer.parseInt(response.getString(ServerResponseStorage.s_szRESULT_CODE));
if (nResultCodeFromServer == ConstantInt.m_kTRANSACTION_SUCCESS) {
JSONArray posts = response.optJSONArray(ServerResponseStorage.s_szDEAL_ARRAY);// get Deal list in array from response
s_oDataset.clear();
for (int i = 0; i < posts.length(); i++) {// loop for counting deals from server
try {
JSONObject post = posts.getJSONObject(i);// counting deal based on index
item = new CDealAppDatastorage();// creating object of DealAppdata storage
item.setM_szHeaderText(post.getString(ServerResponseStorage.s_szDEAL_NAME));// get deal name from response
item.setM_szsubHeaderText(post.getString(ServerResponseStorage.s_szDEAL_CODE));// get dealcode from response
s_oDataset.add(item);// add all items in ArrayList
} catch (Exception e) {
e.printStackTrace();
}
}
arrayCount = posts.length();
Log.d(TAG, "ArrayCount::" + arrayCount);
/*here we are storing no. of deals coming from server*/
// write
m_oPreferenceHelper.saveIntegerValue("LastCountLength", arrayCount);
if (!s_oDataset.isEmpty()) {// condition if data in arraylist is not empty
mRecyclerView.setAdapter(mUserAdapter);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Server error:-" + error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(ConstantInt.INITIAL_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
/*This method send request to server for more deals*/
private void moreDealsRequest() {
try {
// 3. build jsonObject
final JSONObject jsonObject = new JSONObject();// making object of Jsons.
jsonObject.put(ServerRequestKeyStorage.s_szAGENT_CODE, "9565656565");// put mobile number
jsonObject.put(ServerRequestKeyStorage.s_szPASSWORD, "D55A8077E0208A5C5B25176608EF84BD");// put password
jsonObject.put(ServerRequestKeyStorage.s_szRECORD_COUNT, sz_RecordCount.trim());// put record count
jsonObject.put(ServerRequestKeyStorage.s_szLAST_COUNT, sz_LastCount.trim());// put last count
Log.e("CAppList:", sz_RecordCount);
Log.e("Capplist:", sz_LastCount);
// 4. convert JSONObject to JSON to String
Log.e(TAG, "Server Request:-" + jsonObject.toString());
RequestQueue requestQueue = Volley.newRequestQueue(context);
final String imgPath = APIStorage.IREWARDS_URL + APIStorage.DEAL_IMAGE_PATH;
final String m_DealListingURL = APIStorage.IREWARDS_URL + APIStorage.DEALLISTING_URL;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Server Response:-" + response);
try {
int nResultCodeFromServer = Integer.parseInt(response.getString(ServerResponseStorage.s_szRESULT_CODE));
if (nResultCodeFromServer == ConstantInt.m_kTRANSACTION_SUCCESS) {
// Select the last row so it will scroll into view...
JSONArray posts = response.optJSONArray(ServerResponseStorage.s_szDEAL_ARRAY);// GETTING DEAL LIST
for (int i = 0; i < posts.length(); i++) {
try {
JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
item = new CDealAppDatastorage();// object create of DealAppdatastorage
item.setM_szHeaderText(post.getString(ServerResponseStorage.s_szDEAL_NAME));//getting deal name
item.setM_szsubHeaderText(post.getString(ServerResponseStorage.s_szDEAL_CODE));// getting deal code
s_oDataset.add(item);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Server Error::" + error);
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(ConstantInt.INITIAL_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
static class UserViewHolder extends RecyclerView.ViewHolder {
public TextView tvName;
public TextView tvEmailId;
public UserViewHolder(View itemView) {
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvEmailId = (TextView) itemView.findViewById(R.id.tvEmailId);
}
}
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 s_oDataset.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.layout_user_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) {
CDealAppDatastorage user = s_oDataset.get(position);
UserViewHolder userViewHolder = (UserViewHolder) holder;
userViewHolder.tvName.setText(user.getM_szHeaderText());
userViewHolder.tvEmailId.setText(user.getM_szsubHeaderText());
} else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return s_oDataset == null ? 0 : s_oDataset.size();
}
public void setLoaded() {
isLoading = false;
}
}
}
Use Below Code:
First Declare these global variables:
int visibleItemCount, totalItemCount = 1;
int firstVisiblesItems = 0;
int totalPages = 1; // get your total pages from web service first response
int current_page = 0;
boolean canLoadMoreData = true; // make this variable false while your web service call is going on.
LinearLayoutManager linearLayoutManager;
Assign Layout manager to your Recyclerview:
linearLayoutManager = new LinearLayoutManager(mActivity);
mRecyclerView.setLayoutManager(linearLayoutManager);
Scroll Listener of your recyclerview:
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy > 0) //check for scroll down
{
visibleItemCount = linearLayoutManager.getChildCount();
totalItemCount = linearLayoutManager.getItemCount();
firstVisiblesItems = linearLayoutManager.findFirstVisibleItemPosition();
if (canLoadMoreData) {
if ((visibleItemCount + firstVisiblesItems) >= totalItemCount) {
if (current_page < totalPages) {
canLoadMoreData = false;
/**
* .
* .
* .
* .call your webservice with page index
* .
* .
*
*/
//After completion of web service make 'canLoadMoreData = true'
}
}
}
}
}
});
Too late but i'm also refer same way check with my code it work for me
Here is API call using retrofit and get listnotifications then in this method i create one more method for loadmore getMoreNotificationListApiCall()
public void getNotification()
{
if (listnotifications.size() > 0) {
notificationListAdapter = new NotificationListAdapter(NotificationListActivity.this, listnotifications, notificationListRecyclerview);
notificationListRecyclerview.setAdapter(notificationListAdapter);
notificationListAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
Log.e("ad", "Load More");
listnotifications.add(null);
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
if (listnotifications.size()>0) {
notificationListAdapter.notifyItemInserted(listnotifications.size() - 1);
}
}
};
handler.post(r);
try {
if (CommonUtils.isConnectingToInternet(NotificationListActivity.this)) {
// Internet Connection is Present
getMoreNotificationListApiCall();
} else {
//Remove loading item
if (listnotifications.size()>0) {
listnotifications.remove(listnotifications.size() - 1);
}
notificationListAdapter.notifyItemRemoved(listnotifications.size());
CommonUtils.commonToast(NotificationListActivity.this, getResources().getString(R.string.no_internet_exist));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
getMoreNotificationListApiCall() method code in this method i increment startlimit means page index and remove null (i'm using retorfit for api call)
private void getMoreNotificationListApiCall() {
try {
if (CommonUtils.isConnectingToInternet(NotificationListActivity.this)) {
StartLimit = StartLimit + 10;
Call<NotificationBase> call = ApiHandler.getApiService().getNotificationListApi(notificationListJsonMap());
call.enqueue(new Callback<NotificationBase>() {
#Override
public void onResponse(Call<NotificationBase> registerCall, Response<NotificationBase> response) {
Log.e(TAG, " Full json gson => " + "Hi i am here");
try {
Log.e(TAG, " Full json gson => " + new Gson().toJson(response));
JSONObject jsonObj = new JSONObject(new Gson().toJson(response).toString());
Log.e(TAG, " responce => " + jsonObj.getJSONObject("body").toString());
if (response.isSuccessful()) {
int success = response.body().getSuccess();
if (success == 1) {
List<NotificationBean> moreNotication = response.body().getNotificatons();
//Remove loading item
if (listnotifications.size() > 0) {
listnotifications.remove(listnotifications.size() - 1);
}
notificationListAdapter.notifyItemRemoved(listnotifications.size());
for (int i = 0; i < moreNotication.size(); i++) {
listnotifications.add(moreNotication.get(i));
}
notificationListAdapter.notifyDataSetChanged();
notificationListAdapter.setLoaded();
} else if (success == 0) {
if (listnotifications.size() > 0) {
listnotifications.remove(listnotifications.size() - 1);
}
notificationListAdapter.notifyItemRemoved(listnotifications.size());
} else {
if (listnotifications.size() > 0) {
listnotifications.remove(listnotifications.size() - 1);
}
notificationListAdapter.notifyItemRemoved(listnotifications.size());
}
} else {
if (listnotifications.size() > 0) {
listnotifications.remove(listnotifications.size() - 1);
}
notificationListAdapter.notifyItemRemoved(listnotifications.size());
}
} catch (Exception e) {
e.printStackTrace();
try {
Log.e(TAG, "error=" + e.toString());
if (listnotifications.size() > 0) {
listnotifications.remove(listnotifications.size() - 1);
}
notificationListAdapter.notifyItemRemoved(listnotifications.size());
} catch (Resources.NotFoundException e1) {
e1.printStackTrace();
}
}
}
#Override
public void onFailure(Call<NotificationBase> call, Throwable t) {
try {
Log.e(TAG, "error" + t.toString());
if (listnotifications.size() > 0) {
listnotifications.remove(listnotifications.size() - 1);
}
notificationListAdapter.notifyItemRemoved(listnotifications.size());
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
}
});
} else {
CommonUtils.commonToast(NotificationListActivity.this, getResources().getString(R.string.no_internet_exist));
}
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
}
Here is my Adapter class in which i implement OnLoadMoreListener
public class NotificationListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static List<NotificationBean> mList;
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
FragmentActivity mFragmentActivity;
private OnLoadMoreListener mOnLoadMoreListener;
private boolean isLoading;
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
public NotificationListAdapter(FragmentActivity fragmentActivity, List<NotificationBean> data, RecyclerView mRecyclerView) {
this.mList = data;
this.mFragmentActivity = fragmentActivity;
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 mList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
public void delete(int position) { //removes the row
Log.e("Position : ", "" + position);
mList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mList.size());
}
// Return the size arraylist
#Override
public int getItemCount() {
return mList == null ? 0 : mList.size();
}
public void setLoaded() {
isLoading = false;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_notification_list, parent, false);
return new ViewHolder(itemLayoutView);
} else if (viewType == VIEW_TYPE_LOADING) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.loading_layout, parent, false);
return new LoadingViewHolder(itemLayoutView);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof ViewHolder) {
try {
final ViewHolder viewHolder = (ViewHolder) holder;
viewHolder.singleBean = mList.get(position);
viewHolder.pos = position;
final NotificationBean list = mList.get(position);
String notificationTitle = list.getMessage();
String notificationTimeDate = list.getCreatedDatetime();
String notificationIsRead = list.getIsRead();
} catch (Exception e) {
e.printStackTrace();
}
} else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
static class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public LoadingViewHolder(View itemView) {
super(itemView);
progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
public NotificationBean singleBean;
int pos;
TextView txt_notification_time_date;
CustomTextview checkbox_notification;
RelativeLayout rl_row_background;
public ViewHolder(final View v) {
super(v);
checkbox_notification = (CustomTextview) v.findViewById(R.id.checkbox_notification);
//checkbox_notification.setButtonDrawable(android.R.color.transparent);//custom_checkbox
// txt_notification_title= (TextView) v.findViewById(R.id.txt_notification_title);
txt_notification_time_date = (TextView) v.findViewById(R.id.txt_notification_time_date);
rl_row_background = (RelativeLayout) v.findViewById(R.id.rl_row_background);
}
}
public void refreshAdapter() {
notifyDataSetChanged();
}
}
here is xml file loading_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:orientation="vertical">
<ProgressBar
android:id="#+id/progressBar1"
style="#style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:indeterminate="true" />
</LinearLayout>
Fetching the data from server is a Async Task. So you need to enclose the
updation code in a runOnUiThread runnable. to change UI.
runOnUiThread(new Runnable() {
#Override
public void run() {
mUsers.remove(mUsers.size() - 1);
mUserAdapter.notifyItemRemoved(mUsers.size());
//sending request to server for more data
moreDealsRequest();
mUserAdapter.notifyDataSetChanged();
mUserAdapter.setLoaded();
}});
How can i pass the position of item using intent to start a new activity?
I want to start a new activity called single which displays the rating of the movie correspondingly..pls help
I have been trying this for the past two days.
Here is the code:
public class NowPlaying extends Fragment {
private static final String TAG = NowPlaying.class.getSimpleName();
// Movies json url
private static final String url = "http://private-8149-themoviedb.apiary-mock.com/3/movie/now_playing?api_key=";
private ProgressDialog pDialog;
private List<NowPlayingInfo> bottom = new ArrayList<NowPlayingInfo>() ;
NowPlayingAdapter adapter;
RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
ActionBar toolbar = ((AppCompatActivity) getActivity()).getSupportActionBar();
toolbar.setTitle("Now playing");
recyclerView = (RecyclerView) v.findViewById(R.id.cardList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new NowPlayingAdapter(getActivity(), bottom);
recyclerView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
v.getContext().startActivity(i);
}
});
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
NowPlayingInfo trailer = new NowPlayingInfo();
trailer.setTitle(jsonObject.getString("original_title"));
String iss = "http://image.tmdb.org/t/p/w500" + jsonObject.getString("poster_path") ;
trailer.setImage(iss);
bottom.add(trailer);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
NowPlayingInfo _nowPlaying = bottom.get(position);
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
i.putExtra("ISS", _nowPlaying.getImage()); //you can put your current playing info.
i.putExtra("POSITION", position); //you can put your position to next activity.
v.getContext().startActivity(i);
}
});
Add this in your SingleInfo Class.
String _rating = "";
public String get_rating() {
return _rating;
}
public void set_rating(String _rating) {
this._rating = _rating;
}
Add this in your Single class -
int _currentPos = 0 ; //Global variable .
_currentPos = getIntent().getIntExtra("position", 0);// paste this in onCreate()
Add this code in onResponse of Single Class -
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
SingleInfo s = new SingleInfo();
s.set_rating(jsonObject.getString("rating"));
single.add(s);
}
//changed by Shoeb
SingleInfo _singleInfo = single.get(_currentPos); //position from previous activity
textView.setText(_singleInfo.get_rating());
//end changes
} catch (JSONException e) {
e.printStackTrace();
}
Add an extra to your intent
i.putExtra("position",position);
And on the other activity:
getIntent().getIntExtra("position", 0);