Kmh54 Kmh54 - 2 months ago 22
Android Question

How to load data from server with Retrofit - Android

I want load data from server and show into

recyclerView
, for connection i use
Retrofit2
.

First i load categoryData and it's ok, i can see categoryData. but when click on category post i want load this post data into other activity but when go to this
activity
Show me Error!


I can show Post comments in activity, but when go to Commentactivity show me Force close error :

10-01 14:20:33.765 32415-32415/com.tellfa.colony E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tellfa.colony, PID: 32415
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.tellfa.colony.Adapters.CommentAdapter2.onBindViewHolder(CommentAdapter2.java:43)
at com.tellfa.colony.Adapters.CommentAdapter2.onBindViewHolder(CommentAdapter2.java:21)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5822)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5855)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5091)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4967)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2029)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1414)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3315)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3124)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3568)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1705)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1559)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1468)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.widget.SlidingDrawer.onLayout(SlidingDrawer.java:358)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1077)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1705)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1559)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1468)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1705)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1559)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1468)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15654)
at android.view.ViewGroup.layout(ViewGroup.java:4969)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2102)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1859)
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.Hand


Activity codes:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_show_page);

bindActivity();

// Initialize
favDB = new FavHelper(context);
postShow_favPost = (ShineButton) mToolbar.findViewById(R.id.post_FavImage);
post_cover = (ImageView) findViewById(R.id.postShow_cover_image);
postShow_title = (TextView) findViewById(R.id.postShow_title);
postShow_title2 = (TextView) findViewById(R.id.postShow_titleBig);
//postShow_content = (TextView) findViewById(R.id.postShow_content_text);
postShow_dateTime = (TextView) findViewById(R.id.postShow_man_date_text);
postShow_author = (TextView) findViewById(R.id.postShow_man_author_text);
postShow_category = (TextView) findViewById(R.id.postShow_man_category_text);
title_sliding = (TextView) findViewById(R.id.post_sliding_title);
comment_Recyclerview = (RecyclerView) findViewById(R.id.comment_recyclerView);
post_content_web = (WebView) findViewById(R.id.postShow_content_web);
mLayoutManager = new LinearLayoutManager(this);


//Give Data
Bundle bundle = getIntent().getExtras();

if (bundle != null) {
postID = bundle.getInt("postID");
title = bundle.getString("title");
image = bundle.getString("image");
content = bundle.getString("content");
dateTime = bundle.getString("dateTime");
author = bundle.getString("author");
category = bundle.getString("category");
categoryID = bundle.getString("categoryID");
}

mAppBarLayout.addOnOffsetChangedListener(this);
// Setup comment RecyclerView
comment_Recyclerview.setLayoutManager(mLayoutManager);
comment_Recyclerview.setHasFixedSize(true);
postShow_favPost.init(this);
postShow_favPost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (postShow_favPost.isChecked()) {

/// Add to Database
favDB.insertFAV(context, title, image, content, dateTime, author, category);
} else {

TastyToast.makeText(context, "برای حذفش به علاقه مندی ها برو", TastyToast.LENGTH_LONG, TastyToast.WARNING);
}
}
});

if (favDB.checkFavPost(title)) {

postShow_favPost.setBtnColor(ContextCompat.getColor(context, R.color.favColorON));
postShow_favPost.setBtnFillColor(ContextCompat.getColor(context, R.color.favColorOFF));
} else {

postShow_favPost.setBtnColor(ContextCompat.getColor(context, R.color.favColorOFF));
postShow_favPost.setBtnFillColor(ContextCompat.getColor(context, R.color.favColorON));
}

//mToolbar.inflateMenu(R.menu.post_menu);
mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {

switch (item.getItemId()) {
case R.id.menu_share:

break;
}
return true;
}
});

startAlphaAnimation(mTitle, 0, View.INVISIBLE);

// Set Data into views
if (title != null) {
postShow_title.setText(title);
postShow_title2.setText(title);
title_sliding.setText(getResources().getString(R.string.comment_title) + " " + title);
}
loadPostProgressDialog.createAndShow(this);
if (image != null) {
Glide.with(this)
.load(image)
.placeholder(R.drawable.post_image)
.listener(new RequestListener<String, GlideDrawable>() {
@Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
return false;
}

@Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target,
boolean isFromMemoryCache, boolean isFirstResource) {
loadPostProgressDialog.dissmis();
return false;
}
})
.into(post_cover);
}

