I want to load data from server and show in my application (RecyclerView), for this job, when the application starts it shows 10 posts and when scrolling recyclerView show another post .
I write below codes but when get other 10 posts, not show loading layout! I want when get other 10 posts, first show loading layout then show other 10 posts!
For connect to internet I use Retrofit v2 and for custom Endless methos for recyclerView I use this class : EndLess Class
My Activity codes:
public class Category_page extends AppCompatActivity implements ConnectivityReceiver.ConnectivityReceiverListener {
private static final long RIPPLE_DURATION = 250;
private Toolbar toolbar;
private TextView toolbar_title;
private ImageView toolbar_menuImage;
private Button categoryCheckNet_button;
private RelativeLayout root;
private CategoryAdapter mAdapter;
private RecyclerView cat_recyclerView;
private LinearLayoutManager mLayoutManager;
private RelativeLayout loadLayout, checkNetLayout;
private String catTitle = "";
private Integer catID;
private Bundle bundle;
private int pageCount = 1;
private Context context;
private List<R_CatModel> models;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_page);
// Hide StatusBar color
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
// Initializing
context = Category_page.this;
toolbar = (Toolbar) findViewById(R.id.category_toolbar);
cat_recyclerView = (RecyclerView) findViewById(R.id.category_recycler);
toolbar_title = (TextView) toolbar.findViewById(R.id.toolbar_pages_title);
mLayoutManager = new LinearLayoutManager(this);
root = (RelativeLayout) findViewById(R.id.category_root);
loadLayout = (RelativeLayout) findViewById(R.id.category_empty_layout);
checkNetLayout = (RelativeLayout) findViewById(R.id.category_checkInternet_layout);
categoryCheckNet_button = (Button) checkNetLayout.findViewById(R.id.checkNet_button);
// Toolbar
setSupportActionBar(toolbar);
if (toolbar != null) {
getSupportActionBar().setTitle("");
}
// Receive Data
bundle = getIntent().getExtras();
catID = bundle.getInt("categoryID");
if (bundle != null) {
catTitle = bundle.getString("categoryTitle");
}
if (catTitle != null) {
toolbar_title.setText(catTitle);
}
// Load Data
loadData();
// Load Progress
loadLayout.setVisibility(View.VISIBLE);
// Menu
View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
root.addView(guillotineMenu);
toolbar_menuImage = (ImageView) toolbar.findViewById(R.id.toolbar_pages_logo);
new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), toolbar_menuImage)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.build();
// RecyclerView
cat_recyclerView.setLayoutManager(mLayoutManager);
cat_recyclerView.setHasFixedSize(true);
cat_recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
#Override
public void onLoadMore(int current_page) {
Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
Call<R_CatModelResponse> call = apiInterface.getCatMoreResponse(catID, current_page);
call.enqueue(new Callback<R_CatModelResponse>() {
#Override
public void onResponse(Call<R_CatModelResponse> call, Response<R_CatModelResponse> response) {
if (response != null) {
mAdapter.addNewItem(response.body().getCat_posts());
//loadLayout.setVisibility(View.GONE);
} else {
//loadLayout.setVisibility(View.VISIBLE);
Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
TastyToast.makeText(context, "خطایی رخ داده است", TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
}
#Override
public void onFailure(Call<R_CatModelResponse> call, Throwable t) {
}
});
}
});
}
private void loadData() {
boolean isConnected = ConnectivityReceiver.isConnected();
retrofitData(isConnected);
}
private void retrofitData(boolean isConnect) {
if (isConnect) {
Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
Call<R_CatModelResponse> call = apiInterface.getCatResponse(catID);
call.enqueue(new Callback<R_CatModelResponse>() {
#Override
public void onResponse(Call<R_CatModelResponse> call, Response<R_CatModelResponse> response) {
if (response != null) {
models = response.body().getCat_posts();
mAdapter = new CategoryAdapter(context, cat_recyclerView, models);
cat_recyclerView.setAdapter(mAdapter);
loadLayout.setVisibility(View.GONE);
} else {
//loadLayout.setVisibility(View.VISIBLE);
Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
TastyToast.makeText(context, "خطایی رخ داده است", TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
checkNetLayout.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<R_CatModelResponse> call, Throwable t) {
//loadLayout.setVisibility(View.VISIBLE);
//TastyToast.makeText(context, "لطفا برنامه را مجددا باز کنید", TastyToast.LENGTH_LONG, TastyToast.ERROR);
Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
//Cat_EmptyLayout.setVisibility(View.VISIBLE);
Log.e("CatResponseError", "Error : " + t);
}
});
} else {
//loadLayout.setVisibility(View.GONE);
checkNetLayout.setVisibility(View.VISIBLE);
if (mAdapter != null) {
mAdapter.clear();
cat_recyclerView.setAdapter(mAdapter);
}
categoryCheckNet_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadData();
}
});
}
}
public void post_back(View view) {
onBackPressed();
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onResume() {
super.onResume();
// register connection status listener
MyApplication.getInstance().setConnectivityListener(this);
}
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
retrofitData(isConnected);
}
}
My Adapter codes:
public class CategoryAdapter extends RecyclerView.Adapter {
private List<R_CatModel> mDateSet;
private Context mContext;
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 10;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
public CategoryAdapter(Context context, RecyclerView recyclerView, List<R_CatModel> dataSet) {
this.mContext = context;
this.mDateSet = dataSet;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView
.getLayoutManager();
recyclerView
.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView,
int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager
.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public int getItemViewType(int position) {
return mDateSet.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.post_card_layout, parent, false);
vh = new DataViewHolder(v);
} else {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.progressbar_item, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof DataViewHolder) {
((DataViewHolder) holder).main_post_title.setText(Html.fromHtml(mDateSet.get(position).getTitle()));
Glide.with(mContext)
.load(mDateSet.get(position).getThumbnail_images().getMedium().getUrl())
.placeholder(R.drawable.post_image)
.crossFade()
.override(600, 350)
.into(((DataViewHolder) holder).main_post_image);
((DataViewHolder) holder).main_post_content.setText(Html.fromHtml(mDateSet.get(position).getContent()));
// Convert Date ////////
String date = mDateSet.get(position).getDate();
String[] parts = date.split(" ");
String datePart = parts[0];
String timePart = parts[1];
int year;
int month;
int day;
String[] dateParts = datePart.split("-");
year = Integer.parseInt(dateParts[0]);
month = Integer.parseInt(dateParts[1]);
day = Integer.parseInt(dateParts[2]);
JalaliCalendar.YearMonthDate georgianDate = new JalaliCalendar.YearMonthDate(year, month, day);
JalaliCalendar.YearMonthDate JalaliDate = JalaliCalendar.gregorianToJalali(georgianDate);
String jalaliDateTime = JalaliDate.toString();
((DataViewHolder) holder).main_dateTime.setText(jalaliDateTime);
////////////////////////
((DataViewHolder) holder).main_author.setText(Html.fromHtml(mDateSet.get(position).getCatAuthor().getAuthorName()));
((DataViewHolder) holder).main_author.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
R_CatModel model = mDateSet.get(position);
v.getContext().startActivity(new Intent(v.getContext(), Profile_page.class));
//.putExtra("author", model.getAuthor())
//.putExtra("authorID", model.getAuthorID())
//.putExtra("authorStatus", model.getAuthorStatus()));
}
});
((DataViewHolder) holder).main_category.setText(Html.fromHtml(String.valueOf(mDateSet.get(position).getCategories().get(0).getCatTitle())));
((DataViewHolder) holder).main_category.setTextColor(mContext.getResources().getColor(R.color.colorAccent));
((DataViewHolder) holder).main_post_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getPosition();
R_CatModel model = mDateSet.get(pos);
v.getContext().startActivity(new Intent(v.getContext(), PostShow_page.class)
.putExtra("title", model.getTitle())
.putExtra("image", model.getThumbnail())
.putExtra("content", model.getContent())
.putExtra("dateTime", model.getDate())
//.putExtra("author", model.getAuthor())
.putExtra("category", model.getTitle()));
}
});
} else {
((ProgressViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
}
}
public void setLoaded() {
loading = false;
}
#Override
public int getItemCount() {
return mDateSet.size();
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void addNewItem(List<R_CatModel> newContent) {
int start = this.mDateSet.size();//contents is a List of your items initialize it your constructor
int end = newContent.size();
mDateSet.addAll(newContent);
notifyItemRangeInserted(start + 1, end);
}
public void add(List<R_CatModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<R_CatModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
public class DataViewHolder extends RecyclerView.ViewHolder {
private TextView main_post_title, main_post_content, main_dateTime, main_author, main_category;
private ImageView main_post_image;
public DataViewHolder(final View itemView) {
super(itemView);
main_post_title = (TextView) itemView.findViewById(R.id.post_content_title);
main_post_image = (ImageView) itemView.findViewById(R.id.post_picture_image);
main_post_content = (TextView) itemView.findViewById(R.id.post_content_text);
main_dateTime = (TextView) itemView.findViewById(R.id.post_date_text);
main_author = (TextView) itemView.findViewById(R.id.post_name_text);
main_category = (TextView) itemView.findViewById(R.id.post_category_text);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public AVLoadingIndicatorView progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
}
}
}
My Json :
{
"status": "ok",
"count": 9,
"pages": 3,
"category": {
"id": 1,
"slug": "%d8%b3%d8%b1%da%af%d8%b1%d9%85%db%8c",
"title": "\u0633\u0631\u06af\u0631\u0645\u06cc",
"description": "\u062a\u0648\u06cc \u0627\u06cc\u0646 \u06a9\u0644\u0648\u0646\u06cc \u0647\u0645\u0647 \u0686\u06cc\u0632 \u0648\u0627\u0633\u0647 \u0633\u0631\u06af\u0631\u0645 \u0628\u0648\u062f\u0646 \u0647\u0633\u062a. \u067e\u0633 \u0628\u062f\u0648 \u0628\u0631\u0648 \u062a\u0648\u0634",
"parent": 0,
"post_count": 29
},
"posts": [{
"id": 85,
"type": "post",
"slug": "%d8%b9%d9%86%d9%88%d8%a7%d9%86-%d8%b3%d9%88%d9%85-%d8%a8%d8%b1%d8%a7%db%8c-%d8%b1%d9%81%d8%b1%d8%b4",
"url": "http:\/\/tellfa.com\/tafrihgah\/?p=85",
"status": "publish",
"title": "\u0639\u0646\u0648\u0627\u0646 \u0633\u0648\u0645 \u0628\u0631\u0627\u06cc \u0631\u0641\u0631\u0634",
"title_plain": "\u0639\u0646\u0648\u0627\u0646 \u0633\u0648\u0645 \u0628\u0631\u0627\u06cc \u0631\u0641\u0631\u0634",
"content": "<p>\u062f\u06cc\u06af\u0647 \u0639\u0635\u0628\u0627\u0646\u06cc \u0634\u062f\u0645\u060c \u0686\u0631\u0627 \u0631\u0641\u0631\u0634 \u0646\u0645\u06cc\u06a9\u0646\u0647! :#<\/p>\n",
"excerpt": "<p>\u062f\u06cc\u06af\u0647 \u0639\u0635\u0628\u0627\u0646\u06cc \u0634\u062f\u0645\u060c \u0686\u0631\u0627 \u0631\u0641\u0631\u0634 \u0646\u0645\u06cc\u06a9\u0646\u0647! :#<\/p>\n",
"date": "2016-04-20 15:02:26",
"modified": "2016-04-20 15:02:26",
"categories": [{
"id": 1,
"slug": "%d8%b3%d8%b1%da%af%d8%b1%d9%85%db%8c",
"title": "\u0633\u0631\u06af\u0631\u0645\u06cc",
"description": "\u062a\u0648\u06cc \u0627\u06cc\u0646 \u06a9\u0644\u0648\u0646\u06cc \u0647\u0645\u0647 \u0686\u06cc\u0632 \u0648\u0627\u0633\u0647 \u0633\u0631\u06af\u0631\u0645 \u0628\u0648\u062f\u0646 \u0647\u0633\u062a. \u067e\u0633 \u0628\u062f\u0648 \u0628\u0631\u0648 \u062a\u0648\u0634",
"parent": 0,
"post_count": 29
}],
"tags": [],
"author": {
"id": 1,
"slug": "tellfa",
"name": "\u0645\u062d\u0645\u062f",
"first_name": "",
"last_name": "",
"nickname": "\u0645\u062d\u0645\u062f",
"url": "http:\/\/codesaz.com",
"description": "\u0627\u06cc\u0646 \u0632\u0646\u062f\u06af\u06cc \u0646\u0627\u0645\u0647 \u0645\u0646 \u0627\u0633\u062a",
"avatar": "76"
},
"comments": [],
"attachments": [{
"id": 86,
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024.jpg",
"slug": "wallpapersmania_vol119-024",
"title": "[WallpapersMania]_vol119-024",
"description": "",
"caption": "",
"parent": 85,
"mime_type": "image\/jpeg",
"images": {
"full": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024.jpg",
"width": 1680,
"height": 1050
},
"thumbnail": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-150x150.jpg",
"width": 150,
"height": 150
},
"medium": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-300x188.jpg",
"width": 300,
"height": 188
},
"medium_large": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-768x480.jpg",
"width": 768,
"height": 480
}
}
}],
"comment_count": 0,
"comment_status": "open",
"thumbnail": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-150x150.jpg",
"custom_fields": {},
"thumbnail_size": "thumbnail",
"thumbnail_images": {
"full": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024.jpg",
"width": 1680,
"height": 1050
},
"thumbnail": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-150x150.jpg",
"width": 150,
"height": 150
},
"medium": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-300x188.jpg",
"width": 300,
"height": 188
},
"medium_large": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-768x480.jpg",
"width": 768,
"height": 480
}
}
}
How can I show loading layout when get other 10 posts?
create a layout for loadmore with the progressbar in activity layout and set its visibility to gone , now setVisibility of your loadMore layout to visible programmatically inside public void onLoadMore(int current_page) method and set it back to gone in the response of your webservice(in onResponse and onFailure methods)
load_more.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/load_more"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#AA000000"
android:gravity="center"
android:visibility="gone"
android:padding="5dp">
<ProgressBar
android:id="#+id/more_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/more_progress"
android:padding="5dp"
android:text="Loading results..."
android:textColor="#ffffff"
android:textSize="#dimen/medium_text_size" />
</RelativeLayout>
In your activity xml file include load_more like -
listing_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#color/listing_background"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="#dimen/medium_text_size"
android:gravity="center"
android:id="#+id/noListFound"
android:textColor="#color/orange"
android:text="No List found Please click here to add a new one"
android:visibility="gone"
android:padding="#dimen/header_margin"/>
</RelativeLayout>
<include layout="#layout/load_more"/>
</LinearLayout>
BaseLoadMoreActivity.java
public abstract class BaseLoadMoreActivity extends Activity {
#BindView(R.id.recycleView)
RecyclerView recyclerView;
#BindView(R.id.load_more)
RelativeLayout loadMore;
private LinearLayoutManager ll;
private int page = 1;
private boolean isNoData = false;
private boolean isLoading = false;
private RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy > 0) //check for scroll down
{
int visibleItemCount = ll.getChildCount();
int totalItemCount = ll.getItemCount();
int pastVisiblesItems = ll.findFirstVisibleItemPosition();
if (!isLoading && !isNoData) {
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
loadMore.setVisibility(View.VISIBLE);
page++;
LoadMoreList();
isLoading = true;
}
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ll = new LinearLayoutManager(this);
ll.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(ll);
recyclerView.addOnScrollListener(scrollListener);
}
public abstract void LoadMoreList();
}
Now extends your category_page.java with BaseLoadMoreActivity and change code
#Override
public void LoadMoreList() {
boolean isConnected = ConnectivityReceiver.isConnected();
retrofitData(isConnected);
}
private void retrofitData(boolean isConnect) {
if (isConnect) {
Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
Call<R_CatModelResponse> call = apiInterface.getCatResponse(catID);
call.enqueue(new Callback<R_CatModelResponse>() {
#Override
public void onResponse(Call<R_CatModelResponse> call, Response<R_CatModelResponse> response) {
if (response != null) {
models = response.body().getCat_posts();
mAdapter = new CategoryAdapter(context, cat_recyclerView, models);
cat_recyclerView.setAdapter(mAdapter);
loadMore.setVisibility(View.GONE);
isLoading = false;
} else {
loadMore.setVisibility(View.GONE);
isLoading = false;
Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
TastyToast.makeText(context, "خطایی رخ داده است", TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
checkNetLayout.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<R_CatModelResponse> call, Throwable t) {
loadMore.setVisibility(View.GONE);
isLoading = false;
//TastyToast.makeText(context, "لطفا برنامه را مجددا باز کنید", TastyToast.LENGTH_LONG, TastyToast.ERROR);
Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
//Cat_EmptyLayout.setVisibility(View.VISIBLE);
Log.e("CatResponseError", "Error : " + t);
}
});
} else {
loadMore.setVisibility(View.GONE);
isLoading = false;
checkNetLayout.setVisibility(View.VISIBLE);
if (mAdapter != null) {
mAdapter.clear();
cat_recyclerView.setAdapter(mAdapter);
}
categoryCheckNet_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadData();
}
});
}
}
Please remove code of finding recycleView and setting layout manager of it from
category_page.java as we did it in BaseLoadMoreActivity otherwise code will not work.
I have just provided code for sample. Hope it will help you...
You didn't implement the getItemViewType and getItemCount correctly:
#Override
public int getItemViewType(int position) {
if (position < mDataSet.size()) {
return VIEW_ITEM;
}
return VIEW_PROG;
}
and
#Override
public int getItemCount() {
return mDateSet.size() + 1;
}
additionally replace the notifyItemRangeInserted(start + 1, end); with notifyDataSetChanged(); in addNewItem
EDIT
keep a boolean private boolean hasMore = true in your adapter and edit the getItemCount() like this:
#Override
public int getItemCount() {
if (hasMore)
return mDateSet.size() + 1;
else
return mDataSet.size();
}
You'll have two cases:
1. If you know from your previous response that there aren't anymore items you can load, set your hasMore = false .
2. If you don't know that, then in your Activity when you get the response in onLoadMore if response== null || response.body() == null || response.body().getCat_posts().size() == 0 set hasMore = false.
It all depends on the response you get from the server
Edit
in your adapter add a method
public void setHasMore(boolean hasMore) {
this.hasMore = hasMore;
}
in the onLoadMore
call.enqueue(new Callback<R_CatModelResponse>() {
#Override
public void onResponse(Call<R_CatModelResponse> call, Response<R_CatModelResponse> response) {
if (response != null) {
adapter.setHasMore(response.body().getPages() !=current_page+1)
mAdapter.addNewItem(response.body().getCat_posts());
//loadLayout.setVisibility(View.GONE);
} else {
//loadLayout.setVisibility(View.VISIBLE);
Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
TastyToast.makeText(context, "خطایی رخ داده است", TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
}
#Override
public void onFailure(Call<R_CatModelResponse> call, Throwable t) {
}
});
Related
I'm trying to set recyclerview data from this type of json response but data is not setting into recylerview
Response:
{
"vehicles": [
{
"id": 1,
"vehicle_number": "gj03fn3235",
"driver_id": 4,
"vehicle_type": "3",
"admindata": {
"id": 7,
"email": "chirag.pwt2#gmail.com"
},
"userdata": {
"id": 4,
"email": "keval.pwt#gmail.com"
}
},
{
"id": 2,
"vehicle_number": "gj03fn3236",
"driver_id": 4,
"vehicle_type": "4",
"admindata": {
"id": 7,
"email": "keval.pwt#gmail.com"
},
"userdata": {
"id": 4,
"email": "keval.pwt#gmail.com"
}
}
]
}
I have created a pojo class of response But my data is not setting into recylerview api call successfully but response print in logcat i tried to set vehicle_number and email in recylerview
Here is my java code:
#Override
public void onSuccess(int
statusCode, Header[] headers, JSONObject
response) {
super.onSuccess(statusCode,
headers, response);
try {
Gson gson = new
GsonBuilder().create();
List<VehicleList> list =
gson.fromJson(response.getJSONArray
("vehicles").toString(), new
TypeToken<List<VehicleList>>() {
}.getType());
Log.e("listsize",""+list.size());
if (list.size() == 0) {
txt_error.setVisibility(View.VISIBLE);
} else {
VehiclesDriverAdpter
acceptedRequestAdapter = new
VehiclesDriverAdpter(list);
recyclerView.setAdapter
(acceptedRequestAdapter);
acceptedRequestAdapter.
notifyDataSetChanged();
}
} catch (JSONException e) {
}
}
My Adapter class:
public class VehiclesDriverAdpter extends
RecyclerView.Adapter<VehiclesDriverAdpter.Holder> {
List<VehicleList> list;
List<Vehicle> list1;
FragmentActivity activity;
public VehiclesDriverAdpter(List<VehicleList> list) {
this.list = list;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
return new
Holder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_vehicle, parent, false));
}
#Override
public void onBindViewHolder(final Holder holder, int position) {
final Vehicle pojo1 = list1.get(position);
Log.e("VehicleNumber",""+pojo1.getVehicleNumber());
holder.txt_vehicle_number.setText(pojo1.getVehicleNumber());
holder.txt_vehicle_driver_name.setText(pojo1.getUserdata().getEmail());
holder.drivername.setText(pojo.getDriver_name());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putSerializable("data", pojo1);
VehiclesInfoFragment detailFragment = new
VehiclesInfoFragment();
detailFragment.setArguments(bundle);
((HomeActivity) holder.itemView.getContext()).
changeFragment(detailFragment, "Passenger Information");
}
});
BookFont(holder, holder.txt_vehilce_type);
BookFont(holder, holder.txt_vehicle_driver_name);
BookFont(holder, holder.txt_vehicle_driver_mobile_no);
MediumFont(holder, holder.txt_vehicle_number);
}
#Override
public int getItemCount() {
return list.size();
}
public class Holder extends RecyclerView.ViewHolder {
TextView txt_vehicle_number, txt_vehilce_type, txt_vehicle_driver_name,
txt_vehicle_driver_mobile_no;
CircleImageView img_driver;
public Holder(View itemView) {
super(itemView);
txt_vehicle_number = (TextView)
itemView.findViewById(R.id.txt_vehicle_number);
txt_vehilce_type = (TextView)
itemView.findViewById(R.id.txt_vehilce_type);
txt_vehicle_driver_name = (TextView)
itemView.findViewById(R.id.txt_vehicle_driver_name);
txt_vehicle_driver_mobile_no = (TextView)
itemView.findViewById(R.id.txt_vehicle_driver_mobile_no);
}
}
public void BookFont(Holder holder, TextView view1) {
Typeface font1 =
Typeface.createFromAsset(holder.itemView.getContext().getAssets(),
"font/AvenirLTStd_Book.otf");
view1.setTypeface(font1);
}
public void MediumFont(Holder holder, TextView view) {
Typeface font =
Typeface.createFromAsset(holder.itemView.getContext().getAssets(),
"font/AvenirLTStd_Medium.otf");
view.setTypeface(font);
}
}
Try this one
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
setRecyclerData();
}
});
private void setRecyclerData(){
VehiclesDriverAdpter acceptedRequestAdapter = new VehiclesDriverAdpter(list);
recyclerView.setAdapter(acceptedRequestAdapter);
acceptedRequestAdapter.notifyDataSetChanged();
}
I think you have forgotten to add layout manager on your recyclerView add it in code like this
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getBaseContext());
recyclerView.setLayoutManager(mLayoutManager);
VehiclesDriverAdpter acceptedRequestAdapter = new VehiclesDriverAdpter(list);
recyclerView.setAdapter (acceptedRequestAdapter);
You put data to List<VehicleList> list list, but take it from List<Vehicle> list1;
You can try(but only if you always have one item in VehicleList) something like this
public VehiclesDriverAdpter(List<VehicleList> list) {
if(!list.isEmpty()){
this.list1 = list.get(0);
}
}
Okay , I have an Json I want to parse it to the tabs (if i have 6 string so it means 6 tabs) i'm receiving the data but I can't parse it..
anyone can help ???
public class WallpaperPageActivity extends BaseActivity {
private ViewPager mViewPager;
private TabLayout mTabLayout;
private WallpaperActivityFragmentAdapter wallpaperActivityFragmentAdapter;
private CategoryList resultCategories;
private ArrayList<Category> categoriesTab = new ArrayList<>();
protected ApiInterface service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wallpaper);
service = RestApiClient.getClient();
mViewPager = (ViewPager) findViewById(R.id.activity_wallpapers_content_viewpager);
mTabLayout = (TabLayout) findViewById(R.id.activity_wallpapers_content_tablayout);
getCategoryNames();
mViewPager.setAdapter(new WallpaperActivityFragmentAdapter(getSupportFragmentManager(), this, categoriesTab));
mViewPager.getAdapter().notifyDataSetChanged();
setTablayoutItemsMode(mTabLayout, categoriesTab);
mTabLayout.setupWithViewPager(mViewPager);
setupTabLayout(mTabLayout, categoriesTab);
}
public void getCategoryNames() {
Call<CategoryList> call = service.requestCategoryList("get_categories_wallpaper");
call.enqueue(new Callback<CategoryList>() {
#Override
public void onResponse(Response<CategoryList> response) {
Log.d("wow", "Status Code = " + response.code());
if (response.isSuccess()) {
// request successful (status code 200, 201)
resultCategories = response.body();
for (int i = 0; i < resultCategories.getCategories().size(); i++) {
categoriesTab.add(resultCategories.getCategories().get(i));
}
} else {
Log.d("wow", "error = ");
}
}
#Override
public void onFailure(Throwable t) {
}
});
}
public void setTablayoutItemsMode(TabLayout tabLayout, List<Category> categories) {
if (categories.size() > 3)
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
else {
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
}
}
}
this is the fragment adapter.
public class WallpaperActivityFragmentAdapter extends FragmentPagerAdapter {
private int PAGE_COUNT = 1;
private ArrayList<Category> categoriesTab;
private Context context;
private Bundle bundle;
private WallpaperActivityFragment fragment;
public WallpaperActivityFragmentAdapter(FragmentManager fm, Context context, ArrayList<Category> categoriesTab) {
super(fm);
this.context = context;
this.categoriesTab = categoriesTab;
PAGE_COUNT = categoriesTab.size();
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
fragment = new WallpaperActivityFragment();
bundle = new Bundle();
bundle.putInt("position", position);
fragment.setArguments(bundle);
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
return categoriesTab.get(position).getCategoryName();
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
}
and this is the fragment
public class WallpaperActivityFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.wallpaper_content_fragment,container,false);
}
}
and this is the xml that contains the viewpager and tablayout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tablayout_linear"
android:orientation="horizontal" >
<include layout="#layout/category_btn"/>
<android.support.design.widget.TabLayout
android:id="#+id/activity_wallpapers_content_tablayout"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#FFFFFF"
app:tabGravity="fill"
app:tabMaxWidth="0dp"
app:tabMode="fixed" />
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="#+id/activity_wallpapers_content_viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_below="#+id/tablayout_linear"
android:background="#FFF123" />
I already include it inside activity_wallpaper........... now i cant get the data with retrofit but how to do like (setTabText something like this)
of course this is in the BaseActivity
public void setupTabLayout(TabLayout tabLayout, ArrayList<Category> categoriesTab) {
for (int i = 0; i < tabLayout.getTabCount(); i++) {
RelativeLayout customTab = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.page_content_custom_tab, null);
TextView tabTitle = (TextView) customTab.findViewById(R.id.activity_music_page_content_tab_title);
tabTitle.setTextSize(15);
tabTitle.setText(categoriesTab.get(i).getCategoryName());
tabTitle.setTextColor(ContextCompat.getColor(this, 0));
tabLayout.getTabAt(i).setCustomView(customTab);
}
}
the json i'm getting contains id and tabs title
{
"categories": [
{
"ID": "18",
"CategoryName": "Inside Yerevan"
},
{
"ID": "1",
"CategoryName": "Armenia"
},
{
"ID": "2",
"CategoryName": "National Days"
},
{
"ID": "17",
"CategoryName": "Armenian Taraz"
},
{
"ID": "3",
"CategoryName": "Nature"
},
{
"ID": "4",
"CategoryName": "Animals"
},
{
"ID": "5",
"CategoryName": "Art"
},
{
"ID": "6",
"CategoryName": "Travel"
},
{
"ID": "7",
"CategoryName": "Music"
},
{
"ID": "8",
"CategoryName": "Flowers"
},
{
"ID": "9",
"CategoryName": "Food"
},
{
"ID": "10",
"CategoryName": "Architecture"
},
{
"ID": "11",
"CategoryName": "Retro"
},
{
"ID": "13",
"CategoryName": "Architecture"
},
{
"ID": "14",
"CategoryName": "Funny"
},
{
"ID": "15",
"CategoryName": "National Holida"
},
{
"ID": "16",
"CategoryName": "Sky"
}
]
}
I just wrote my viewpager and tablayout code inside server response and everything works
public class WallpaperPageActivity extends BaseActivity {
private ViewPager mViewPager;
private TabLayout mTabLayout;
private WallpaperActivityFragmentAdapter wallpaperActivityFragmentAdapter;
private CategoryList resultCategories;
private ArrayList<Category> categoriesTab = new ArrayList<>();
protected ApiInterface service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wallpaper);
service = RestApiClient.getClient();
mViewPager = (ViewPager) findViewById(R.id.activity_wallpapers_content_viewpager);
mTabLayout = (TabLayout) findViewById(R.id.activity_wallpapers_content_tablayout);
getCategoryNames();
}
public void getCategoryNames() {
Call<CategoryList> call = service.requestCategoryList("get_categories_wallpaper");
call.enqueue(new Callback<CategoryList>() {
#Override
public void onResponse(Response<CategoryList> response) {
Log.d("wow", "Status Code = " + response.code());
if (response.isSuccess()) {
// request successful (status code 200, 201)
resultCategories = response.body();
for (int i = 0; i < resultCategories.getCategories().size(); i++) {
categoriesTab.add(resultCategories.getCategories().get(i));
mViewPager.setAdapter(new WallpaperActivityFragmentAdapter(getSupportFragmentManager(),WallpaperPageActivity.this, categoriesTab));
mViewPager.getAdapter().notifyDataSetChanged();
setTablayoutItemsMode(mTabLayout, categoriesTab);
mTabLayout.setupWithViewPager(mViewPager);
setupTabLayout(mTabLayout, categoriesTab);
}
} else {
Log.d("wow", "error = ");
}
}
#Override
public void onFailure(Throwable t) {
}
});
}
public void setTablayoutItemsMode(TabLayout tabLayout, List<Category> categories) {
if (categories.size() > 3)
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
else {
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
}
}
}
You are making async call so the app does not know when you did reach the data. Please add mViewPager.getAdapter().notifyDataSetChanged(); in onResponse callback after your for loop
In my app I have got some json data from url. I have deserialize those data in controller class. Now I want to show those image into recyclerview.This recyclerview will be shown in detail activity. I have devided the relative layout into two part. First half is for information and the second half is for a recyclerview. I tried with the follwing code. The problem is I am very new in android developing and I am not getting the correct logic of doing this. I have explained in detail below-
Here is my model class
public class NewsModel {
#Expose
private String id;
#Expose
private String title;
#Expose
private List<AppImage> appImages;
public List<AppImage> getAppImages() {
return appImages;
}
public void setAppImages(List<AppImage> appImages) {
this.appImages = appImages;
}
}
The AppImageClass is
public class AppImage {
#Expose
private String _id;
#Expose
private String alt;
#Expose
private String src;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getAlt() {
return alt;
}
public void setAlt(String alt) {
this.alt = alt;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
}
The adapter class is
public class NewsImageAdapter extends RecyclerView.Adapter<NewsImageAdapter.ImageHolder> {
private Context context;
private List<NewsModel> imageObject;
public NewsImageAdapter(Context context, List<NewsModel> imageObject) {
this.context = context;
this.imageObject = imageObject;
}
#Override
public ImageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.newsdetail_image_row,parent,false);
return new ImageHolder(view);
}
#Override
public void onBindViewHolder(ImageHolder holder, int position) {
final NewsModel currentImage=imageObject.get(position);
for (int i = 0; i < currentImage.getAppImages().size() ; i++)
{
AppImage appImage = currentImage.getAppImages().get(i);
Picasso.with(holder.itemView.getContext()).load(appImage.getSrc()).into( holder.images[i] ); }
Picasso.with(holder.itemView.getContext());
}
#Override
public int getItemCount() {
return imageObject.size();
}
public class ImageHolder extends RecyclerView.ViewHolder {
public ImageView images;
public ImageHolder(View itemView) {
super(itemView);
images= itemView.findViewById(R.id.news_image);
}
}
}
In Deatil activity
public class DetailNews extends AppCompatActivity {
private List<NewsModel> newsObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_detail);
setUpUIViews();
//newsObject=getAllImageList();
}
private void setUpUIViews() {
recyclerView = (RecyclerView)findViewById(R.id.image_list);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(DetailNews.this);
recyclerView.setLayoutManager(layoutManager);
adapter = new NewsImageAdapter(this,newsObject );
recyclerView.setAdapter(adapter);
}
private List<NewsImageModel> getAllImageList() {
//how to set image here?
return images;
}
The json data looks like this
[
{ "id": "5925280ec925a9a6dd5173bb",
"title": "Headline",
"appImages": [
{
"alt": "",
"src": "source1",
"_id": "12213"
},
{
"alt": "",
"src": "source2",
"_id": "fdgdg"
},
{
"alt": "",
"src": "source3",
"_id": "fdfdfdf"
},
{
"alt": "",
"src": "source4",
"_id": "599d9018daf57d002c100ffa"
},
{
"alt": "",
"src": "source5",
"_id": "f7879"
}
],
},
{ "id": "5925280ec925a9a6dd5173bb",
"title": "Headline",
"appImages": [
{
"alt": "",
"src": "source1",
"_id": "12213"
},
{
"alt": "",
"src": "source2",
"_id": "fdgdg"
},
{
"alt": "",
"src": "source3",
"_id": "fdfdfdf"
},
{
"alt": "",
"src": "source4",
"_id": "599d9018daf57d002c100ffa"
},
{
"alt": "",
"src": "source5",
"_id": "f7879"
}
],
},
]
You should use one "raw/item" for each image. You don't need use "Picasso" to load the images, you can use something like:
In your RecyclerView.Adapter
.
.
.
#Override
public void onBindViewHolder(ViewHolderCustom viewHolder, final int position) {
viewHolder.setImage("imageUrl");
}
static class ViewHolderCustom extends RecyclerView.ViewHolder{
private final ImageView imageViewPhotoUrl;
ViewHolderCustom(View v) {
super(v);
imageViewPhotoUrl = (ImageView) v.findViewById(R.id.iv_photo_url);
}
void setImage(String photo) {
if (photo != null && !photo.isEmpty())
new DownloadImageTask(imageViewPhotoUrl)
.execute(photo);
}
}
.
.
.
Your DownloadImageTask:
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
private ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urlDisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urlDisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
if (result != null)
bmImage.setImageBitmap(result);
}
}
I want load data from server and show into my application (RecyclerView), for this job when start application i show 10 posts and when scrolling recyclerView show another posts . I write below codes but when get 10 posts not load other posts!
My Json :
{
"status": "ok",
"count": 9,
"pages": 3,
"category": {
"id": 1,
"slug": "%d8%b3%d8%b1%da%af%d8%b1%d9%85%db%8c",
"title": "\u0633\u0631\u06af\u0631\u0645\u06cc",
"description": "\u062a\u0648\u06cc \u0627\u06cc\u0646 \u06a9\u0644\u0648\u0646\u06cc \u0647\u0645\u0647 \u0686\u06cc\u0632 \u0648\u0627\u0633\u0647 \u0633\u0631\u06af\u0631\u0645 \u0628\u0648\u062f\u0646 \u0647\u0633\u062a. \u067e\u0633 \u0628\u062f\u0648 \u0628\u0631\u0648 \u062a\u0648\u0634",
"parent": 0,
"post_count": 29
},
"posts": [{
"id": 85,
"type": "post",
"slug": "%d8%b9%d9%86%d9%88%d8%a7%d9%86-%d8%b3%d9%88%d9%85-%d8%a8%d8%b1%d8%a7%db%8c-%d8%b1%d9%81%d8%b1%d8%b4",
"url": "http:\/\/tellfa.com\/tafrihgah\/?p=85",
"status": "publish",
"title": "\u0639\u0646\u0648\u0627\u0646 \u0633\u0648\u0645 \u0628\u0631\u0627\u06cc \u0631\u0641\u0631\u0634",
"title_plain": "\u0639\u0646\u0648\u0627\u0646 \u0633\u0648\u0645 \u0628\u0631\u0627\u06cc \u0631\u0641\u0631\u0634",
"content": "<p>\u062f\u06cc\u06af\u0647 \u0639\u0635\u0628\u0627\u0646\u06cc \u0634\u062f\u0645\u060c \u0686\u0631\u0627 \u0631\u0641\u0631\u0634 \u0646\u0645\u06cc\u06a9\u0646\u0647! :#<\/p>\n",
"excerpt": "<p>\u062f\u06cc\u06af\u0647 \u0639\u0635\u0628\u0627\u0646\u06cc \u0634\u062f\u0645\u060c \u0686\u0631\u0627 \u0631\u0641\u0631\u0634 \u0646\u0645\u06cc\u06a9\u0646\u0647! :#<\/p>\n",
"date": "2016-04-20 15:02:26",
"modified": "2016-04-20 15:02:26",
"categories": [{
"id": 1,
"slug": "%d8%b3%d8%b1%da%af%d8%b1%d9%85%db%8c",
"title": "\u0633\u0631\u06af\u0631\u0645\u06cc",
"description": "\u062a\u0648\u06cc \u0627\u06cc\u0646 \u06a9\u0644\u0648\u0646\u06cc \u0647\u0645\u0647 \u0686\u06cc\u0632 \u0648\u0627\u0633\u0647 \u0633\u0631\u06af\u0631\u0645 \u0628\u0648\u062f\u0646 \u0647\u0633\u062a. \u067e\u0633 \u0628\u062f\u0648 \u0628\u0631\u0648 \u062a\u0648\u0634",
"parent": 0,
"post_count": 29
}],
"tags": [],
"author": {
"id": 1,
"slug": "tellfa",
"name": "\u0645\u062d\u0645\u062f",
"first_name": "",
"last_name": "",
"nickname": "\u0645\u062d\u0645\u062f",
"url": "http:\/\/codesaz.com",
"description": "\u0627\u06cc\u0646 \u0632\u0646\u062f\u06af\u06cc \u0646\u0627\u0645\u0647 \u0645\u0646 \u0627\u0633\u062a",
"avatar": "76"
},
"comments": [],
"attachments": [{
"id": 86,
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024.jpg",
"slug": "wallpapersmania_vol119-024",
"title": "[WallpapersMania]_vol119-024",
"description": "",
"caption": "",
"parent": 85,
"mime_type": "image\/jpeg",
"images": {
"full": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024.jpg",
"width": 1680,
"height": 1050
},
"thumbnail": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-150x150.jpg",
"width": 150,
"height": 150
},
"medium": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-300x188.jpg",
"width": 300,
"height": 188
},
"medium_large": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-768x480.jpg",
"width": 768,
"height": 480
}
}
}],
"comment_count": 0,
"comment_status": "open",
"thumbnail": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-150x150.jpg",
"custom_fields": {},
"thumbnail_size": "thumbnail",
"thumbnail_images": {
"full": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024.jpg",
"width": 1680,
"height": 1050
},
"thumbnail": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-150x150.jpg",
"width": 150,
"height": 150
},
"medium": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-300x188.jpg",
"width": 300,
"height": 188
},
"medium_large": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-768x480.jpg",
"width": 768,
"height": 480
}
}
}
Api Interface codes:
public interface Retrofit_ApiInterface {
// For load more category
#GET("?json=get_category_posts")
Call<R_CatModelResponse> getCatMoreResponse(#Query("id") Integer id, #Query("page") Integer page);
}
Adapter codes:
public class CategoryAdapter extends RecyclerView.Adapter {
private List<R_CatModel> mDateSet;
private Context mContext;
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 10;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
public CategoryAdapter(Context context, RecyclerView recyclerView, List<R_CatModel> dataSet) {
this.mContext = context;
this.mDateSet = dataSet;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView
.getLayoutManager();
recyclerView
.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView,
int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager
.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public int getItemViewType(int position) {
return mDateSet.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.post_card_layout, parent, false);
vh = new DataViewHolder(v);
} else {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.progressbar_item, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof DataViewHolder) {
((DataViewHolder) holder).main_post_title.setText(Html.fromHtml(mDateSet.get(position).getTitle()));
Glide.with(mContext)
.load(mDateSet.get(position).getThumbnail_images().getMedium().getUrl())
.placeholder(R.drawable.post_image)
.crossFade()
.override(600, 350)
.into(((DataViewHolder) holder).main_post_image);
((DataViewHolder) holder).main_post_content.setText(Html.fromHtml(mDateSet.get(position).getContent()));
// Convert Date ////////
String date = mDateSet.get(position).getDate();
String[] parts = date.split(" ");
String datePart = parts[0];
String timePart = parts[1];
int year;
int month;
int day;
String[] dateParts = datePart.split("-");
year = Integer.parseInt(dateParts[0]);
month = Integer.parseInt(dateParts[1]);
day = Integer.parseInt(dateParts[2]);
JalaliCalendar.YearMonthDate georgianDate = new JalaliCalendar.YearMonthDate(year, month, day);
JalaliCalendar.YearMonthDate JalaliDate = JalaliCalendar.gregorianToJalali(georgianDate);
String jalaliDateTime = JalaliDate.toString();
((DataViewHolder) holder).main_dateTime.setText(jalaliDateTime);
////////////////////////
((DataViewHolder) holder).main_author.setText(Html.fromHtml(mDateSet.get(position).getCatAuthor().getAuthorName()));
((DataViewHolder) holder).main_author.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
R_CatModel model = mDateSet.get(position);
v.getContext().startActivity(new Intent(v.getContext(), Profile_page.class));
//.putExtra("author", model.getAuthor())
//.putExtra("authorID", model.getAuthorID())
//.putExtra("authorStatus", model.getAuthorStatus()));
}
});
((DataViewHolder) holder).main_category.setText(Html.fromHtml(String.valueOf(mDateSet.get(position).getCategories().get(0).getCatTitle())));
((DataViewHolder) holder).main_category.setTextColor(mContext.getResources().getColor(R.color.colorAccent));
((DataViewHolder) holder).main_post_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getPosition();
R_CatModel model = mDateSet.get(pos);
v.getContext().startActivity(new Intent(v.getContext(), PostShow_page.class)
.putExtra("title", model.getTitle())
.putExtra("image", model.getThumbnail())
.putExtra("content", model.getContent())
.putExtra("dateTime", model.getDate())
//.putExtra("author", model.getAuthor())
.putExtra("category", model.getTitle()));
}
});
} else {
((ProgressViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
}
}
public void setLoaded() {
loading = false;
}
#Override
public int getItemCount() {
return mDateSet.size();
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void add(List<R_CatModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<R_CatModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
public class DataViewHolder extends RecyclerView.ViewHolder {
private TextView main_post_title, main_post_content, main_dateTime, main_author, main_category;
private ImageView main_post_image;
public DataViewHolder(final View itemView) {
super(itemView);
main_post_title = (TextView) itemView.findViewById(R.id.post_content_title);
main_post_image = (ImageView) itemView.findViewById(R.id.post_picture_image);
main_post_content = (TextView) itemView.findViewById(R.id.post_content_text);
main_dateTime = (TextView) itemView.findViewById(R.id.post_date_text);
main_author = (TextView) itemView.findViewById(R.id.post_name_text);
main_category = (TextView) itemView.findViewById(R.id.post_category_text);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public AVLoadingIndicatorView progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
}
}
}
Activity and Retrofit codes:
public class Category_page extends AppCompatActivity implements ConnectivityReceiver.ConnectivityReceiverListener {
private static final long RIPPLE_DURATION = 250;
private Toolbar toolbar;
private TextView toolbar_title;
private ImageView toolbar_menuImage;
private Button categoryCheckNet_button;
private RelativeLayout root;
private CategoryAdapter mAdapter;
private RecyclerView cat_recyclerView;
private LinearLayoutManager mLayoutManager;
private RelativeLayout loadLayout, checkNetLayout;
private String catTitle = "";
private Integer catID;
private Bundle bundle;
private int pageCount = 1;
private Context context;
private List<R_CatModel> models;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_page);
// Hide StatusBar color
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
// Initializing
context = Category_page.this;
toolbar = (Toolbar) findViewById(R.id.category_toolbar);
cat_recyclerView = (RecyclerView) findViewById(R.id.category_recycler);
toolbar_title = (TextView) toolbar.findViewById(R.id.toolbar_pages_title);
mLayoutManager = new LinearLayoutManager(this);
root = (RelativeLayout) findViewById(R.id.category_root);
loadLayout = (RelativeLayout) findViewById(R.id.category_empty_layout);
checkNetLayout = (RelativeLayout) findViewById(R.id.category_checkInternet_layout);
categoryCheckNet_button = (Button) checkNetLayout.findViewById(R.id.checkNet_button);
// Toolbar
setSupportActionBar(toolbar);
if (toolbar != null) {
getSupportActionBar().setTitle("");
}
// Receive Data
bundle = getIntent().getExtras();
catID = bundle.getInt("categoryID");
if (bundle != null) {
catTitle = bundle.getString("categoryTitle");
}
if (catTitle != null) {
toolbar_title.setText(catTitle);
}
// Load Data
loadData();
// Load Progress
loadLayout.setVisibility(View.VISIBLE);
// Menu
View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
root.addView(guillotineMenu);
toolbar_menuImage = (ImageView) toolbar.findViewById(R.id.toolbar_pages_logo);
new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), toolbar_menuImage)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.build();
// RecyclerView
cat_recyclerView.setLayoutManager(mLayoutManager);
cat_recyclerView.setHasFixedSize(true);
// Load More data
if (mAdapter != null) {
mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
models.add(null);
mAdapter.notifyItemInserted(models.size() - 1);
retrofitMoreData();
}
});
}
}
private void loadData() {
boolean isConnected = ConnectivityReceiver.isConnected();
retrofitData(isConnected);
}
private void retrofitData(boolean isConnect) {
if (isConnect) {
Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
Call<R_CatModelResponse> call = apiInterface.getCatResponse(catID);
call.enqueue(new Callback<R_CatModelResponse>() {
#Override
public void onResponse(Call<R_CatModelResponse> call, Response<R_CatModelResponse> response) {
if (response != null) {
models = response.body().getCat_posts();
mAdapter = new CategoryAdapter(context, cat_recyclerView, models);
cat_recyclerView.setAdapter(mAdapter);
loadLayout.setVisibility(View.GONE);
} else {
//loadLayout.setVisibility(View.VISIBLE);
Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
TastyToast.makeText(context, "خطایی رخ داده است", TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
checkNetLayout.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<R_CatModelResponse> call, Throwable t) {
//loadLayout.setVisibility(View.VISIBLE);
//TastyToast.makeText(context, "لطفا برنامه را مجددا باز کنید", TastyToast.LENGTH_LONG, TastyToast.ERROR);
Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
//Cat_EmptyLayout.setVisibility(View.VISIBLE);
Log.e("CatResponseError", "Error : " + t);
}
});
} else {
//loadLayout.setVisibility(View.GONE);
checkNetLayout.setVisibility(View.VISIBLE);
if (mAdapter != null) {
mAdapter.clear();
cat_recyclerView.setAdapter(mAdapter);
}
categoryCheckNet_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadData();
}
});
}
}
public void retrofitMoreData() {
if (models.size() > 0) {
mAdapter.remove(models.size() - 1);
mAdapter.notifyItemRemoved(models.size());
mAdapter.setLoaded();
}
mAdapter.add(models);
mAdapter.notifyDataSetChanged();
pageCount++;
Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
Call<R_CatModelResponse> call = apiInterface.getCatMoreResponse(catID, pageCount);
call.enqueue(new Callback<R_CatModelResponse>() {
#Override
public void onResponse(Call<R_CatModelResponse> call, Response<R_CatModelResponse> response) {
if (response != null) {
models = response.body().getCat_posts();
mAdapter = new CategoryAdapter(context, cat_recyclerView, models);
cat_recyclerView.setAdapter(mAdapter);
//loadLayout.setVisibility(View.GONE);
} else {
//loadLayout.setVisibility(View.VISIBLE);
Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
TastyToast.makeText(context, "خطایی رخ داده است", TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
}
#Override
public void onFailure(Call<R_CatModelResponse> call, Throwable t) {
}
});
}
How can i edit my above codes for set lazyLoader ? Please Help me, I really need thi. Thanks all <3
Update : Why does not anyone help me? :(
For loading page ten by ten in Retrofit following structure would be helpful:
1- First of all I recommend use this to make your request cleaner.
2- Instead of implementing onScrollListener use EndlessRecyclerView it's much more better.
3- In onLoadMore(page) (assume using EndlessRecyclerView) call your webService something like bellow:
#Override
public void onLoadMore(int page) {
callWebservice(page);
}
4- In your onResponse add new Items to your adapter:
#Override
public void onResponse(Call<YOUR_OBJECT> call, Response<YOUR_OBJECT> response) {
adapter.addNewItem(response.body());
}
5- Your addNewItem in your Adapter would be like:
public void addNewItem(List<YOUR_OBJECT> newContent) {
int start = this.contents.size();//contents is a List of your items initialize it your constructor
int end = newContent.size();
contents.addAll(newContent);
notifyItemRangeInserted(start + 1, end);
}
I trying to send a volley request to populate recyclerviews but for some reason I can fathom, the recyclerview is not populated. The data is fetched quite alright, I can see that from the logcat.
After loading I just see a blank page, blank and empty page.
These are my codes:
Sample jsoup
{
"found": 4,
"site_ID": 1,
"comments": [
{
"ID": 26934,
"post": {
"ID": 194784,
"type": "post",
"title": "Lorem Ipsum is simply dummy text",
},
"author": {
"email": false,
"avatar_URL": "http://1.gravatar.com/avatar/af61ad05da322fccae2bd02f7062e357?s=96&d=wavatar&r=g",
},
"date": "2016-05-28T02:54:35+01:00",
"content": "<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout</p>\n",
"status": "approved",
},
{
"ID": 26934,
"post": {
"ID": 194784,
"type": "post",
"title": "Contrary to popular belief, Lorem Ipsum",
},
"author": {
"email": false,
"avatar_URL": "http://1.gravatar.com/avatar/af61ad05da322fccae2bd02f7062e357?s=96&d=wavatar&r=g",
},
"date": "2016-05-28T02:54:35+01:00",
"content": "<p>Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia</p>\n",
"status": "approved",
},
{
"ID": 26934,
"post": {
"ID": 194784,
"type": "post",
"title": "Lorem Ipsum is simply dummy text",
},
"author": {
"email": false,
"avatar_URL": "http://1.gravatar.com/avatar/af61ad05da322fccae2bd02f7062e357?s=96&d=wavatar&r=g",
},
"date": "2016-05-28T02:54:35+01:00",
"content": "<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout</p>\n",
"status": "approved",
},
{
"ID": 26934,
"post": {
"ID": 194784,
"type": "post",
"title": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
},
"author": {
"email": false,
"avatar_URL": "http://1.gravatar.com/avatar/af61ad05da322fccae2bd02f7062e357?s=96&d=wavatar&r=g",
},
"date": "2016-05-28T02:54:35+01:00",
"content": "<p>Sed ut porttitor nunc. Cras scelerisque lobortis diam, nec placerat lacus aliquam eu. Ut a eros non libero porta commodo. Nulla odio lectus, vestibulum ut ultrices eget</p>\n",
"status": "approved",
},
]
}
CommentItem
public class CommentItem {
private String comt_name;
private String comt_if_auth;
private String comt_cont;
private String comt_timest;
public String getComt_imageUrl() {
return comt_image_url;
}
public void setComt_imageUrl(String comt_image) {
this.comt_image_url = comt_image;
}
public String getComt_name() {
return comt_name;
}
public void setComt_name(String comt_name) {
this.comt_name = comt_name;
}
public String getComt_if_auth() {
return comt_if_auth;
}
public void setComt_if_auth(String comt_if_auth) {
this.comt_if_auth = comt_if_auth;
}
public String getComt_cont() {
return comt_cont;
}
public void setComt_cont(String comt_cont) {
this.comt_cont = comt_cont;
}
public String getComt_timest() {
return comt_timest;
}
public void setComt_timest(String comt_timest) {
this.comt_timest = comt_timest;
}
}
CommentFragment
public class CommentFragment extends Fragment {
private final String TAG = "CommentFragment";
private ProgressBar mProgressBar;
private TextView comtHeader;
//Creating a list of comments
private List<CommentItem> mCommentItems;
//Creating views
RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
LinearLayoutManager mLayoutManager;
private String comtUrl;
public CommentFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreate View called");
comtUrl = getArguments().getString("commentUrl");
Log.d(TAG, comtUrl);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_comment, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.comment_recyclerm);
mProgressBar = (ProgressBar) view.findViewById(R.id.comt_prog);
comtHeader = (TextView) view.findViewById(R.id.comt_head);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
loadComment();
mCommentItems = new ArrayList<>();
mRecyclerView.setAdapter(mAdapter);
mAdapter = new CommentAdapter(mCommentItems, getActivity());
return view;
}
private void loadComment() {
Log.d(TAG, "loadComment called");
mProgressBar.setVisibility(View.VISIBLE);
JsonObjectRequest comments = new JsonObjectRequest(comtUrl, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse for loadComment called");
parseComment(response);
if (mProgressBar != null) {
mProgressBar.setVisibility(View.GONE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (mProgressBar != null) {
mProgressBar.setVisibility(View.GONE);
}
}
});
int socketTimeOut = 10000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeOut, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
comments.setRetryPolicy(policy);
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(comments);
}
public void parseComment(JSONObject object) {
Log.d(TAG, "Parsing comments");
try {
String found = object.getString("found");
if (found.equals("1")) {
comtHeader.setText(getString(R.string.comment, found));
} else {
comtHeader.setText(getString(R.string.comments, found));
}
JSONArray commentArray = object.getJSONArray("comments");
for(int i = 0; i<commentArray.length(); i++) {
CommentItem commentItem = new CommentItem();
JSONObject jsonObject;
try {
jsonObject = commentArray.getJSONObject(i);
JSONObject author = jsonObject.getJSONObject("author");
String name = author.getString("name");
commentItem.setComt_name(name);
commentItem.setComt_imageUrl(author.getString("avatar_URL"));
SimpleDateFormat formatDate = new SimpleDateFormat("dd MMM, yy", Locale.getDefault());
SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm", Locale.getDefault());
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String inputDateStr = jsonObject.getString("date");
Log.d(TAG, "comment date is " + inputDateStr);
try {
Date inputDate = inputFormat.parse(inputDateStr);
String commDateStr = formatDate.format(inputDate);
String commTime = formatTime.format(inputDate);
commentItem.setComt_timest(String.format(getResources().getString(R.string.com_time_stamp), commDateStr, commTime));
} catch (ParseException e) {
Log.d(TAG, "Error in Parsing date");
}
String content = jsonObject.getString("content");
commentItem.setComt_cont(content);
mCommentItems.add(commentItem);
} catch (JSONException w) {
w.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
comtHeader.setText(R.string.comment_no);
}
mAdapter.notifyItemRangeChanged(0, mAdapter.getItemCount());
}
}
CommentAdapter
public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.ViewHolder> {
private ImageLoader mImageLoader;
private Context sContext;
//List of comments
#Override
public CommentAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.comment_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
CommentItem commentItem = mCommentItems.get(position);
mImageLoader = VolleyRequest.getInstance(sContext).getImageLoader();
mImageLoader.get(commentItem.getComt_imageUrl(), ImageLoader.getImageListener(holder.mImageView, R.drawable.comt_image, R.drawable.comt_name_error));
holder.mImageView.setImageUrl(commentItem.getComt_imageUrl(), mImageLoader);
holder.comtName.setText(commentItem.getComt_name());
holder.comtContent.setText(commentItem.getComt_cont());
holder.comtTimeStamp.setText(commentItem.getComt_timest());
}
public class ViewHolder extends RecyclerView.ViewHolder {
public CircularNetworkImageView mImageView;
public TextView comtName;
public TextView comtContent;
public TextView comtTimeStamp;
public ViewHolder(View view) {
super(view);
mImageView = (CircularNetworkImageView) view.findViewById(R.id.comt_img);
comtName = (TextView) view.findViewById(R.id.comt_name);
comtContent = (TextView) view.findViewById(R.id.comt_content);
comtTimeStamp = (TextView) view.findViewById(R.id.comt_timestamp);
}
}
private List<CommentItem> mCommentItems;
public CommentAdapter(List<CommentItem> commentItems, Context context) {
super();
//Getting all comments
this.mCommentItems = commentItems;
this.sContext = context;
}
#Override
public int getItemCount() {
return mCommentItems.size();
}
}
comment_item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="#+id/comt_item_recy"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.Abdullq.commenter.CircularNetworkImageView
android:layout_width="40dp"
android:layout_height="40dp"
android.alignParentLeft="true"
android:id="#+id/comt_img"
android.scaleType="centerCrop"
android:background="#drawable/round_button"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/comt_name"
android:layout_toRightOf="#+id/comt_img"
android:textStyle="bold"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/comt_content"
android:layout_below="#+id/comt_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/comt_timestamp"
android:textStyle="italic"
android:layout_below="#+id/comt_content"/>
</RelativeLayout>
frament_comment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="#+id/comment_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/comt_head"/>
<ProgressBar
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/comt_prog"
android:indeterminate="true"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/comment_recyclerm"/>
</LinearLayout>
What's confusing most is that mProgressBar and comtHeader are showing then why is the recyclerview nor displaying the fetched items.
Please, can you tell me where I got it wrong?
probably here:
mRecyclerView.setAdapter(mAdapter);
mAdapter = new CommentAdapter(mCommentItems, getActivity());
move second line before first one :)
after second line mAdapter is new object, so attached to recyclerview one points to old one.