I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts and when user scrolling on RecyclerView show more 10 post and go to end! in this project i use okHTTP v3, Glide and RecyclerView!
Json link : JSON LINK
I can load first 10 posts, but when scrolling on RecyclerView and show other 10 posts, show me this error :
04-27 15:34:33.599 3249-3249/com.tellfa.colony E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tellfa.colony, PID: 3249
java.lang.IndexOutOfBoundsException: Invalid index 11, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.tellfa.colony.Activities.Main_page$1$1.run(Main_page.java:95)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5349)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
MainActivity codes:
public class Main_page extends AppCompatActivity {
private static final long RIPPLE_DURATION = 250;
private Toolbar toolbar;
private RelativeLayout root;
private ImageView menu_image;
private RecyclerView main_recyclerView;
private MainAdapter2 mAdaper;
private List<MainDataModel> dataModels = new ArrayList<MainDataModel>();
private List<MainDataModel> dataModelsArray;
private Context context;
protected Handler handler;
private RelativeLayout loadLayout;
private LinearLayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
handler = new Handler();
context = getApplicationContext();
loadLayout = (RelativeLayout) findViewById(R.id.main_empty_layout);
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
}
LoadData();
mLayoutManager = new LinearLayoutManager(this);
// Menu
root = (RelativeLayout) findViewById(R.id.main_root);
View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
root.addView(guillotineMenu);
menu_image = (ImageView) toolbar.findViewById(R.id.toolbar_logo);
new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), menu_image)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.build();
// RecyclerView and setData
main_recyclerView = (RecyclerView) findViewById(R.id.main_recycler);
main_recyclerView.setHasFixedSize(true);
main_recyclerView.setLayoutManager(mLayoutManager);
mAdaper = new MainAdapter2(this, main_recyclerView, dataModels);
main_recyclerView.setAdapter(mAdaper);
mAdaper.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
dataModels.add(null);
mAdaper.notifyItemInserted(dataModels.size() - 1);
dataModelsArray = new ArrayList<MainDataModel>();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
dataModels.remove(dataModels.size() - 1);
mAdaper.notifyItemRemoved(dataModels.size());
int start = dataModels.size();
int end = start + 10;
for (int i = start + 1; i <= end; i++) {
dataModels.add(new MainDataModel(dataModelsArray.get(i).getId(),
dataModelsArray.get(i).getTitle(),
dataModelsArray.get(i).getContent(),
dataModelsArray.get(i).getThumbnail()));
mAdaper.notifyItemInserted(dataModels.size());
}
mAdaper.setLoaded();
}
}, 1000);
}
});
}
#Subscribe
public void onEvent(List<MainDataModel> mainInfoModels) {
mAdaper.add(mainInfoModels);
if (dataModels.isEmpty()) {
main_recyclerView.setVisibility(View.GONE);
loadLayout.setVisibility(View.VISIBLE);
} else {
main_recyclerView.setVisibility(View.VISIBLE);
loadLayout.setVisibility(View.GONE);
}
}
private void LoadData() {
MainDataInfo dataInfo = new MainDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getMainDataInfo(this);
}
}
AsyncTask codes:
public class MainDataInfo {
private Context mContext;
private String ServerAddress = ServerIP.getIP();
public void getMainDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "page=1");
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(ServerAddress + "page=1")
.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
JSONObject images=postObject.optJSONObject("thumbnail_images");
JSONObject imagesPair=images.optJSONObject("medium");
int id = postObject.getInt("id");
String title = postObject.getString("title");
String content = postObject.getString("content");
String thumbnail = imagesPair.getString("url");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post title: " + thumbnail);
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(id, title, content, thumbnail));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
}
}
}
}
for load more data i use Interface class : OnLoadMoreListener
Attention : Please don't give me negative points, help me and i really need you helps! thanks all <3 How can i fix it?
Change this code
mAdaper.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
dataModels.add(null);
mAdaper.notifyItemInserted(dataModels.size() - 1);
dataModelsArray = new ArrayList<MainDataModel>();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
dataModels.remove(dataModels.size() - 1);
mAdaper.notifyItemRemoved(dataModels.size());
int start = dataModels.size();
int end = start + 10;
for (int i = start + 1; i <= end; i++) {
dataModels.add(new MainDataModel(dataModelsArray.get(i).getId(),
dataModelsArray.get(i).getTitle(),
dataModelsArray.get(i).getContent(),
dataModelsArray.get(i).getThumbnail()));
mAdaper.notifyItemInserted(dataModels.size());
}
mAdaper.setLoaded();
}
}, 1000);
}
});
to
mAdaper.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
dataModels.add(null);
mAdaper.notifyItemInserted(dataModels.size() - 1);
LoadData(pageNumber);
}
});
and change this method:
#Subscribe
public void onEvent(List<MainDataModel> mainInfoModels) {
mAdaper.add(mainInfoModels);
if (dataModels.isEmpty()) {
main_recyclerView.setVisibility(View.GONE);
loadLayout.setVisibility(View.VISIBLE);
} else {
main_recyclerView.setVisibility(View.VISIBLE);
loadLayout.setVisibility(View.GONE);
}
}
to:
int pageNumber = 1;
#Subscribe
public void onEvent(List mainInfoModels) {
if(dataModels.size()>0){
dataModels.remove(dataModels.size() - 1);
mAdaper.notifyItemRemoved(dataModels.size());
mAdaper.setLoaded();
}
mAdaper.add(mainInfoModels);
mAdapter.notifyDataSetChanged();
pageNumber++;
if (dataModels.isEmpty()) {
main_recyclerView.setVisibility(View.GONE);
loadLayout.setVisibility(View.VISIBLE);
} else {
main_recyclerView.setVisibility(View.VISIBLE);
loadLayout.setVisibility(View.GONE);
}
}
It is just overview as I understand: you are not doing anything with the dataModelsArray.
Check this out hope this helps. As you did not provided all the code
EDIT:
for your Second answer you are saying 10 post are repeatedly showing because you are not passing the page number:
Change this method:
public void getMainDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "page=1");
}
to:
public void getMainDataInfo(Context context, int pageNumber) {
mContext = context;
new getInfo().execute(ServerAddress + "page="+pageNumber);
}
change this method to:
private void LoadData() {
MainDataInfo dataInfo = new MainDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getMainDataInfo(this);
}
to
private void LoadData(int pageNumber) {
MainDataInfo dataInfo = new MainDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getMainDataInfo(this, pageNumber);
}
Change LoadData() to LoadData(pageNumber)
make an integer in your activity class, increment it when you get response and pass incremented pageNumber to this method.
Thank hope it solve you issue. Accept it as answer as others can get idea.
Try This code :
And Delete Don't use your MainDataInfo class. I have implemented that in Main_Page.java itself.
Your Main_Page.java:
public class Main_page extends AppCompatActivity {
private static final long RIPPLE_DURATION = 250;
private Toolbar toolbar;
private RelativeLayout root;
private ImageView menu_image;
private RecyclerView main_recyclerView;
private MainAdapter2 mAdaper;
private List<MainDataModel> dataModels = new ArrayList<MainDataModel>();
protected Handler handler;
private RelativeLayout loadLayout;
private LinearLayoutManager mLayoutManager;
private int pageCount = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
handler = new Handler();
loadLayout = (RelativeLayout) findViewById(R.id.main_empty_layout);
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
}
LoadData(pageCount);
mLayoutManager = new LinearLayoutManager(Main_page.this);
// Menu
root = (RelativeLayout) findViewById(R.id.main_root);
View guillotineMenu = LayoutInflater.from(Main_page.this).inflate(R.layout.menu_layout, null);
root.addView(guillotineMenu);
menu_image = (ImageView) toolbar.findViewById(R.id.toolbar_logo);
new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), menu_image)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.build();
// RecyclerView and setData
main_recyclerView = (RecyclerView) findViewById(R.id.main_recycler);
main_recyclerView.setHasFixedSize(true);
main_recyclerView.setLayoutManager(mLayoutManager);
mAdaper.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
dataModels.add(null);
mAdaper.notifyItemInserted(dataModels.size() - 1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
dataModels.remove(dataModels.size() - 1);
mAdaper.notifyItemRemoved(dataModels.size());
LoadData(++pageCount);
}
}, 1000);
}
});
}
/*
#Subscribe
public void onEvent(List<MainDataModel> mainInfoModels) {
mAdaper.add(mainInfoModels);
if (dataModels.isEmpty()) {
main_recyclerView.setVisibility(View.GONE);
loadLayout.setVisibility(View.VISIBLE);
} else {
main_recyclerView.setVisibility(View.VISIBLE);
loadLayout.setVisibility(View.GONE);
}
}*/
private void LoadData(int pageNumber) {
new APIInfoAsyncTask().execute(ServerAddress + "page=" + pageNumber);
}
private class APIInfoAsyncTask extends AsyncTask<String, Void, List<MainDataModel>> {
private String ou_response;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(Main_page.this);
}
#Override
protected List<MainDataModel> doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
List<MainDataModel> responseData = new ArrayList<>();
Request request = new Request.Builder()
.url(ServerAddress + "page=1")
.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
JSONObject images = postObject.optJSONObject("thumbnail_images");
JSONObject imagesPair = images.optJSONObject("medium");
int id = postObject.getInt("id");
String title = postObject.getString("title");
String content = postObject.getString("content");
String thumbnail = imagesPair.getString("url");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post title: " + thumbnail);
//Use the title and id as per your requirement
responseData.add(new MainDataModel(id, title, content, thumbnail));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return responseData;
}
#Override
protected void onPostExecute(List<MainDataModel> result) {
CustomProcessDialog.dissmis();
dataModels.addAll(result);
mAdaper = new MainAdapter2(Main_page.this, main_recyclerView, dataModels);
main_recyclerView.setAdapter(mAdaper);
}
}
}
Use your adapter class without any edit,And dont use EventBus.
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 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 want show 3 fragments in my Activity and load data from json in any fragments! I want show each json data into one fragment, but in my application show all of data in all fragments!
For example : i want show article data into article fragment, music data into music fragment and more ...
But when running application, show me this error :
FATAL EXCEPTION: main
Process: com.razemovafaghiat.tellfa.android, PID: 1865
org.greenrobot.eventbus.EventBusException: Subscriber class com.razemovafaghiat.tellfa.android.fragments.free_fragment and its super classes have no public methods with the #Subscribe annotation
at org.greenrobot.eventbus.SubscriberMethodFinder.findSubscriberMethods(SubscriberMethodFinder.java:67)
at org.greenrobot.eventbus.EventBus.register(EventBus.java:136)
at com.razemovafaghiat.tellfa.android.fragments.free_fragment.onResume(free_fragment.java:83)
at android.support.v4.app.Fragment.performResume(Fragment.java:2020)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1107)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:664)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:731)
at android.view.View.measure(View.java:17496)
at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1075)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2636)
at android.view.View.measure(View.java:17496)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2031)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1193)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1400)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1078)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5875)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityT
06-06 17:23:29.721 1865-3617/com.razemovafaghiat.tellfa.android E/error: org.json.JSONException: Index 1 out of range [0..1)
06-06 17:23:30.350 1865-3755/com.razemovafaghiat.tellfa.android E/error: org.json.JSONException: Index 1 out of range [0..1)
MyEvent code:
public class MyEvent {
public String fragmentTag ;
private List<DataModel> infoModels = new ArrayList<>();
public MyEvent (String tag,List<DataModel> models){
this.fragmentTag = tag;
this.infoModels = models;
}
}
freeData (AsyncTask) :
public class freeDataInfo {
private Context mContext;
private String ServerAddress = freeServer_IP.getFreeIP();
public void getFreeDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "limit=10");
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<DataModel> infoModels = new ArrayList<>();
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
//CustomProcessDialog.createAndShow(mContext);
dialog = new ProgressDialog(mContext);
this.dialog.setMessage("شکیبا باشید...");
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
//String url = (String) params[0];
Request request = new Request.Builder()
.url(ServerAddress + "limit=10")
.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("result");
for (int i = 0; i <= postsArray.length(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
Log.d("id", String.valueOf(id));
String title = postObject.getString("title");
String description = postObject.getString("description");
String image = postObject.getString("image");
String category = postObject.getString("categoryName");
String date = postObject.getString("publishDate");
Log.d("Data", "Post ID: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post image: " + image);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new DataModel(id, title, description, category, date, image));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", String.valueOf(e));
}
}
} catch (IOException e) {
e.printStackTrace();
Log.e("error2", String.valueOf(e));
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
//CustomProcessDialog.dissmis();
//Stop Progress
if (dialog.isShowing()) {
dialog.dismiss();
}
if (result != null) {
bus.post(new MyEvent("forfragment1", infoModels));
} else {
Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
}
}
}
}
paidData (AsyncTask) :
public class paidDataInfo {
private Context mContext;
private String ServerAddress = paidServer_IP.getPaidIP();
public void getPaidDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "limit=10");
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<DataModel> infoModels = new ArrayList<>();
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
//CustomProcessDialog.createAndShow(mContext);
//infoModels = new ArrayList<>();
// Initiate Progress
dialog = new ProgressDialog(mContext);
this.dialog.setMessage("شکیبا باشید...");
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
//String url = (String) params[0];
Request request = new Request.Builder()
.url(ServerAddress + "limit=10")
.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("result");
infoModels = new ArrayList<>();
for (int i = 0; i <= postsArray.length(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
Log.d("id", String.valueOf(id));
String title = postObject.getString("title");
String description = postObject.getString("full_description");
String image = postObject.getString("image");
String category = postObject.getString("categoryName");
String date = postObject.getString("publishDate");
Log.d("Data", "Post ID: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post Desc: " + description);
Log.d("Data", "Post image: " + image);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new DataModel(id, title, description, category, date, image));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", String.valueOf(e));
}
}
} catch (IOException e) {
e.printStackTrace();
Log.e("error2", String.valueOf(e));
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
//Stop Progress
if (dialog.isShowing()) {
dialog.dismiss();
}
//CustomProcessDialog.dissmis();
if (result != null) {
bus.post(new MyEvent("forfragment2", infoModels));
} else {
Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
}
}
}
}
free Fragment :
public class free_fragment extends Fragment {
private RecyclerView mRecyclerView;
private free_recycler_adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<DataModel> dataModels = new ArrayList<DataModel>();
private Context context;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_free_layout, container, false);
context = getContext();
/* if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}*/
LoadData();
///----- RecyclerView -----
mRecyclerView = (RecyclerView) view.findViewById(R.id.pdf_RecyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter = new free_recycler_adapter(context, dataModels);
mRecyclerView.setAdapter(mAdapter);
return view;
}
#Subscribe
public void onEvent(MyEvent event, List<DataModel> mainInfoModels) {
/* if (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdapter.notifyItemRemoved(dataModels.size());
//mAdapter.setLoaded();
}*/
if (event.fragmentTag.equals("forfragment1")) {
mAdapter.add(mainInfoModels);
mAdapter.notifyDataSetChanged();
}
}
private void LoadData() {
freeDataInfo dataInfo = new freeDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getFreeDataInfo(context);
}
#Override
public void onResume() {
super.onResume();
EventBus.getDefault().register(this);
}
#Override
public void onPause() {
EventBus.getDefault().unregister(this);
super.onPause();
}
}
paid fragment :
public class paid_fragment extends Fragment {
private RecyclerView mRecyclerView;
private paid_recycler_adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<DataModel> dataModels = new ArrayList<DataModel>();
private Context context;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_paid_layout, container, false);
context = getContext();
/* if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}*/
LoadData();
///----- RecyclerView -----
mRecyclerView = (RecyclerView) view.findViewById(R.id.voice_RecyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter = new paid_recycler_adapter(context, dataModels);
mRecyclerView.setAdapter(mAdapter);
return view;
}
#Subscribe
public void onEvent(MyEvent event, List<DataModel> mainInfoModels) {
/* if (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdapter.notifyItemRemoved(dataModels.size());
//mAdapter.setLoaded();
}*/
if (event.fragmentTag.equals("forfragment2")) {
mAdapter.add(mainInfoModels);
mAdapter.notifyDataSetChanged();
}
}
private void LoadData() {
paidDataInfo dataInfo = new paidDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getPaidDataInfo(context);
}
#Override
public void onResume() {
super.onResume();
EventBus.getDefault().register(this);
}
#Override
public void onPause() {
EventBus.getDefault().unregister(this);
super.onPause();
}
}
How can i fix this problem? Thanks all <3
If you are using proguard for your builds. Ensure that, these lines are in your proguard config file in android. (for Flutter project also)
-keepattributes *Annotation*
-keepclassmembers class ** {
#org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
I got the same error, after digging around for some time i discovered the problem was due to a wrong import
i had used
import com.google.common.eventbus.Subscribe;
instead of
import org.greenrobot.eventbus.Subscribe;
hope this will be helpful to someone out there.
remove the list parameter from you onEvent method. instead use the List you already put into the event. that would either require to make the field public in your event or add a getter for the list.
something like this:
public class MyEvent {
public String fragmentTag ;
private List<DataModel> infoModels = new ArrayList();
public MyEvent (String tag,List<DataModel> models){
this.fragmentTag = tag;
this.infoModels = models;
}
public List<DataModel> getInfoModels() {
return infoModels;
}
}
#Subscribe
public void onEvent(MyEvent event) {
List<DataModel> dataModels = event.getInfoModels();
if (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdapter.notifyItemRemoved(dataModels.size());
//mAdapter.setLoaded();
}
if (event.fragmentTag.equals("forfragment2")) {
mAdapter.add(mainInfoModels);
mAdapter.notifyDataSetChanged();
}
}
I load some json data from server and I show them in my app.I use RecyclerView.
I want load 10 items for first time and load 10 other items with scroll.
How can I do it?
I am using this tutorial and this point I cant match tutorial to my code
recyclerview load more
Update
this is my code in activity
public class NewsActivity extends AppCompatActivity {
//--------------------------------
private ProgressDialog pDialog;
//----------------------------------
private String urlJsonArray="http://kazeroon.mosbate16.com/news/news.php";
private static String TAG = ListActivity.class.getSimpleName();
static List<News> mNews = new ArrayList<>();
private int page=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//-------------
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
//----------------
if (isOnline()==true) {
makeJsonArrayRequest_News();
}else
Toast.makeText(getApplicationContext(),
"برای دریافت اطلاعات به اینترنت نیاز دارید.",
Toast.LENGTH_LONG).show();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
private void makeJsonArrayRequest_News() {
showpDialog();
RequestQueue MyRequestQueue = Volley.newRequestQueue(NewsActivity.this);
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, urlJsonArray, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
JSONObject jsonObj = jsonArray.getJSONObject(i);
String id = jsonObj.getString("id");
String title = jsonObj.getString("title");
String shortcontent = jsonObj.getString("shortcontent");
String longcontent = jsonObj.getString("longcontent");
String publicationdate = jsonObj.getString("publicationdate");
String pic = jsonObj.getString("pic");
String diffdate = jsonObj.getString("diffdate");
String src = jsonObj.getString("src");
String link = jsonObj.getString("link");
news.setId(id);
news.setTitle(title);
news.setShortContent(shortcontent);
news.setLongContent(longcontent);
news.setPublicationDate(publicationdate);
news.setPic(pic);
news.setDiffDate(diffdate);
news.setSrc(src);
news.setLink(link);
mNews.add(news);
}
RecyclerView recyclerViewlist = (RecyclerView) findViewById(R.id.newsList);
//tarif layout maneger baraye tarif noe nemayesh
recyclerViewlist.setLayoutManager(new LinearLayoutManager(NewsActivity.this));
//tarif class adapter recyclview
final RVAdapterNews ad = new RVAdapterNews(NewsActivity.this, mNews, recyclerViewlist);
recyclerViewlist.setAdapter(ad);
ad.setOnLoadMoreListener(new ir.kazeroonsara.kazeroon.OnLoadMoreListener() {
#Override
public void onLoadMore() {
Log.e("haint", "Load More");
mNews.add(null);
ad.notifyItemInserted(mNews.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
mNews.remove(mNews.size() - 1);
ad.notifyItemRemoved(mNews.size());
//Load data
//-----------------------------------------------------------------------------------------------
RequestQueue MyRequestQueue = Volley.newRequestQueue(NewsActivity.this);
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, urlJsonArray, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
JSONObject jsonObj = jsonArray.getJSONObject(i);
String id = jsonObj.getString("id");
String title = jsonObj.getString("title");
String shortcontent = jsonObj.getString("shortcontent");
String longcontent = jsonObj.getString("longcontent");
String publicationdate = jsonObj.getString("publicationdate");
String pic = jsonObj.getString("pic");
String diffdate = jsonObj.getString("diffdate");
String src = jsonObj.getString("src");
String link = jsonObj.getString("link");
news.setId(id);
news.setTitle(title);
news.setShortContent(shortcontent);
news.setLongContent(longcontent);
news.setPublicationDate(publicationdate);
news.setPic(pic);
news.setDiffDate(diffdate);
news.setSrc(src);
news.setLink(link);
mNews.add(news);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"ارتباط با سرور برقرار نشد،آخرین اطلاعات دریافتی نمایش داده می شود",
Toast.LENGTH_LONG).show(); }
hidepDialog();
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
Toast.makeText(getApplicationContext(),
"مشکلی در دریافت اطلاعات وجود دارد",
Toast.LENGTH_LONG).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
page=page+1;
MyData.put("page", String.valueOf(page));
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
//----------------------------------------------------------------------------------------------
ad.notifyDataSetChanged();
ad.setLoaded();
}
}, 5000);
}
});
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"ارتباط با سرور برقرار نشد،آخرین اطلاعات دریافتی نمایش داده می شود",
Toast.LENGTH_LONG).show(); }
hidepDialog();
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
Toast.makeText(getApplicationContext(),
"مشکلی در دریافت اطلاعات وجود دارد",
Toast.LENGTH_LONG).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("page", String.valueOf(page));
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
public interface OnLoadMoreListener {
void onLoadMore();
}
}
and this is my code adapter
public class RVAdapterNews extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
//consteraktor ra misazim
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;
private Context context;
private LayoutInflater inflater;
List<News> mNews;
News news=new News();
private RecyclerView mRecyclerViewlist;
public RVAdapterNews(final NewsActivity context, List<News> mNews,RecyclerView recyclerViewlist){
this.context=context;
this.inflater=LayoutInflater.from(context);
this.mNews=mNews;
this.mRecyclerViewlist=recyclerViewlist;
//-------------------------------------------------
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerViewlist.getLayoutManager();
mRecyclerViewlist.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;
}
}
});
}
#Override
public int getItemViewType(int position) {
//return super.getItemViewType(position);
return mNews.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
//--------------------------------------------------------MyViewHolder----------------------------------------------
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//bayad aval yek layout besazim - recycler_layout
//layout ro moarefi mikonim
//View v=inflater.inflate(R.layout.rvnews_layout,parent,false);
// vh=new MyViewHolder(v);
//return vh;
if (viewType == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(context).inflate(R.layout.rvnews_layout, parent, false);
MyViewHolder vh=new MyViewHolder(view);
return vh;
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(context).inflate(R.layout.layout_loading_item, parent, false);
LoadingViewHolder vh2=new LoadingViewHolder(view);
return vh2;
}
return null;
}
//--------------------------------MyViewHolder holder------------------------------------------------------------
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
//itemhaei ke bayad neshan dadeh shavad bayad inja vared shavad
if (holder instanceof MyViewHolder) {
news = mNews.get(position);
final MyViewHolder myViewHolder = (MyViewHolder) holder;
myViewHolder.newsTitle.setText(news.getTitle());
//----------------------
long seconds = Long.parseLong(news.getDiffDate());
//int day = (int) TimeUnit.SECONDS.toDays(seconds);
//long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
//long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
//long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
long minute = seconds / 60;
long hours = minute / 60;
int day = (int) hours / 24;
int week = day / 7;
int month = day / 30;
int year = day / 365;
if (seconds < 60)
myViewHolder.newsDatePublication.setText(seconds + " ثانیه قبل");
else if (seconds >= 60 && seconds < 3600)
myViewHolder.newsDatePublication.setText(minute + " دقیقه قبل");
else if (seconds >= 3600 && seconds < 86400)
myViewHolder.newsDatePublication.setText(hours + " ساعت قبل");
else if (seconds >= 86400 && seconds < 604800)
myViewHolder.newsDatePublication.setText(day + " روز قبل");
else if (seconds >= 604800 && seconds < 2629743)
myViewHolder.newsDatePublication.setText(week + " هفته قبل");
else if (seconds >= 2629743 && seconds < 31556926)
myViewHolder.newsDatePublication.setText(month + " ماه قبل");
else
myViewHolder.newsDatePublication.setText(year + " سال قبل");
//----------------------
//holder.newsDatePublication.setText(newsPublicationDateItems.get(position));
Uri uri = Uri.parse(news.getPic());
Picasso.with(context).load(uri).resize(200, 200).centerCrop().into(myViewHolder.newsPic, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
myViewHolder.newsPic.setImageResource(R.mipmap.ic_default_list);
}
});
myViewHolder.cvNews.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
News news = mNews.get(position);
Intent intent = new Intent(context, NewsViewActivity.class);
intent.putExtra("id", news.getId());
intent.putExtra("title", news.getTitle());
intent.putExtra("shortContent", news.getShortContent());
intent.putExtra("longContent", news.getLongContent());
intent.putExtra("datePublication", news.getPublicationDate());
intent.putExtra("pic", news.getPic());
intent.putExtra("src", news.getSrc());
intent.putExtra("link", news.getLink());
context.startActivity(intent);
}
});
}else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
//tedad itemhara baraye nemayesh midahim
//return mNews.size();
return mNews == null ? 0 : mNews.size();
}
class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public LoadingViewHolder(View itemView) {
super(itemView);
progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
}
}
class MyViewHolder extends RecyclerView.ViewHolder {
//bayad ajzaye layout ro tarif konim
ImageView newsPic;
TextView newsTitle;
TextView newsShortContent;
TextView newsLongContent;
TextView newsDatePublication;
CardView cvNews;
public MyViewHolder(View itemView) {
super(itemView);
newsPic=(ImageView) itemView.findViewById(R.id.ivNewsPic);
newsTitle= (TextView) itemView.findViewById(R.id.txtNewsTitle);
newsDatePublication = (TextView) itemView.findViewById(R.id.txtNewsDatePublication);
cvNews = (CardView) itemView.findViewById(R.id.CVNews);
}
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.mOnLoadMoreListener = mOnLoadMoreListener;
}
public void setLoaded() {
isLoading = false;
}
}
enter image description here
You can follow this website : recyclerview load more
At the and of tutorial you should see a video about working sample
code for activity
public class NewsActivity extends AppCompatActivity {
//--------------------------------
private ProgressDialog pDialog;
//----------------------------------
private String urlJsonArray="http://...../test.php";
private static String TAG = ListActivity.class.getSimpleName();
static List<News> mNews = new ArrayList<>();
private int page=0;
RVAdapterNews ad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//---------------------------------------
ActionBar mActionBar = getSupportActionBar();
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
LinearLayout actionBarLayout = (LinearLayout)getLayoutInflater().inflate(R.layout.actionbar, null);
TextView actionBarTitleview = (TextView)actionBarLayout.findViewById(R.id.tvTitleActionbar);
//----daryafte lable activity
ActivityInfo activityInfo = null;
try {
activityInfo = getPackageManager().getActivityInfo(
getComponentName(), PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String title = activityInfo.loadLabel(getPackageManager())
.toString();
//-------------------------------------
actionBarTitleview.setText(title);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(
ActionBar.LayoutParams.MATCH_PARENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.RIGHT);
mActionBar.setCustomView(actionBarLayout, params);
mActionBar.setDisplayHomeAsUpEnabled(false);
//------------------------------------------
//-------------
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
//----------------
if (isOnline()==true) {
makeJsonArrayRequest_News();
}else
Toast.makeText(getApplicationContext(),
"برای دریافت اطلاعات به اینترنت نیاز دارید.",
Toast.LENGTH_LONG).show();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
private void makeJsonArrayRequest_News() {
showpDialog();
RequestQueue MyRequestQueue = Volley.newRequestQueue(NewsActivity.this);
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, urlJsonArray, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
JSONObject jsonObj = jsonArray.getJSONObject(i);
String id = jsonObj.getString("id");
String title = jsonObj.getString("title");
String shortcontent = jsonObj.getString("shortcontent");
String longcontent = jsonObj.getString("longcontent");
String publicationdate = jsonObj.getString("publicationdate");
String pic = jsonObj.getString("pic");
String diffdate = jsonObj.getString("diffdate");
String src = jsonObj.getString("src");
String link = jsonObj.getString("link");
news.setId(id);
news.setTitle(title);
news.setShortContent(shortcontent);
news.setLongContent(longcontent);
news.setPublicationDate(publicationdate);
news.setPic(pic);
news.setDiffDate(diffdate);
news.setSrc(src);
news.setLink(link);
mNews.add(news);
}
RecyclerView recyclerViewlist = (RecyclerView) findViewById(R.id.newsList);
//tarif layout maneger baraye tarif noe nemayesh
recyclerViewlist.setLayoutManager(new LinearLayoutManager(NewsActivity.this));
//tarif class adapter recyclview
ad = new RVAdapterNews(NewsActivity.this, mNews, recyclerViewlist);
recyclerViewlist.setAdapter(ad);
ad.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
Log.e("haint", "Load More");
mNews.add(null);
ad.notifyItemInserted(mNews.size() - 1);
//Load more data for reyclerview
Log.e("haint", "Load More 2");
//Remove loading item
//mNews.remove(mNews.size() - 1);
//ad.notifyItemRemoved(mNews.size());
//ad.notifyDataSetChanged();
//Load data
//-----------------------------------------------------------------------------------------------
RequestQueue MyRequestQueue = Volley.newRequestQueue(NewsActivity.this);
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, urlJsonArray, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
},3000);
Toast.makeText(getApplicationContext(), "بارگزاری اخبار بیشتر انجام شد", Toast.LENGTH_SHORT).show();
//Remove loading item
mNews.remove(mNews.size() - 1);
ad.notifyItemRemoved(mNews.size());
//ad.notifyDataSetChanged();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
JSONObject jsonObj = jsonArray.getJSONObject(i);
String id = jsonObj.getString("id");
String title = jsonObj.getString("title");
String shortcontent = jsonObj.getString("shortcontent");
String longcontent = jsonObj.getString("longcontent");
String publicationdate = jsonObj.getString("publicationdate");
String pic = jsonObj.getString("pic");
String diffdate = jsonObj.getString("diffdate");
String src = jsonObj.getString("src");
String link = jsonObj.getString("link");
news.setId(id);
news.setTitle(title);
news.setShortContent(shortcontent);
news.setLongContent(longcontent);
news.setPublicationDate(publicationdate);
news.setPic(pic);
news.setDiffDate(diffdate);
news.setSrc(src);
news.setLink(link);
mNews.add(news);
}
ad.setLoaded();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"ارتباط با سرور برقرار نشد،آخرین اطلاعات دریافتی نمایش داده می شود",
Toast.LENGTH_LONG).show(); }
hidepDialog();
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
Toast.makeText(getApplicationContext(),
"مشکلی در دریافت اطلاعات وجود دارد",
Toast.LENGTH_LONG).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
page=page+1;
MyData.put("page", String.valueOf(page));
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
ad.notifyDataSetChanged();
// ad.setLoaded();
}
});
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"ارتباط با سرور برقرار نشد،آخرین اطلاعات دریافتی نمایش داده می شود",
Toast.LENGTH_LONG).show(); }
hidepDialog();
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
Toast.makeText(getApplicationContext(),
"مشکلی در دریافت اطلاعات وجود دارد",
Toast.LENGTH_LONG).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("page", String.valueOf(page));
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
code for adapter
public class RVAdapterNews extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
//consteraktor ra misazim
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;
private Context context;
private LayoutInflater inflater;
List<News> mNews;
News news=new News();
private RecyclerView mRecyclerViewlist;
public RVAdapterNews(final NewsActivity context, List<News> mNews,RecyclerView recyclerViewlist){
this.context=context;
this.inflater=LayoutInflater.from(context);
this.mNews=mNews;
this.mRecyclerViewlist=recyclerViewlist;
//-------------------------------------------------
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerViewlist.getLayoutManager();
mRecyclerViewlist.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;
}
}
});
}
#Override
public int getItemViewType(int position) {
//return super.getItemViewType(position);
return mNews.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//bayad aval yek layout besazim - recycler_layout
//layout ro moarefi mikonim
//View v=inflater.inflate(R.layout.rvnews_layout,parent,false);
// vh=new MyViewHolder(v);
//return vh;
if (viewType == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(context).inflate(R.layout.rvnews_layout, parent, false);
MyViewHolder vh=new MyViewHolder(view);
return vh;
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(context).inflate(R.layout.layout_loading_item, parent, false);
LoadingViewHolder vh2=new LoadingViewHolder(view);
return vh2;
}
return null;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
//itemhaei ke bayad neshan dadeh shavad bayad inja vared shavad
if (holder instanceof MyViewHolder) {
news = mNews.get(position);
final MyViewHolder myViewHolder = (MyViewHolder) holder;
myViewHolder.newsTitle.setText(news.getTitle());
//----------------------
long seconds = Long.parseLong(news.getDiffDate());
//int day = (int) TimeUnit.SECONDS.toDays(seconds);
//long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
//long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
//long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
long minute = seconds / 60;
long hours = minute / 60;
int day = (int) hours / 24;
int week = day / 7;
int month = day / 30;
int year = day / 365;
if (seconds < 60)
myViewHolder.newsDatePublication.setText(seconds + " ثانیه قبل");
else if (seconds >= 60 && seconds < 3600)
myViewHolder.newsDatePublication.setText(minute + " دقیقه قبل");
else if (seconds >= 3600 && seconds < 86400)
myViewHolder.newsDatePublication.setText(hours + " ساعت قبل");
else if (seconds >= 86400 && seconds < 604800)
myViewHolder.newsDatePublication.setText(day + " روز قبل");
else if (seconds >= 604800 && seconds < 2629743)
myViewHolder.newsDatePublication.setText(week + " هفته قبل");
else if (seconds >= 2629743 && seconds < 31556926)
myViewHolder.newsDatePublication.setText(month + " ماه قبل");
else
myViewHolder.newsDatePublication.setText(year + " سال قبل");
//----------------------
//holder.newsDatePublication.setText(newsPublicationDateItems.get(position));
Uri uri = Uri.parse(news.getPic());
Picasso.with(context).load(uri).resize(200, 200).centerCrop().into(myViewHolder.newsPic, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
myViewHolder.newsPic.setImageResource(R.mipmap.ic_default_list);
}
});
myViewHolder.cvNews.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
News news = mNews.get(position);
Intent intent = new Intent(context, NewsViewActivity.class);
intent.putExtra("id", news.getId());
intent.putExtra("title", news.getTitle());
intent.putExtra("shortContent", news.getShortContent());
intent.putExtra("longContent", news.getLongContent());
intent.putExtra("datePublication", news.getPublicationDate());
intent.putExtra("pic", news.getPic());
intent.putExtra("src", news.getSrc());
intent.putExtra("link", news.getLink());
context.startActivity(intent);
}
});
}else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
//tedad itemhara baraye nemayesh midahim
//return mNews.size();
return mNews == null ? 0 : mNews.size();
}
class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public LoadingViewHolder(View itemView) {
super(itemView);
progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
}
}
class MyViewHolder extends RecyclerView.ViewHolder {
//bayad ajzaye layout ro tarif konim
ImageView newsPic;
TextView newsTitle;
TextView newsShortContent;
TextView newsLongContent;
TextView newsDatePublication;
CardView cvNews;
public MyViewHolder(View itemView) {
super(itemView);
newsPic=(ImageView) itemView.findViewById(R.id.ivNewsPic);
newsTitle= (TextView) itemView.findViewById(R.id.txtNewsTitle);
newsDatePublication = (TextView) itemView.findViewById(R.id.txtNewsDatePublication);
cvNews = (CardView) itemView.findViewById(R.id.CVNews);
}
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.mOnLoadMoreListener = mOnLoadMoreListener;
}
public void setLoaded() {
isLoading = false;
}
}
JsonArrayRequest req = new JsonArrayRequest(urlJsonArray,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
for (int i = 0; i < response.length(); i++) {
News news = new News();
JSONObject person = (JSONObject) response.get(i);
String id = person.getString("id");
String title = person.getString("title");
String shortcontent = person.getString("shortcontent");
String longcontent = person.getString("longcontent");
String publicationdate = person.getString("publicationdate");
String pic = person.getString("pic");
String diffdate=person.getString("diffdate");
String src=person.getString("src");
String link=person.getString("link");
news.setId(id);
news.setTitle(title);
news.setShortContent(shortcontent);
news.setLongContent(longcontent);
news.setPublicationDate(publicationdate);
news.setPic(pic);
news.setDiffDate(diffdate);
news.setSrc(src);
news.setLongContent(link);
mNews.add(news);
}
RecyclerView recyclerViewlist=(RecyclerView) findViewById(R.id.newsList);
//tarif class adapter recyclview
RVAdapterNews ad=null;
if(ad==null)
{
ad=new RVAdapterNews(NewsActivity.this,mNews);
recyclerViewlist.setAdapter(ad);
//tarif layout maneger baraye tarif noe nemayesh
recyclerViewlist.setLayoutManager(new LinearLayoutManager(NewsActivity.this));
}
else
{
ad.Add(mActivity, mNews);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"error"`enter code here`,
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
//Toast.makeText(getApplicationContext(),
// error.getMessage(), Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),
"error",
Toast.LENGTH_LONG).show();
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
.
.
IN Adapter make a method Add like below
private ArrayList<News> newsall;
public RVAdapterNews(Activity mActivity, ArrayList<News> news) {
this.mActivity = mActivity;
newsall.addAll(news);
notifyDataSetChanged();
}
I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts and when user scrolling on RecyclerView show more 10 post and go to end! in this project i use okHTTP v3 and RecyclerView!
Json link : JSON LINK
I can load first 10 posts. i want when scrolling on RecyclerView show next 10 post, but show me again first 10 post!
MainActivity codes:
public class Main_page extends AppCompatActivity {
private static final long RIPPLE_DURATION = 250;
private Toolbar toolbar;
private RelativeLayout root;
private ImageView menu_image;
private RecyclerView main_recyclerView;
private MainAdapter2 mAdaper;
private List<MainDataModel> dataModels = new ArrayList<MainDataModel>();
private List<MainDataModel> dataModelsArray;
private Context context;
protected Handler handler;
private RelativeLayout loadLayout;
private LinearLayoutManager mLayoutManager;
private int pageCount = 1;
private String ServerAddress = ServerIP.getIP();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
handler = new Handler();
context = getApplicationContext();
loadLayout = (RelativeLayout) findViewById(R.id.main_empty_layout);
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
}
LoadData(pageCount);
mLayoutManager = new LinearLayoutManager(this);
// Menu
root = (RelativeLayout) findViewById(R.id.main_root);
View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
root.addView(guillotineMenu);
menu_image = (ImageView) toolbar.findViewById(R.id.toolbar_logo);
new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), menu_image)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.build();
// RecyclerView and setData
main_recyclerView = (RecyclerView) findViewById(R.id.main_recycler);
main_recyclerView.setHasFixedSize(true);
main_recyclerView.setLayoutManager(mLayoutManager);
mAdaper = new MainAdapter2(this, main_recyclerView, dataModels);
main_recyclerView.setAdapter(mAdaper);
mAdaper.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
dataModels.add(null);
mAdaper.notifyItemInserted(dataModels.size() - 1);
LoadData(pageCount);
}
});
}
#Subscribe
public void onEvent(List<MainDataModel> mainInfoModels) {
if (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdaper.notifyItemRemoved(dataModels.size());
mAdaper.setLoaded();
}
mAdaper.add(mainInfoModels);
mAdaper.notifyDataSetChanged();
++pageCount;
if (dataModels.isEmpty()) {
main_recyclerView.setVisibility(View.GONE);
loadLayout.setVisibility(View.VISIBLE);
} else {
main_recyclerView.setVisibility(View.VISIBLE);
loadLayout.setVisibility(View.GONE);
}
}
private void LoadData(int pageNumber) {
MainDataInfo dataInfo = new MainDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getMainDataInfo(this, pageNumber);
}
}
AsyncTask code:
public class MainDataInfo {
private Context mContext;
private String ServerAddress = ServerIP.getIP();
public void getMainDataInfo(Context context, int pageNumber) {
mContext = context;
new getInfo().execute(ServerAddress + "page=" + pageNumber);
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(ServerAddress + "page=1")
.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
JSONObject images = postObject.optJSONObject("thumbnail_images");
JSONObject imagesPair = images.optJSONObject("medium");
int id = postObject.getInt("id");
String title = postObject.getString("title");
String content = postObject.getString("content");
String thumbnail = imagesPair.getString("url");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post title: " + thumbnail);
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(id, title, content, thumbnail));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
}
}
}
}
How can show next 10 post when scrolling on RecyclerView instance of show again first 10 post?
I checked your JSON , and when you increase page number there is no result. Please fix it first to show your results in your app.
While this one returning you 10 post
When you set your page number 2 , it is not returning any post, this is why you are seeing everytime first 10 post.
Hope it helps.
You will have to make different pages. One page have data of only 10 blogs. To get information about, Request JSON fro next page when 10th item is shown.
To get item shown info you can use layoutManager.findLastVisbleItem() or lastComletlyVisibleItem().
once requested data is downloaded. There must be method like onRequestComleted() in Volley. notifysetChanged there.