Please help me out to load more data from the server upon scrolling my RecyclerView . Here I have successfully created RecyclerView by loading data from my Mysql server by using volley string request.
Here is my code.
private void populateRecycleView() {
if (Utility.checkNetworkConnection(this)) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Searching...");
progressDialog.setMessage("Searching for the blood donor. Please wait a moment.");
progressDialog.setCancelable(false);
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_DONORS_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONArray jsonArray = new JSONArray(response);
int count = 0;
while (count < jsonArray.length()) {
JSONObject jsonObject = jsonArray.getJSONObject(count);
String firstName = jsonObject.getString("fName");
String secondName = jsonObject.getString("sName");
String email = jsonObject.getString("emailid");
String password = jsonObject.getString("pass");
String mobile = jsonObject.getString("mobile");
String bloodRt = jsonObject.getString("blood");
String age = jsonObject.getString("age");
String gender = jsonObject.getString("gender");
String country = jsonObject.getString("country");
String location = jsonObject.getString("location");
String latitude = jsonObject.getString("latitude");
String longitude = jsonObject.getString("longitude");
String profilePicFIleName = jsonObject.getString("picname");
String profilePicURL = jsonObject.getString("pic");
Donor donor = new Donor(firstName, secondName, email, password, mobile, bloodRt, age, gender,
country, location, latitude, longitude, profilePicFIleName, profilePicURL);
donorsList.add(donor);
count++;
}
donorsAdapter = new DonorsAdapter(FindDonorResult.this, donorsList);
recyclerView = (RecyclerView) findViewById(R.id.rv_search_result_donor);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(FindDonorResult.this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(donorsAdapter);
donorsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(FindDonorResult.this, "Active data network is not available.", Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("bloodGroup", bloodGroup);
return params;
}
};
NetworkRequestSingleTon.getOurInstance(this).addToRequestQue(stringRequest);
} else {
Utility.checkNetworkConnectionFound(this);
}
}
And this is my RecyclerView adapter...
public class DonorsAdapter extends RecyclerView.Adapter<DonorsAdapter.CustomViewHolder> {
private Context context;
private ArrayList<Donor> donorList;
private String bloodGroup;
public DonorsAdapter(Context context, ArrayList<Donor> donorList) {
this.context = context;
this.donorList = donorList;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_blood_donors_result,
parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
final Donor donor = donorList.get(position);
String displayName = donor.getFirstName() + " " + donor.getSecondName();
holder.tvDisplayName.setText(displayName);
holder.tvEmailID.setText(donor.getEmail());
String userProfileURL = donor.getProfilePicURL();
if (!userProfileURL.equals("")) {
Picasso.with(context).load(userProfileURL).resize(80, 80).centerCrop().
into(holder.ivProfilePic);
} else {
holder.ivProfilePic.setImageResource(R.drawable.ic_person_white_24dp);
}
bloodGroup = donor.getBloodGroup();
if (bloodGroup.equals("A+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_);
else if (bloodGroup.equals("A-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_negative);
else if (bloodGroup.equals("B+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_positive);
else if (bloodGroup.equals("B-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_negative);
else if (bloodGroup.equals("O+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_positive);
else if (bloodGroup.equals("O-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_negative);
else if (bloodGroup.equals("AB+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_positive);
else if (bloodGroup.equals("AB-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_negative);
if(Utility.isNetworkEnabled){
holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, DisplayDonorDetails.class);
intent.putExtra("donor", donor);
context.startActivity(intent);
}
});
}else {
Toast.makeText(context, "Network not available.", Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemCount() {
if(donorList != null){
return donorList.size();
}else {
return 0;
}
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView ivProfilePic, ivBloodTypeDisplay, ivArrow;
TextView tvDisplayName;
TextView tvEmailID;
ConstraintLayout constraintLayout;
public CustomViewHolder(View itemView) {
super(itemView);
ivProfilePic = (ImageView) itemView.findViewById(R.id.civ_user_profile_picture);
ivBloodTypeDisplay = (ImageView) itemView.findViewById(R.id.civ_user_blood_type_display);
ivArrow = (ImageView) itemView.findViewById(R.id.civ_arrow);
tvDisplayName = (TextView) itemView.findViewById(R.id.tvUserNameOnRV);
tvEmailID = (TextView) itemView.findViewById(R.id.tvEmailDisplayOnRV);
constraintLayout = (ConstraintLayout) itemView.findViewById(R.id.recycle_view_item_container);
}
}
}
Populate your donorsAdapter only with the 50 first elements of your donorsList, create a function that save the position of the latest element displayed and add other 50 donors to your adapter starting from the latest position saved when you need it.
Hope it helps.
EDIT
First create an emptyList:
List<Donor> subElements = new ArrayList<>();
and pass it to your adapter:
donorsAdapter = new DonorsAdapter(FindDonorResult.this, subElements);
Now you can create a method like this (you can call in onClick event for example):
private int LAST_POSITION = 0;
private int DONORS_NUM_TOSHOW = 50;
public void showMoreDonors(){
if(donarsList.size() > Last_postion+50){
List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,Last_postion+DONORS_NUM_TOSHOW));
for(Donor a : tempList){
subElements.add(a);
}
Last_postion += DONORS_NUM_TOSHOW;
donorsAdapter.notifyDataSetChanged();
}else{
List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,donorsList.size()));
for(Donor a : tempList){
subElements.add(a);
}
donorsAdapter.notifyDataSetChanged();
}
}
Remember to check when donorsList is over.
I didn't test it, but i hope it is usefull to understand the idea.
Finally, I sort this out. I have got an awesome tutorial from this blog.
http://android-pratap.blogspot.in/2015/06/endless-recyclerview-with-progress-bar.html.
I made some changes to populate the list because my data is on a remote server and by using volley library I fetched the data into the list. Remaining things are same.
Related
I am trying to display posts from a server in listView. So I used recycle-view to achieve that. Everything is working fine except that ll items are displaying twice.
I counted the total fetched items from server, and the count is 5, but adapter.getItemCount is showing 10.
After searching hours on the internet, I tried following :
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
and
homeFragmentAdapter.setHasStableIds(true);
Below is my fragment...
package com.example.projectName;
import static android.content.Context.MODE_PRIVATE;
import static android.webkit.ConsoleMessage.MessageLevel.LOG;
import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;
public class HomeFollowersFragment extends Fragment implements InfiniteScrollListener.OnLoadMoreListener, RecyclerViewItemListener {
private static final String TAG = "HomeFollowersFragment";
private static final String URL = "https://api.androidhive.info/json/movies_2017.json";
private RecyclerView recyclerView;
private ProgressBar postLoader;
FFmpeg ffmpeg;
// private List<Movie> movieList;
// private HomeAdapter mAdapter;
private List<PostList> postListGlobal = new ArrayList<>();
List<VerticalDataModal> verticalDataModals;
List<HorizontalDataModal> horizontalDataModals;
private SwipeRefreshLayout swipeMore;
private InfiniteScrollListener infiniteScrollListener;
private HomeFragmentAdapter homeFragmentAdapter;
SharedPreferences sharedPreferences;
private Boolean isLoggedIn = false;
private String email = "";
private String token = "";
private String userId = "";
private Dialog customLoader;
SkeletonScreen skeletonScreen;
private int pastVisiblesItems, visibleItemCount, totalItemCount;
private boolean loading = false;
private EndlessScrollListener scrollListener;
SharedPreferences sp;
SharedPreferences.Editor Ed;
public HomeFollowersFragment() {
//super();
}
/**
* #return A new instance of fragment HomeFollowersFragment.
*/
public static HomeFollowersFragment newInstance() {
return new HomeFollowersFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
// ((AppCompatActivity) getActivity()).getSupportActionBar().show();
try{
sharedPreferences = getActivity().getSharedPreferences("Login", MODE_PRIVATE);
email = sharedPreferences.getString("email", null);
token = sharedPreferences.getString("token", null);
isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
userId = sharedPreferences.getString("id", null);
}catch (Exception e){
e.printStackTrace();
Log.d("StackError", "StackError: "+e);
}
sp = getActivity().getSharedPreferences("Posts", MODE_PRIVATE);
if(!isLoggedIn || token == null || userId == null){
Intent intent = new Intent(getActivity(), RegisterActivity.class);
intent.putExtra("loginFrom", "profile");
startActivity(intent);
}
recyclerView = view.findViewById(R.id.recycler_view);
postLoader = view.findViewById(R.id.post_loader);
swipeMore = view.findViewById(R.id.swipe_layout);
homeFragmentAdapter = new HomeFragmentAdapter(postListGlobal, this, "home");
if(sp.contains("postListGlobal"))
skeletonScreen = Skeleton.bind(recyclerView)
.adapter(homeFragmentAdapter)
.shimmer(true)
.angle(20)
.frozen(false)
.duration(1200)
.count(10)
.load(R.layout.item_skelton_home_page)
.show(); //default count is 10
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
StaggeredGridLayoutManager sLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(sLayoutManager);
homeFragmentAdapter.setHasStableIds(true);
recyclerView.setAdapter(homeFragmentAdapter);
recyclerView.setNestedScrollingEnabled(false);
customLoader = new Dialog(getActivity(), R.style.crystal_range_seek_bar);
customLoader.setCancelable(false);
View loaderView = getLayoutInflater().inflate(R.layout.custom_loading_layout, null);
customLoader.getWindow().getAttributes().windowAnimations = R.style.crystal_range_seek_bar;
customLoader.getWindow().setBackgroundDrawableResource(R.color.translucent_black);
ImageView imageLoader = loaderView.findViewById(R.id.logo_loader);
Glide.with(this).load(R.drawable.logo_loader).into(imageLoader);
customLoader.setContentView(loaderView);
if(homeFragmentAdapter.getItemCount() == 0 && !loading){
// server fetchdata
Log.d(TAG, "no item available..");
postLoader.setVisibility(View.VISIBLE);
loading = true;
fetchStoreItems();
}else{
postLoader.setVisibility(View.GONE);
}
swipeMore.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.d(TAG, "on refresh...");
fetchStoreItems();
}
});
return view;
}
#Override
public void onItemClicked(int position) {
Log.d(TAG, "click position: "+position);
Toast.makeText(getActivity(),postListGlobal.get(position).getTitle(),Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(),""+position, Toast.LENGTH_SHORT).show();
}
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;
}
#Override
public void onLoadMore() {
homeFragmentAdapter.addNullData();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
homeFragmentAdapter.removeNull();
Toast.makeText(getContext(), "load more here...", Toast.LENGTH_LONG).show();
// fetchStoreItems();
swipeMore.setRefreshing(false);
}
}, 2000);
}
private void fetchStoreItems() {
RequestQueue queue = Volley.newRequestQueue(getActivity());
Log.d(TAG, "Post Data Followers: "+Constant.FETCH_POSTS_API);
CacheRequest cacheRequest = new CacheRequest(0, Constant.FETCH_POSTS_API, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
try {
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
if (response == null) {
Toast.makeText(getActivity(), "Couldn't fetch the store items! Pleas try again.", Toast.LENGTH_LONG).show();
loading = false;
return;
}
JSONObject postObj = new JSONObject(jsonString);
System.out.println("post full data... : " + postObj);
if (postObj.getBoolean("Status")) {
try {
postLoader.setVisibility(View.GONE);
JSONArray arrayResponse = postObj.optJSONArray("Data");
int dataArrLength = arrayResponse.length();
if(dataArrLength == 0){
Toast.makeText(getActivity(), "No posts available at this time, you can create yout own post by clicking on mic button", Toast.LENGTH_SHORT).show();
}
postListGlobal.clear();
Log.d(TAG, "Total Posts count: "+dataArrLength);
for(int i=0; i<dataArrLength; i++) {
try {
JSONObject dataListObj = arrayResponse.optJSONObject(i);
System.out.println("post full data... : " + dataListObj);
JSONObject postDetailObj = dataListObj.optJSONObject("post_detail");
JSONObject followDtatusObj = dataListObj.optJSONObject("follow_status");
JSONArray postFilesArr = dataListObj.optJSONArray("post_files");
JSONObject userDatasObj = postDetailObj.optJSONObject("user");
String userId = userDatasObj.optString("id");
String userName = userDatasObj.optString("email");
String userImage = userDatasObj.optString("email");
boolean followStatus = followDtatusObj.optBoolean("follow");
String postId = postDetailObj.optString("id");
String postTitle = postDetailObj.optString("post_title");
String postDescription = postDetailObj.optString("post_description");
String postCoverUrl = postDetailObj.optString("post_coverurl", "1");
String postViewType = postDetailObj.optString("view_type", "1");
String postAllowComment = postDetailObj.optString("allow_comments", "1");
String postAllowDownload = postDetailObj.optString("allow_download", "1");
String postTotalPost = postDetailObj.optString("total_post", "1");
String postPostSection = postDetailObj.optString("post_section", "image");
String postActiveStatus = postDetailObj.optString("is_active", "1");
String postTotalViews = postDetailObj.optString("total_watched","0");
String postTotalShare = postDetailObj.optString("total_share","0");
String postTotalDownload = postDetailObj.optString("total_download","0");
String postTotalReaction = postDetailObj.optString("total_reaction","0");
String postTotalLike = postDetailObj.optString("total_like","0");
String postTotalSmile = postDetailObj.optString("smile_reaction","0");
String postTotalLaugh = postDetailObj.optString("laugh_reaction","0");
String postTotalSad = postDetailObj.optString("sad_reaction","0");
String postTotalLove = postDetailObj.optString("love_reaction","0");
String postTotalShock = postDetailObj.optString("shock_reaction","0");
int totalPostFiles = Integer.parseInt(postTotalPost);
int postArrLength = postFilesArr.length();
String postImageUrl = null;
String postMusicUrl = null;
String commonUrl = "http://serverName.com/";
if(postArrLength >= 1){
JSONObject dataFilesListObj = postFilesArr.optJSONObject(0);
// System.out.println("post files full data... : " + dataFilesListObj);
String postFileId = dataFilesListObj.optString("id");
postImageUrl = dataFilesListObj.optString("image_file_path");
postMusicUrl = dataFilesListObj.optString("music_file_path");
System.out.println("post files full data... : " + dataFilesListObj);
}
System.out.println("post files full data... : " + commonUrl+postMusicUrl);
System.out.println("post files full data... : " + commonUrl+postImageUrl);
PostList postList = new PostList();
postList.setId(postId);
postList.setTitle(postTitle);
postList.setTotalPost(""+dataArrLength);
postList.setTotalView(postTotalViews);
postList.setTotalReaction(postTotalReaction);
postList.setMusicPath(commonUrl+postMusicUrl);
postList.setImagePath(commonUrl+postImageUrl);
if(postImageUrl == null){
postList.setImagePath("https://amazonBucket.s3.location.amazonaws.com/images/pic1.jpg");
}
postList.setUserId(userId);
postList.setUserName(userName);
postList.setPostDataObject(arrayResponse);
postListGlobal.add(postList);
Log.d(TAG, "Total Posts: "+dataListObj);
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "Post Data Error1: "+e);
Toast.makeText(getActivity(), "File now found", Toast.LENGTH_LONG).show();
loading = false;
}
}
} catch (Exception e){
e.printStackTrace();
Log.d(TAG, "Post Data Error2: "+e);
Toast.makeText(getActivity(), R.string.server_error, Toast.LENGTH_LONG).show();
loading = false;
}
}else{
try {
Toast.makeText(getActivity(), new JSONObject(jsonString).getString("Message"), Toast.LENGTH_LONG).show();
} catch (JSONException ex) {
ex.printStackTrace();
Log.d(TAG, "Post Data Error3: "+ex);
Toast.makeText(getActivity(), R.string.server_error, Toast.LENGTH_SHORT).show();
}
loading = false;
}
// refreshing recycler view
homeFragmentAdapter.removeNull();
homeFragmentAdapter.addData(postListGlobal);
homeFragmentAdapter.notifyDataSetChanged();
// save in local memory
// saveArrayList(postListGlobal, "postListGlobal");
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "Post Data Error4: "+e);
}
loading = true;
homeFragmentAdapter.notifyDataSetChanged();
swipeMore.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "onErrorResponse: "+ error, Toast.LENGTH_SHORT).show();
swipeMore.setRefreshing(false);
loading = true;
homeFragmentAdapter.notifyDataSetChanged();
postLoader.setVisibility(View.VISIBLE);
loading = false;
Log.d(TAG, "Post Data Error5: "+error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
String finalToken = "Bearer "+token;
params.put("Authorization", finalToken);
params.put("Content-Type", "application/json");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(cacheRequest);
}
private class CacheRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
public CacheRequest(int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
}
#Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
if (cacheEntry == null) {
cacheEntry = new Cache.Entry();
}
final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
long now = System.currentTimeMillis();
final long softExpire = now + cacheHitButRefreshed;
final long ttl = now + cacheExpired;
cacheEntry.data = response.data;
cacheEntry.softTtl = softExpire;
cacheEntry.ttl = ttl;
String headerValue;
headerValue = response.headers.get("Date");
if (headerValue != null) {
cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
headerValue = response.headers.get("Last-Modified");
if (headerValue != null) {
cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
cacheEntry.responseHeaders = response.headers;
return Response.success(response, cacheEntry);
}
#Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
Log.d(TAG, "Post Data volleyError: "+volleyError);
return super.parseNetworkError(volleyError);
}
#Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}
}
and Adapter Class
package com.example.ProjectName;
public class HomeFragmentAdapter extends RecyclerView.Adapter <HomeFragmentAdapter.HomeViewHolder>{
// private ArrayList<Integer> dataList;
private List<PostList> postListGlobal;
int VIEW_TYPE_LOADING;
int VIEW_TYPE_ITEM;
Context context;
private RecyclerViewItemListener callback;
FFmpeg ffmpeg;
String callingPage;
public HomeFragmentAdapter(List<PostList> postListGlobal, RecyclerViewItemListener callback, String callingPage) {
this.postListGlobal = postListGlobal;
this.callback = callback;
this.callingPage = callingPage;
// setHasStableIds(true);
}
#NonNull
#Override
public HomeFragmentAdapter.HomeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View root = null;
context = parent.getContext();
root = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_home_tile_list, parent, false);
return new DataViewHolder(root);
}
#Override
public void onBindViewHolder(#NonNull HomeFragmentAdapter.HomeViewHolder holder, int position) {
if (holder instanceof DataViewHolder) {
final PostList postList = postListGlobal.get(position);
holder.postTitle.setText(postList.getTitle());
holder.postWatch.setText(postList.getTotalView());
holder.postReaction.setText(postList.getTotalReaction());
String imageUrl = postList.getImagePath();
// String imageUrl = Constant.SERVER_URL+"/"+postList.getImagePath();
String musicUrl = postList.getMusicPath();
// String musicUrl = Constant.SERVER_URL+"/"+postList.getMusicPath();
Log.d(TAG, "Post url: "+imageUrl+" -- "+musicUrl);
// int totalMusicTime = getDurationVal(musicUrl, "second");
holder.postTime.setText(postList.getTotalPost());
holder.thumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callback.onItemClicked(position);
Log.d("homeView", "screenName : "+callingPage);
if(callingPage.equals("home")){
Log.d("homeView", "screenName : "+position);
Intent intent = new Intent(context, MainViewActivity.class);
intent.putExtra("loginFrom", "homeView");
intent.putExtra("postDataObj", postList.getPostDataObject().toString());
intent.putExtra("postPosition", ""+position);
intent.putExtra("tabId", "1");
context.startActivity(intent);
}
}
});
Drawable mDefaultBackground = context.getResources().getDrawable(R.drawable.influencers);
CircularProgressDrawable circularProgressDrawable = new CircularProgressDrawable(context);
circularProgressDrawable.setStrokeWidth(5f);
Glide.with(context)
.load(imageUrl)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
// progressBar.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
// progressBar.setVisibility(View.GONE);
return false;
}
})
.error(mDefaultBackground)
.into(holder.thumbnail);
}else{
//Do whatever you want. Or nothing !!
}
}
#Override
public int getItemCount() {
return postListGlobal.size();
}
class DataViewHolder extends HomeViewHolder {
public DataViewHolder(View itemView) {
super(itemView);
}
}
class ProgressViewHolder extends HomeViewHolder {
public ProgressViewHolder(View itemView) {
super(itemView);
}
}
class HomeViewHolder extends RecyclerView.ViewHolder {
public TextView postTitle, postTime, postWatch, postReaction;
public ImageView thumbnail;
public HomeViewHolder(View itemView) {
super(itemView);
postTitle = itemView.findViewById(R.id.post_title);
postTime = itemView.findViewById(R.id.total_time);
postWatch = itemView.findViewById(R.id.total_watch);
postReaction = itemView.findViewById(R.id.total_reaction);
thumbnail = itemView.findViewById(R.id.thumbnail);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void addNullData() {
}
public void removeNull() {
notifyItemRemoved(postListGlobal.size());
}
public void addData(List<PostList> postLists) {
postListGlobal.addAll(postLists);
notifyDataSetChanged();
}
}
After trying everything, I was still not able to resolve the issue. Any help/suggestions are welcome. Let me know If I left out any needed code--if so I can update it here.
`postListGlobal.add(postList);` below this line add ` homeFragmentAdapter.notifyDataSetChanged();` and remove ` homeFragmentAdapter.removeNull(); homeFragmentAdapter.addData(postListGlobal);homeFragmentAdapter.notifyDataSetChanged();` this code.Because in this case list added twice without notifying datasetchange check with your code by removing this.
postListGlobal.clear(); just clear tha arraylist before add .
postListGlobal.clear() before adding new list to the adapter.
And then notifyDataSetChanged() to let adapter know of the changes.
Here I am sending data from local data base to mysql database server but aly first row data is uploading
Can anyone help me
here i am fetching data from sqlite using model class and display in recyclerview
now i want to send all recyclerview data in ARRAY or any other way to server database
Here 6 images are fetch from sqlite also send to server without setImage in UI directly want to send to Server
Thanks in advance....!!!
Activity Code
public class FetchLocalInsuranceListActivity extends AppCompatActivity {
protected ViewDialog viewDialog;
private RecyclerView recyclerview;
RequestQueue requestQueue;
private MyCustomAdapter myCustomAdapter;
Context context;
DatabaseHelper database;
List<DataModel> datamodel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fetch_local_insurance_list);
context = this;
datamodel = new ArrayList<DataModel>();
viewDialog = new ViewDialog(this);
viewDialog.setCancelable(false);
database = new DatabaseHelper(context);
datamodel = database.getAllSyncData();
recyclerview = (RecyclerView) findViewById(R.id.recycler_view__local_my_insurance);
LinearLayoutManager layoutManager = new LinearLayoutManager(FetchLocalInsuranceListActivity.this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerview.setLayoutManager(layoutManager);
recyclerview.setHasFixedSize(true);
myCustomAdapter = new MyCustomAdapter(datamodel);
recyclerview.setAdapter(myCustomAdapter);
}
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder> {
private List<DataModel> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView farmer_name, tv_Tagging_Date, tv_insurance_id;
protected ImageButton editButton;
public MyViewHolder(View view) {
super(view);
farmer_name = view.findViewById(R.id.text_insured_name);
tv_Tagging_Date = view.findViewById(R.id.tv_Tagging_Date);
tv_insurance_id = view.findViewById(R.id.tv_insurance_id);
editButton = itemView.findViewById(R.id.edit_button);
}
}
public MyCustomAdapter(List<DataModel> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyCustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_local_insurance_list, parent, false);
return new MyCustomAdapter.MyViewHolder(itemView);
}
public void clear() {
int size = this.moviesList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.moviesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(MyCustomAdapter.MyViewHolder holder, final int position) {
final DataModel datum = moviesList.get(position);
Log.e("image", datum.getAnimal_Tail_Photo() + "");
holder.farmer_name.setText("Farmer Name : " + datum.getFarmer_name() + "");
holder.tv_Tagging_Date.setText("Tagging Date : " + datum.getTagging_date() + "");
holder.tv_insurance_id.setText("#SNV_INSURANCE_" + datum.getId() + " ");
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editDataParticularRow(datum);
}
});
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
private void editDataParticularRow(DataModel dataModel) {
Intent intent = new Intent(FetchLocalInsuranceListActivity.this, EditBankAndFarmerActivity.class);
intent.putExtra("BANK_ID", dataModel.getId() + "");
Log.e("id", dataModel.getId() + "");
startActivity(intent);
}
protected final void hideProgressDialog() {
viewDialog.dismiss();
}
protected void showProgressDialog() {
viewDialog.show();
}
protected void showProgressDialog(String message) {
showProgressDialog();
}
public void doNormalPostOperation(final int i) {
requestQueue = Volley.newRequestQueue(FetchLocalInsuranceListActivity.this);
final ProgressDialog progressDialog = new ProgressDialog(FetchLocalInsuranceListActivity.this);
progressDialog.setMessage("Saving Name...");
progressDialog.show();
final StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://thelastoffers.com/snv/webservices/test.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
database.deleteData(Integer.parseInt(datamodel.get(i).getId() + ""));
database.deleteAnimalData(Integer.parseInt(datamodel.get(i).getFarmer_id() + ""));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(FetchLocalInsuranceListActivity.this, "Something went Wrong.. Please Try again..", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
// params.put("id", datamodel.get(i).getINSURANCE_ID() + "");
// REMAINING PARAMS WITH SAME datamodel.get(i) item
params.put("type", "insertOfflineData");
params.put("id", datamodel.get(i).getINSURANCE_ID() + "");
params.put("head_image_blob", String.valueOf(datamodel.get(i).getAnimal_Tag_Photo()));
params.put("farmer_bank_hypo", datamodel.get(i).getFarmer_bank_hypo() + "");
params.put("farmer_name", datamodel.get(i).getFarmer_name() + "");
params.put("farmer_village", datamodel.get(i).getVillage() + "");
params.put("farmer_taluka", datamodel.get(i).getTaluka() + "");
params.put("farmer_district", datamodel.get(i).getDistrict() + "");
params.put("tagging_date", datamodel.get(i).getTagging_date() + "");
Log.e("Data", params + "");
return params;
}
};
requestQueue.add(stringRequest);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.sync_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_sync:
for (int i = 0; i < datamodel.size(); i++) {
doNormalPostOperation(i);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
Database Code
public List<DataModel> getAllSyncData() {
List<DataModel> data = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM FARMER_SYNC_TABLE LEFT JOIN ANIMAL_SYNC_TABLE ON farmer_id = new_insurane_id ORDER BY new_insurane_id DESC";
Cursor cursor = db.rawQuery(query, null);
Log.e("value", query + ";" + " ");
StringBuilder stringBuffer = new StringBuilder();
if (cursor.moveToFirst()) {
do {
DataModel dataModel_1 = new DataModel();
int NEW_INSURANCE_ID_1 = cursor.getInt(cursor.getColumnIndexOrThrow("new_insurane_id"));
String INSURANCE_ID_1 = cursor.getString(cursor.getColumnIndexOrThrow("insurance_id"));
String INSURED_NAME_1 = cursor.getString(cursor.getColumnIndexOrThrow("insured_name"));
String BANKHYPO_NAME_1 = cursor.getString(cursor.getColumnIndexOrThrow("bankhypo_name"));
String FARMER_NAME_1 = cursor.getString(cursor.getColumnIndexOrThrow("farmer_name"));
String VILLAGE_1 = cursor.getString(cursor.getColumnIndexOrThrow("village"));
String TALUKA_1 = cursor.getString(cursor.getColumnIndexOrThrow("taluka"));
String DISTRICT_1 = cursor.getString(cursor.getColumnIndexOrThrow("district"));
String TAGGING_DATE_1 = cursor.getString(cursor.getColumnIndexOrThrow("tagging_date"));
int NEW_ANIMAL_ID = cursor.getInt(cursor.getColumnIndexOrThrow("new_animal_id"));
int FARMER_ID_1 = cursor.getInt(cursor.getColumnIndexOrThrow("farmer_id"));
String TAG_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("tag_no"));
String ANIMAL_EAR_POSITION_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_ear_position"));
String ANIMAL_SPECIES_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_species"));
String ANIMAL_BREED_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_breed"));
String ANIMAL_BODY_COLOR_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_body_color"));
String ANIMAL_SHAPE_RIGHT_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_shape_right"));
String ANIMAL_SHAPE_LEFT_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_shape_left"));
String ANIMAL_SWITCH_OF_TAIL_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_sitch_of_tail"));
String AGE_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("age_years"));
String ANIMAL_OTHER_MARKS_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_other_marks"));
String PRAG_STATUS_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("prag_status"));
String NUMBER_OF_LACTATION_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("number_of_lactation"));
String CURRENT_MILK_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("current_milk"));
String SUM_INSURED_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("sum_insured"));
dataModel_1.setId(NEW_INSURANCE_ID_1);
dataModel_1.setINSURANCE_ID(INSURANCE_ID_1);
dataModel_1.setFarmer_insure_name(INSURED_NAME_1);
dataModel_1.setFarmer_bank_hypo(BANKHYPO_NAME_1);
dataModel_1.setFarmer_name(FARMER_NAME_1);
dataModel_1.setVillage(VILLAGE_1);
dataModel_1.setTaluka(TALUKA_1);
dataModel_1.setDistrict(DISTRICT_1);
dataModel_1.setTagging_date(TAGGING_DATE_1);
dataModel_1.setAnimal_id(NEW_ANIMAL_ID);
dataModel_1.setFarmer_id(FARMER_ID_1);
dataModel_1.setTag_no(TAG_COLUMN_1);
dataModel_1.setEar_position(ANIMAL_EAR_POSITION_COLUMN_1);
dataModel_1.setAnimal_species(ANIMAL_SPECIES_COLUMN_1);
dataModel_1.setAnimal_breed(ANIMAL_BREED_COLUMN_1);
dataModel_1.setBody_color(ANIMAL_BODY_COLOR_COLUMN_1);
dataModel_1.setShape_right(ANIMAL_SHAPE_RIGHT_COLUMN_1);
dataModel_1.setShape_left(ANIMAL_SHAPE_LEFT_COLUMN_1);
dataModel_1.setTail_switch(ANIMAL_SWITCH_OF_TAIL_COLUMN_1);
dataModel_1.setAge(AGE_COLUMN_1);
dataModel_1.setOther_marks(ANIMAL_OTHER_MARKS_COLUMN_1);
dataModel_1.setPrag_status(PRAG_STATUS_COLUMN_1);
dataModel_1.setLactations(NUMBER_OF_LACTATION_COLUMN_1);
dataModel_1.setMilk_qty(CURRENT_MILK_COLUMN_1);
dataModel_1.setSum_insured(SUM_INSURED_COLUMN_1);
dataModel_1.setAnimal_Tag_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("tag_image"))));
dataModel_1.setAnimal_Head_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("head_image"))));
dataModel_1.setAnimal_Left_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("left_side_image"))));
dataModel_1.setAnimal_Right_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("right_side_image"))));
dataModel_1.setAnimal_Tail_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("tail_image"))));
dataModel_1.setAnimal_Farmer_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("farmer_image"))));
stringBuffer.append(dataModel_1);
data.add(dataModel_1);
} while (cursor.moveToNext());
}
db.close();
return data;
}
This is a simple problem. You are only using
use for loop to iterate through all items like,
for(int i=0; i<datamodel.size(); i++){
doNormalPostOperation(i)
}
and in doNormalPostOperation method
public void doNormalPostOperation(int i) {
// PREVIOUS CODE
#Override
protected Map<String, String> getParams() {
params.put("id", datamodel.get(i).getINSURANCE_ID() + "");
// REMAINING PARAMS WITH SAME datamodel.get(i) item
}
}
which is causing that issue and only sending first item. You will need to iterate through all items to generate parameters and send to server, or else you can combine them to one json array and modify the code server side.
First you collect the Data from sqltables
/* Collecting Information */
public Cursor getAllData() {
String selectQuery = "Select * from "+TABLE_MEMBER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}
public JSONObject createJsonObject(){
Cursor cursor = getAllData();
JSONObject jobj ;
JSONArray arr = new JSONArray();
cursor.moveToFIrst();
while(cursor.moveToNext()) {
jobj = new JSONObject();
jboj.put("Id", cursor.getInt("Id"));
jboj.put("Name", cursor.getString("Name"));
arr.put(jobj);
}
jobj = new JSONObject();
jobj.put("data", arr);
}
public void postJsonToServer(){
JSONObject js = createJsonObject();
String url = "YOUR -- Post Url";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST,url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
}
You can go through this:
Get all the data which you want to send, via select query and store this data in a array list.
Using GSON library you can convert that arraylist into json data
Now you have to create an API which receive that json data and parse it and insert every record to database.
On the app end you have to hit that API and pass json data to it.
Here is my code, I have to call method getServerResponse() for first time to get store in arraylist and when I scrolls down I have to call method getServerResponseScroll(). I got result and notify adapter but after scrolling down and up data changes position or may be not visible or get changed. I had created custom adapter for chat. Please help me how to sort out this kind of problem.
public class ChatDetailActivity extends AppCompatActivity {
String macAddress;
RecyclerView recyclerView;
Activity context;
ChatAdapter adapter;
EditText etText;
DatabaseAdapter db;
NetClient nc;
EditText edtSend;
Button btnSend;
DataPref mDataPref;
static int page = 0;
SwipeRefreshLayout mSwipeRefreshLayout;
JSONArray chatDetailListJsonArray;
String toId, channelId, toProfilePic, deviceToken, deviceOsType;
static ArrayList<ChatDetailModel> chatDetailModels = new ArrayList<ChatDetailModel>();
// User mchatUSer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_detail);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
edtSend = (EditText) findViewById(R.id.edtSend);
btnSend = (Button) findViewById(R.id.btnSend);
db = new DatabaseAdapter(this);
mDataPref = DataPref.getInstance(this);
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
macAddress = wInfo.getMacAddress();
etText = (EditText) findViewById(R.id.etText);
toId = getIntent().getStringExtra("toId");
channelId = getIntent().getStringExtra("channelId");
toProfilePic = getIntent().getStringExtra("toProfilePic");
deviceToken = getIntent().getStringExtra("deviceToken");
deviceOsType = getIntent().getStringExtra("deviceOsType");
getServerResponse(this);
connectionForSend();
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
}
void getServerResponse(final Context context){
StringRequest strReqNewsList = new StringRequest(Request.Method.POST, Constants.getChatDetailListUrl, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("GetNewsList Response POST " + response);
/*
if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
String message = "";
try {
JSONObject jsonObjectResponse = new JSONObject(response);
String responseStatus = jsonObjectResponse.getString("status");
message = jsonObjectResponse.getString("message");
if (responseStatus.equals("true")) {
chatDetailListJsonArray = jsonObjectResponse.getJSONArray("data");
if(page==0) {
GetChat.getInstance(context).deleteAllTableData("tbl_chat_detail", channelId);
}
// JSONObject chatListJsonObject= new JSONObject(gson.toJson(chatListJsonArray));
ArrayList<ChatDetailModel> chatlistModels = new Gson()
.fromJson(chatDetailListJsonArray.toString(),
new TypeToken<List<ChatDetailModel>>() {
}.getType());
for (int i = 0; i < chatDetailListJsonArray.length(); i++) {
ChatDetailModel chatlistModel = chatlistModels.get(i);
chatlistModel.setChannel_id(channelId);
GetChat.getInstance(context).addChatDetailList(new JSONObject(new Gson().toJson(chatlistModel)));
}
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
}
} catch (JSONException e) {
e.printStackTrace();
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/* if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
error.printStackTrace();
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
// DatabaseAdapter.deleteDatabase(context);
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("to_id", toId);
params.put("from_id", mDataPref.getUserId());
params.put("page",page+"");
params.put("last_sync_date_time", "");
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
strReqNewsList.setRetryPolicy(new DefaultRetryPolicy(40 * 1000, 1, 1.0f));
AppController.getInstance(context).addToRequestQueue(strReqNewsList);
}
void getServerResponseScroll(final Context context) {
StringRequest strReqNewsList = new StringRequest(Request.Method.POST, Constants.getChatDetailListUrl, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("GetNewsList Response POST " + response);
String message = "";
try {
JSONObject jsonObjectResponse = new JSONObject(response);
String responseStatus = jsonObjectResponse.getString("status");
message = jsonObjectResponse.getString("message");
if (responseStatus.equals("true")) {
chatDetailListJsonArray = jsonObjectResponse.getJSONArray("data");
// JSONObject chatListJsonObject= new JSONObject(gson.toJson(chatListJsonArray));
ArrayList<ChatDetailModel> chatlistModels = new Gson()
.fromJson(chatDetailListJsonArray.toString(),
new TypeToken<List<ChatDetailModel>>() {
}.getType());
for (int i = 0; i < chatDetailListJsonArray.length(); i++) {
ChatDetailModel chatlistModel = chatlistModels.get(i);
chatlistModel.setChannel_id(channelId);
GetChat.getInstance(context).addChatDetailList(new JSONObject(new Gson().toJson(chatlistModel)));
}
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
// chatDetailModels.clear();
ArrayList<ChatDetailModel> chatDetailModels1 = new ArrayList<ChatDetailModel>();
chatDetailModels1 = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
chatDetailModels.clear();
chatDetailModels.addAll(chatDetailModels1);
mSwipeRefreshLayout.setRefreshing(false);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/* if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
error.printStackTrace();
// DatabaseAdapter.deleteDatabase(context);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("to_id", toId);
params.put("from_id", mDataPref.getUserId());
params.put("page", page + "");
params.put("last_sync_date_time", "");
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
strReqNewsList.setRetryPolicy(new DefaultRetryPolicy(40 * 1000, 1, 1.0f));
AppController.getInstance(context).addToRequestQueue(strReqNewsList);
}
void implemantation() {
RecyclerView.LayoutManager manager = new LinearLayoutManager(this.getApplicationContext());
recyclerView.setLayoutManager(manager);
adapter = new ChatAdapter(this.getApplicationContext(), chatDetailModels);
recyclerView.setAdapter(adapter);
recyclerView.scrollToPosition(chatDetailModels.size() - 1);
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent i = new Intent(ChatDetailActivity.this, ProfilesDetailActivity.class);
// i.putExtra("profileId",ChatlistModel.get(position).getId());
startActivity(i);
}
#Override
public void onItemLongClick(View view, int position) {
}
}));
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
page++;
getServerResponseScroll(ChatDetailActivity.this);
}
});
}
// Adapter for chat
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ViewHolder> {
private ArrayList<ChatDetailModel> chatDetailModels;
private Context context;
public ChatAdapter(Context context, ArrayList<ChatDetailModel> chatDetailModels) {
this.context = context;
this.chatDetailModels = chatDetailModels;
}
#Override
public ChatAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.chat_lsit_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
if (chatDetailModels.get(position).getFrom_username().equalsIgnoreCase(mDataPref.getUsername())) {
viewHolder.messageTextRight.setText(chatDetailModels.get(position).getMessage());
viewHolder.chatLeftLayout.setVisibility(View.GONE);
if (mDataPref.getProfilePicFullUrl().equals("null") || mDataPref.getProfilePicFullUrl().equals("")) {
viewHolder.fromImageView.setImageResource(R.drawable.default_profile_pic);
} else {
Picasso.with(context).load(mDataPref.getProfilePicFullUrl()).placeholder(R.drawable.default_profile_pic).transform(new CircleTransform()).resize(40, 40).into(viewHolder.fromImageView);
}
} else {
viewHolder.messageTextLeft.setText(chatDetailModels.get(position).getMessage());
viewHolder.chatRightLayout.setVisibility(View.GONE);
if (toProfilePic.equals("null") || toProfilePic.equals("")) {
viewHolder.toImageView.setImageResource(R.drawable.default_profile_pic);
} else {
Picasso.with(context).load(toProfilePic).placeholder(R.drawable.default_profile_pic).transform(new CircleTransform()).resize(40, 40).into(viewHolder.toImageView);
}
}
}
#Override
public int getItemCount() {
return chatDetailModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout chatLeftLayout;
private ImageView toImageView;
private TextView messageTextLeft;
private LinearLayout chatRightLayout;
private TextView messageTextRight;
private ImageView fromImageView;
public ViewHolder(View view) {
super(view);
chatLeftLayout = (LinearLayout) view.findViewById(R.id.chatLeftLayout);
toImageView = (ImageView) view.findViewById(R.id.toImageView);
messageTextLeft = (TextView) view.findViewById(R.id.message_text_left);
chatRightLayout = (LinearLayout) view.findViewById(R.id.chatRightLayout);
messageTextRight = (TextView) view.findViewById(R.id.message_text_right);
fromImageView = (ImageView) view.findViewById(R.id.fromImageView);
}
}
}
}
From onSaveInstanceState documentation:
Called when the LayoutManager should save its state. This is a good time to save your
* scroll position, configuration and anything else that may be required to restore the same
* layout state if the LayoutManager is recreated.
* RecyclerView does NOT verify if the LayoutManager has changed between state save and
* restore. This will let you share information between your LayoutManagers but it is also
* your responsibility to make sure they use the same parcelable class.
To get current state of recyclerview:
private Parcelable recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();
to restore saved instance:
recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);
I need to add my Items one by one to my RcyclerView for example add first item to recyclerView and show then add another item....
I have a volley that connect to a service then get me some data, in this volley I call a method :
private void makeJsonArryReq(String uri) {
userPointList = new ArrayList<>();
orginal = new ArrayList<>();
final JsonArrayRequest req = new JsonArrayRequest(uri,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
orginal = MarketingPoints_JSONParser.FeedOriginal(response.toString(), mUser_Code, ReportActivity.this);
userPointList = MarketingPoints_JSONParser.parseFeed(response.toString(), mUser_Code, ReportActivity.this);
FillList();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Custom Log Error", "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(req, tag_json_arry);
}
when I call this method FillList(); it fill and show first item on RecyclerView,How can I listen to adapter for finalized and call FillList(); again for next item .
My FillList():
public void FillList() {
Geocoder geocoder = new Geocoder(activity, Locale.getDefault());
List<Address> addresses;
StepModel stp = null;
List<StepModel> Step = new ArrayList<>();
if (check < userPointList.size()) {
try {
addresses = geocoder.getFromLocation(userPointList.get(check).getLat(), userPointList.get(check).getLng(), 1);
stp = new StepModel();
stp.setsCity(addresses.get(0).getAdminArea());
stp.setsStreet(addresses.get(0).getThoroughfare());
stp.setSlat(userPointList.get(check).getLat());
stp.setSlng(userPointList.get(check).getLng());
stp.setSdate(userPointList.get(check).getDate());
stp.setStime(userPointList.get(check).getTime());
stp.setsCounts(userPointList.get(check).getCounts());
stp.setSprofilePhoto(userPointList.get(check).getProfilePhoto());
stp.setsUserCode(userPointList.get(check).getUserCode());
Step.add(stp);
} catch (IOException e) {
e.printStackTrace();
}
pointAdapter = new PointsList_Adapter(Step, ReportActivity.this,this, city, street);
Points_Recycler.setAdapter(pointAdapter);
pointAdapter.notifyDataSetChanged();
check++;
}else {
return;
}
}
Explain :
I connect to a service then I get a json then I convert it and store in a List.In my json I have two specific data (Lat and lng) that I should get name country and name street(For example 100 lat lng) then show on recyclerView but it get long time because I should fill recyclerView on by one.
My adapter :
public class PointsList_Adapter extends RecyclerView.Adapter<PointsList_Adapter.ViewHolder> {
int count = 0;
private List<StepModel> mpList;
public static Activity activity;
public static boolean flagItem = true;
public static boolean flagToast = true;
private mstep Mstep;
public PointsList_Adapter(List<StepModel> userCodeList, Activity activity) {
this.mpList = userCodeList;
this.activity = activity;
}
#Override
public PointsList_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.listpoints_cardview, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(PointsList_Adapter.ViewHolder viewHolder, final int position) {
String dateValue = mpList.get(position).getDate();
final String countValue = String.valueOf(mpList.get(position).getCounts());
final Double lat = mpList.get(position).getLat();
final Double lng = mpList.get(position).getLng();
final String userCode = mpList.get(position).getUserCode();
final String time = mpList.get(position).getTime();
final int counts = mpList.get(position).getCounts();
final String city = mpList.get(position).getCity();
final String street = mpList.get(position).getStreet();
viewHolder.txtDate.setText(dateValue);
viewHolder.txtPoints.setText(lat + " , " + lng);
viewHolder.txtTime.setText(time);
viewHolder.txtAddress.setText(city + " , " + street);
viewHolder.txtCount.setText(countValue);
}
#Override
public int getItemCount() {
return mpList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtDate, txtPoints, txtTime, txtAddress, txtCount;
public LinearLayout lLstPoints;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
txtDate = (TextView) itemLayoutView.findViewById(R.id.txtDate);
txtPoints = (TextView) itemLayoutView.findViewById(R.id.txtPoints);
txtTime = (TextView) itemLayoutView.findViewById(R.id.txtTime);
txtAddress = (TextView) itemLayoutView.findViewById(R.id.txtAddress);
txtCount = (TextView) itemLayoutView.findViewById(R.id.txtCount);
lLstPoints = (LinearLayout) itemLayoutView.findViewById(R.id.lLstPoints);
}
}
}
Please add below method in your adapter:
public reloadList(ArrayList<String> mpList) {
this.mpList.addAll(mpList);
}
When you want to update list or want to add one more item in your listview, use below code:
public void FillList() {
Geocoder geocoder = new Geocoder(activity, Locale.getDefault());
List<Address> addresses;
StepModel stp = null;
List<StepModel> Step = new ArrayList<>();
if (check < userPointList.size()) {
try {
addresses = geocoder.getFromLocation(userPointList.get(check).getLat(), userPointList.get(check).getLng(), 1);
stp = new StepModel();
stp.setsCity(addresses.get(0).getAdminArea());
stp.setsStreet(addresses.get(0).getThoroughfare());
stp.setSlat(userPointList.get(check).getLat());
stp.setSlng(userPointList.get(check).getLng());
stp.setSdate(userPointList.get(check).getDate());
stp.setStime(userPointList.get(check).getTime());
stp.setsCounts(userPointList.get(check).getCounts());
stp.setSprofilePhoto(userPointList.get(check).getProfilePhoto());
stp.setsUserCode(userPointList.get(check).getUserCode());
Step.add(stp);
} catch (IOException e) {
e.printStackTrace();
}
// Just update your list and call notifyDataSetChanged()
pointAdapter .reloadList(Step);
pointAdapter .notifyDataSetChanged();
check++;
}else {
return;
}
}
Initialize your adapter as below:
ArrayList<StepModel> userCodeList = new ArrayList<StepModel>();
pointAdapter = new PointsList_Adapter(userCodeList , activity) ;
Thank You.
After retrieving all data from server at once, inside Filllist() method you should use for, while or do..while loops to iterate your code.You have used if conditional loop that will run only once.
Else, you can create a method inside adapter to add item to your list and then call notifydatasetchanged() method there.
public void add(Object obj){
mArraylist.add(obj);
notifyDataSetChanged();
}
I'm implementing an endless data loading for a RecyclerView. When software detects that last item is going to be shown, it downloads new items and call to the loadMoreData() function but new dataset is not showing.
When I called notifyDataSetChanged() so nothing to be happened.
I have only one solution that is refresh the view is to set again the adapter but problem is that the recyclerview returns to the first position then again recyclerview scrolled up from the first position to last position.
RecyclerViewActivity.java
RecyclerView rv;
DatabaseHelpr databaseHelpr;
RVAdapter adapter;
LocationFinder locationfinder;
Location currentLocation;
ArrayList<ServiceModel> childList, list;
private int MainService_ID, city_id;
String url2;
ActionBar actionBar;
JSONArray items = null;
Utility utility;
Double lat, longi;
LinearLayoutManager llm;
int counter=0;
ProgressBar progressBar;
private static final String TAG_ITEMS = "items";
private static final String TAG_LOCALITY = "Locality";
private static final String TAG_BUSINESS_ID = "Business_Id";
private static final String TAG_LONGITUDE = "Longitude";
private static final String TAG_BUSINESS_NAME = "Business_Name";
private static final String TAG_LATITUDE = "Latitude";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview_activity);
list = new ArrayList<>();
utility = new Utility(this);
llm = new LinearLayoutManager(this);
Bundle bundle=getIntent().getExtras();
MainService_ID=bundle.getInt("service_id");
String mainService_Name = bundle.getString("service_name");
city_id = bundle.getInt("city_id");
lat= bundle.getDouble("lat");
longi=bundle.getDouble("longi");
rv=(RecyclerView)findViewById(R.id.rv);
rv.setLayoutManager(llm);
actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(mainService_Name);
//Here city_id = 8, lat = 18.552954, longi = 73.897200, counter=0, MainService_ID = 5
String url="https://servicedata2-dot-indiacomapi.appspot.com/_ah/api/servicedata/v1/ServiceData?city_id=";
url2 =url+city_id+"&lat="+lat+"&lng="+longi+"&roll="+counter+"&service_id="+MainService_ID;
AsyncHttpClient client = new AsyncHttpClient();
progressBar=(ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.VISIBLE);
client.get(url2, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
String s = new String(response);
try {
JSONObject jsonObj = new JSONObject(s);
// Getting JSON Array node
items = jsonObj.getJSONArray(TAG_ITEMS);
// looping through All Contacts
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String locality = c.getString(TAG_LOCALITY);
String business_Id = c.getString(TAG_BUSINESS_ID);
String longitude = c.getString(TAG_LONGITUDE);
String latitude = c.getString(TAG_LATITUDE);
String business_Name = c.getString(TAG_BUSINESS_NAME);
locationfinder = new LocationFinder(RecyclerViewActivity.this);
// check if GPS enabled
if (locationfinder.canGetLocation()) {
double lat = locationfinder.getLatitude();
double longi = locationfinder.getLongitude();
currentLocation = new Location("");
currentLocation.setLatitude(lat);
currentLocation.setLongitude(longi);
} else {
locationfinder.showSettingsAlert();
}
Location savedLocation = new Location("databaseLocation");
savedLocation.setLatitude(Double.parseDouble(latitude));
savedLocation.setLongitude(Double.parseDouble(longitude));
Double difference = currentLocation.distanceTo(savedLocation) * (0.001);
difference = Double.parseDouble(new DecimalFormat("##.##").format(difference));
String newDifference = String.valueOf(difference) + " km";
ServiceModel serviceModel = new ServiceModel(business_Id, business_Name, newDifference, locality);
list.add(serviceModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
adapter = new RVAdapter(RecyclerViewActivity.this, list);
rv.setAdapter(adapter);
rv.addOnScrollListener(new EndlessRecyclerOnScrollListener(llm) {
#Override
public void onLoadMore(int current_page) {
// counter= counter+1;
loadMoreData();
}
});
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
//Toast.makeText(getApplicationContext(),""+statusCode,Toast.LENGTH_LONG).show();
}
});
}
private void loadMoreData() {
counter= counter+1;
//Here city_id = 8, lat = 18.552954, longi = 73.897200, counter=1, MainService_ID = 5
String url="https://servicedata2-dot-indiacomapi.appspot.com/_ah/api/servicedata/v1/ServiceData?city_id=";
url2 =url+city_id+"&lat="+lat+"&lng="+longi+"&roll="+counter+"&service_id="+MainService_ID;
AsyncHttpClient client = new AsyncHttpClient();
progressBar=(ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.VISIBLE);
client.get(url2, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
String s = new String(response);
try {
JSONObject jsonObj = new JSONObject(s);
// Getting JSON Array node
items = jsonObj.getJSONArray(TAG_ITEMS);
// looping through All Contacts
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String locality = c.getString(TAG_LOCALITY);
String business_Id = c.getString(TAG_BUSINESS_ID);
String longitude = c.getString(TAG_LONGITUDE);
String latitude = c.getString(TAG_LATITUDE);
String business_Name = c.getString(TAG_BUSINESS_NAME);
locationfinder = new LocationFinder(RecyclerViewActivity.this);
// check if GPS enabled
if (locationfinder.canGetLocation()) {
double lat = locationfinder.getLatitude();
double longi = locationfinder.getLongitude();
currentLocation = new Location("");
currentLocation.setLatitude(lat);
currentLocation.setLongitude(longi);
} else {
locationfinder.showSettingsAlert();
}
Location savedLocation = new Location("databaseLocation");
savedLocation.setLatitude(Double.parseDouble(latitude));
savedLocation.setLongitude(Double.parseDouble(longitude));
Double difference = currentLocation.distanceTo(savedLocation) * (0.001);
difference = Double.parseDouble(new DecimalFormat("##.##").format(difference));
String newDifference = String.valueOf(difference) + " km";
ServiceModel serviceModel = new ServiceModel(business_Id, business_Name, newDifference, locality);
list.add(serviceModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
//adapter = new RVAdapter(RecyclerViewActivity.this, list);
//rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
}
});
Toast.makeText(this, "Net is present", Toast.LENGTH_SHORT).show();
}
}
RVAdapter.java
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder>{
private final LayoutInflater mInflater;
List<ServiceModel> persons ;
private Context mContext;
public RVAdapter(Context context,List<ServiceModel> persons){
this.mInflater = LayoutInflater.from(context);
this.persons = new ArrayList<>(persons);
this.mContext = context;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
ServiceModel person = persons.get(i);
personViewHolder.businessName.setOnClickListener(clickListener);
personViewHolder.image_url.setOnClickListener(clickListenerImage);
personViewHolder.businessName.setTag(personViewHolder);
personViewHolder.difference.setTag(personViewHolder);
personViewHolder.business_id.setTag(personViewHolder);
personViewHolder.image_url.setTag(personViewHolder);
personViewHolder.locality.setTag(personViewHolder);
personViewHolder.businessName.setText(Html.fromHtml(person.getBusinessname()));
String firstLetter = String.valueOf(person.getBusinessname().charAt(0));
ColorGenerators generator = ColorGenerators.MATERIAL; // or use DEFAULT
int color = generator.getColor(person.getBusinessname());
TextDrawable drawable = TextDrawable.builder().buildRound(firstLetter, color); // radius in px
personViewHolder.image_url.setImageDrawable(drawable);
personViewHolder.difference.setText(Html.fromHtml(person.getNewDiffer()));
personViewHolder.locality.setText(Html.fromHtml(person.getLocality()));
personViewHolder.bind(person);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
PersonViewHolder holder = (PersonViewHolder) view.getTag();
int position = holder.getPosition();
ServiceModel person = persons.get(position);
String businessids = person.getBusinessid();
Intent intent = new Intent(mContext, BusinessInfoActivity.class);
intent.putExtra("businessids", businessids);
mContext.startActivity(intent);
}
};
View.OnClickListener clickListenerImage = new View.OnClickListener() {
#Override
public void onClick(View view) {
PersonViewHolder holder = (PersonViewHolder) view.getTag();
int position = holder.getPosition();
ServiceModel person = persons.get(position);
String businessids = person.getBusinessid();
Intent intent = new Intent(mContext, BusinessInfoActivity.class);
intent.putExtra("businessids", businessids);
mContext.startActivity(intent);
}
};
#Override
public int getItemCount() {
return persons.size();
}
public void animateTo(List<ServiceModel> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateRemovals(List<ServiceModel> newModels) {
for (int i = persons.size() - 1; i >= 0; i--) {
final ServiceModel model = persons.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<ServiceModel> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final ServiceModel model = newModels.get(i);
if (!persons.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(List<ServiceModel> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final ServiceModel model = newModels.get(toPosition);
final int fromPosition = persons.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public ServiceModel removeItem(int position) {
final ServiceModel model = persons.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, ServiceModel model) {
persons.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final ServiceModel model = persons.remove(fromPosition);
persons.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
public static class PersonViewHolder extends RecyclerView.ViewHolder {
protected CardView cv;
protected TextView businessName, difference, business_id, locality;
protected ImageView image_url;
public PersonViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
businessName = (TextView)itemView.findViewById(R.id.business_name);
difference = (TextView)itemView.findViewById(R.id.txtDifferenece);
business_id = (TextView)itemView.findViewById(R.id.business_id);
image_url = (ImageView)itemView.findViewById(R.id.thumbnail);
locality= (TextView)itemView.findViewById(R.id.txtLocality);
}
public void bind(ServiceModel model) {
businessName.setText(model.getBusinessname());
}
}
}
Please help me, How to set notifyDataSetChanged() to the adapter. it is not working in my code. I already checked all answers which is posted on the stackoverflow.
you are setting the new list to the RecyclerView Adapter , set the list in the Adapter:
make a method setItems(list) in adapter and call it before notifyDataSetChanged() and in adapter do
this.persons = new ArrayList<>(persons);
in setItems
add this method in adapter:
public void setItems(List<ServiceModel> persons) {
this.persons = persons;
}
and call it before notifyDataSetChanged() like this:
adapter.setItems(list);
adapter.notifyDataSetChanged();
Issue is in these lines..
adapter = new RVAdapter(RecyclerViewActivity.this, list);
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
You are initialising your adapter every time. No need to reinitialize it.
Just update your arraylist and invoking to adapter.notifyDataSetChanged(); will make it work.
Like #Beena mentioned, you are creating and setting new adapter ever time, in your success response.
One approach would be to create an adapter and set it to the recycler view only for the first time, and then onSuceess() of your api callback, call a method of your adapter.
In, them adapter method, just add that new data in your main arraylist and do notifyItemInserted() instead of notifyDataSetChanged, in this way you will also see the default adding animation of recyclerView.
Every time you fill your list call the method below:
if (adapter != null) // it works second time and later
adapter.notifyDataSetChanged();
else { // it works first time
adapter = new AdapterClass(context,list);
listView.setAdapter(adapter);
}
I solved this with added method in RVAdapter that call notifyDataSetChanged().
Simply in RVAdapter:
public void refreshList(){
notifyDataSetChanged();
}
and call this method in MainActivity when need:
rVAdapter.refreshList();