if (content != null) {
//postShow_content.setText(Html.fromHtml(content));

post_content_web.getSettings().setJavaScriptEnabled(true);

WebSettings settings = post_content_web.getSettings();
settings.setDefaultTextEncodingName("utf-8");

post_content_web.loadData(content, "text/html; charset=utf-8", "utf-8");
}
if (dateTime != null) {
postShow_dateTime.setText(dateTime);
}
if (author != null) {
postShow_author.setText(author);
}
if (category != null) {
postShow_category.setText(category);
}

post_cover.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

BlurBehind.getInstance().execute(PostShow_page.this, new OnBlurCompleteListener() {
@Override
public void onBlurComplete() {
startActivity(new Intent(PostShow_page.this, DialogImage_page.class)
.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
.putExtra("imageCover", image));

}
});
}
});
postShow_category.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (categoryID != null) {
startActivity(new Intent(PostShow_page.this, Category_page.class)
.putExtra("categoryID", categoryID)
.putExtra("categoryTitle", category));
}
}
});
//Sliding Up
slideHandleButton = (ImageView) findViewById(R.id.image_sliding);
slidingDrawer = (SlidingDrawer) findViewById(R.id.SlidingDrawer);
slidingDrawer.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener() {

@Override
public void onDrawerOpened() {
slideHandleButton.setImageResource(R.drawable.ic_down_arrow_sliding);
title_sliding.setText(getResources().getString(R.string.comment_title) + " " + title);

// Load Comment data
bindData();

}
});
slidingDrawer.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() {

@Override
public void onDrawerClosed() {
slideHandleButton.setImageResource(R.drawable.ic_up_arrow_sliding);
title_sliding.setText(getResources().getString(R.string.comment_title) + " " + title);
}
});
}

private void bindActivity() {
mToolbar = (Toolbar) findViewById(R.id.postShow_toolbar);
mTitle = (TextView) findViewById(R.id.postShow_title);
mTitleContainer = (LinearLayout) findViewById(R.id.postShow_linearlayout_title);
mAppBarLayout = (AppBarLayout) findViewById(R.id.postShow_appBar);
}

private void bindData() {

// Setup Connect
Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
Call<R_CatModelResponse> call = apiInterface.getCatResponse(postID);

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();

mAdaper = new CommentAdapter2(context, models);
Toast.makeText(PostShow_page.this, "GoTo Adapter", Toast.LENGTH_SHORT).show();
comment_Recyclerview.setAdapter(mAdaper);

}
}

@Override
public void onFailure(Call<R_CatModelResponse> call, Throwable t) {
Toast.makeText(PostShow_page.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
}


Adapter codes:

public class CommentAdapter2 extends RecyclerView.Adapter<CommentAdapter2.ViewHolder> {

private List<R_CatModel> mDataSet;
private Context context;

public CommentAdapter2(Context context, List<R_CatModel> mDataSet) {
this.mDataSet = mDataSet;
this.context = context;
}

@Override
public CommentAdapter2.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.comment_layout, viewGroup, false);
return new ViewHolder(view);
}

@Override
public void onBindViewHolder(CommentAdapter2.ViewHolder viewHolder, int position) {

int pos = viewHolder.getPosition();
R_CatModel model = mDataSet.get(pos);

viewHolder.comment_name.setText(model.getComments().get(1).getCmName());
viewHolder.comment_date.setText(model.getComments().get(4).getCmDate());
viewHolder.comment_content.setText(Html.fromHtml(model.getComments().get(3).getCmContent()));


}

@Override
public int getItemCount() {
return mDataSet.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {

private TextView comment_name, comment_content, comment_date;

public ViewHolder(View view) {
super(view);

comment_name = (TextView) itemView.findViewById(R.id.comment_userName_text);
comment_content = (TextView) itemView.findViewById(R.id.comment_comment_text);
comment_date = (TextView) itemView.findViewById(R.id.comment_date_text);
}
}
}


Show error for this line :

viewHolder.comment_name.setText(model.getComments().get(1).getCmName());
viewHolder.comment_date.setText(model.getComments().get(4).getCmDate());
viewHolder.comment_content.setText(Html.fromHtml(model.getComments().get(3).getCmContent()));


Json:

{
"status": "ok",
"count": 3,
"pages": 1,
"category": {
"id": 1,
"slug": "entertainment",
"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": 3
},
"posts": [{
"id": 2348,
"type": "post",
"slug": "aenean-ligula-mol-stie-viverra3",
"url": "http:\/\/kolony.ir\/1395\/07\/01\/aenean-ligula-mol-stie-viverra3\/",
"status": "publish",
"title": "Aenean ligula mol stie viverra3",
"title_plain": "Aenean ligula mol stie viverra3",
"content": "<h5>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quo modo? Et nemo nimium beatus est. <a href=\"#\">Verum hoc idem saepe faciamus.<\/a> <b>Duo Reges: constructio interrete.<\/b> Suo genere perveniant ad extremum; <i>Sed ille, ut dixi, vitiose.<\/i> Negat esse eam, inquit, propter se expetendam. Quid est, quod ab ea absolvi et perfici debeat?<\/h5>\n<p>Ut pulsi recurrant? Ratio enim nostra consentit, pugnat oratio. Plane idem, inquit, et maxima quidem, qua fieri nulla maior potest. Diodorus, eius auditor, adiungit ad honestatem vacuitatem doloris. Qua igitur re ab deo vincitur, si aeternitate non vincitur?<\/p>\n<ul>\n<li>Superiores tres erant, quae esse possent, quarum est una sola defensa, eaque vehementer.<\/li>\n<li>Istam voluptatem perpetuam quis potest praestare sapienti?<\/li>\n<li>Quia dolori non voluptas contraria est, sed doloris privatio.<\/li>\n<\/ul>\n<p>Non igitur potestis voluptate omnia dirigentes aut tueri aut retinere virtutem. Summus dolor plures dies manere non potest? <a href=\"#\">Strato, physicum se voluit<\/a>, ec vero alia sunt quaerenda contra Carneadeam illam sententiam. Bonum incolumis acies: misera caecitas. Aliter enim nosmet ipsos nosse non possumus.<\/p>\n<h3>Inde igitur, inquit, ordiendum est.<\/h3>\n<p>At, si voluptas esset bonum, desideraret. Aliter philosophos loqui putas oportere? <i>Ratio enim nostra consentit, pugnat oratio.<\/i> <a href=\"#\">Comprehensum, quod cognitum non habet?<\/a> Nam aliquando posse recte fieri dicunt nulla expectata nec quaesita voluptate. Primum quid tu dicis breve? Eam si varietatem diceres, intellegerem, ut etiam non dicente te intellego; Quae qui non vident, nihil umquam magnum ac cognitione dignum amaverunt. <a href=\"#\">Praeclare hoc quidem.<\/a> Quo plebiscito decreta a senatu est consuli quaestio Cn.<br \/>\n<div class=\"blockquote\"><blockquote>Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis. Maecenas malesuada elit lectus felis, malesuada ultricies. Curabitur et ligula. Ut molestie a, ultricies porta urna.<\/blockquote><\/div>\n<br \/>\nMihi vero, inquit, placet agi subtilius et, ut ipse dixisti, pressius. Inquit, an parum disserui non verbis Stoicos a Peripateticis, sed universa re et tota sententia dissidere? Ego vero volo in virtute vim esse quam maximam; Si enim ad populum me vocas, eum. Videamus animi partes, quarum est conspectus illustrior; Et nemo nimium beatus est.<\/p>\n",
"excerpt": "<p>Vitae adipiscing turpis. Aenean ligula nibh, molestie id viverra dapibus at.<\/p>\n",
"date": "\u06f1\u06f3\u06f9\u06f5-\u06f0\u06f7-\u06f0\u06f1 \u06f2\u06f2:\u06f5\u06f8:\u06f1\u06f7",
"modified": "2016-09-22 22:58:17",
"categories": [{
"id": 1,
"slug": "entertainment",
"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": 3
}],
"comments": [{
"id": 10,
"name": "&#1605;&#1581;&#1605;&#1583;",
"url": "",
"date": "2016-09-28 00:00:00",
"content": "<p>&#1578;&#1587;&#1578; &#1662;&#1610;&#1575;&#1605; &#1575;&#1586; &#1587;&#1605;&#1578; &#1576;&#1585;&#1606;&#1575;&#1605;&#1607; &#1606;&#1608;&#1610;&#1587;&#1610;<\/p>\n",
"parent": 0
}, {
"id": 11,
"name": "Mohammad1",
"url": "",
"date": "2016-09-28 00:00:00",
"content": "<p>Test Comment 1<\/p>\n",
"parent": 0
}, {


ModelResponse:

public class R_CatModelResponse {

@SerializedName("status")
public String Cat_status;
@SerializedName("count")
public int Cat_count;
@SerializedName("pages")
public int Cat_pages;
@SerializedName("category")
public Retrofit_ColoniesModel category;
@SerializedName("posts")
public List<R_CatModel> Cat_posts;

public String getCat_status() {
return Cat_status;
}

public void setCat_status(String cat_status) {
Cat_status = cat_status;
}

public int getCat_count() {
return Cat_count;
}

public void setCat_count(int cat_count) {
Cat_count = cat_count;
}

public int getCat_pages() {
return Cat_pages;
}

public void setCat_pages(int cat_pages) {
Cat_pages = cat_pages;
}

public Retrofit_ColoniesModel getCategory() {
return category;
}

public void setCategory(Retrofit_ColoniesModel category) {
this.category = category;
}

public List<R_CatModel> getCat_posts() {
return Cat_posts;
}

public void setCat_posts(List<R_CatModel> cat_posts) {
Cat_posts = cat_posts;
}


CatModel(with getter setter):

public class R_CatModel {

@SerializedName("id")
public Integer id;
@SerializedName("type")
public String type;
@SerializedName("slug")
public String slug;
@SerializedName("url")
public String url;
@SerializedName("status")
public String status;
@SerializedName("title")
public String title;
@SerializedName("title_plain")
public String title_plain;
@SerializedName("content")
public String content;
@SerializedName("excerpt")
public String excerpt;
@SerializedName("date")
public String date;
@SerializedName("modified")
public String modified;
@SerializedName("comment_count")
public int comment_count;
@SerializedName("comment_status")
public String comment_status;
@SerializedName("thumbnail")
public String thumbnail;
@SerializedName("thumbnail_images")
public R_CatThumbnailImages thumbnail_images;
@SerializedName("categories")
public List<R_CatCategory> categories;
@SerializedName("author")
public R_CatAuthor catAuthor;
@SerializedName("comments")
public List<R_PostComment> comments;


How can i fix it? Thanks all <3

Answer

I think you are assuming those numbers correspond to the key ordering of the JSON data. For example, 1 is the name, 3 is the content, and 4 is the date. That isn't how JSON parsing works. And that is also wrong, you are indexing a List of objects, not JSON data. If there are less than 5 comments in the list, you get an error. And if there were 5 or more, you'd have the name of the first comment, date of the 4th and content of the 3rd.

You need to remodel your application, but maybe this is the problem.

models = response.body().getCat_posts();

This is a list of posts, which you are attempting to load into a CommentAdapter, but each Post object has its own list of Comments. I'd recommend you have a PostAdapter class that loads this list, and attach some click listener to it so you can load one Post into a View, then inside that View, you can use your CommentAdapter to display all comments for that post.

To test your CommentAdapter, though, you can load just the first Post from the response

models = response.body().getCat_posts().get(0).getComments();

And, then, in the CommentAdapter, you can extract the comment data like this after you fix the constructor and mDataSet data type

R_PostComment c = mDataSet.get(pos);

viewHolder.comment_name.setText(c.getCmName());
viewHolder.comment_date.setText(c.getCmDate());
viewHolder.comment_content.setText(Html.fromHtml(c.getCmContent()));

Aside: underscores in variable names is not a Java naming convention. Variables should be camelCase. And R_CatModel is a strange name for what seems to be a Post