Set Image array in recyclerview from json data in android - android

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

Related

How to parse this json objects on recyclerview? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to show this json in recyclerview. how can I do it?
I just want to list "user" and "exchangeName".
My Json;
{
"events": {
"101": {
"id": "0001",
"type": "exchange",
"user": "BTUser01",
"exchangeName": "BTCTurk",
"transactions": {
"send": "249",
"get": "24.1"
},
"certificate": [
"BTUser01Certificate"
]
},
"102": {
"id": "0002",
"type": "exchange",
"user": "BTUser02",
"exchangeName": "Koinim",
"transactions": {
"send": "300",
"get": "641"
},
"certificate": [
"BTUser02Certificate"
]
},
"103": {
"id": "0003",
"type": "exchange2",
"user": "BTUser03",
"exchangeName": "Koineks",
"transactions": {
"send": "823",
"get": "751"
},
"certificate": [
"BTUser03Certificate"
]
},
"104": {
"id": "0004",
"type": "exchange3",
"user": "BTUser04",
"exchangeName": "Paribu",
"transactions": {
"send": "543",
"get": "3.1"
},
"certificate": [
"BTUser04Certificate"
]
}
}
}
MainActivity;
public class MainActivity extends AppCompatActivity {
TextView ev, ev2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ev = (TextView) findViewById(R.id.ev);
ev2 = (TextView) findViewById(R.id.ev2);
Retrofit retrofit = new Retrofit.Builder().baseUrl("MYAPÄ°_ADRESS_LINK").addConverterFactory(GsonConverterFactory.create()).build();
Service service = retrofit.create(Service.class);
Call<ResponseBody> call = service.getData();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(#NonNull Call<ResponseBody> call, #NonNull Response<ResponseBody> response) {
if (response.isSuccessful()) {
String res = null;
if (response.body() != null) {
try {
res = response.body().string();
parse(res);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onFailure(#NonNull Call<ResponseBody> call, #NonNull Throwable t) {
int a = 0;
}
});
}
Model parse(String str) {
Model model = new Model();
try {
String source = str.replace("\n", "").replace("\t", "").replace("\r", "");
String s = new Gson().toJson(source);
s = s.replace("\\","");
s = s.substring(1,s.length()-1);
JSONObject object = new JSONObject(s).getJSONObject("events");
Iterator<String> iter = object.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONObject value = new JSONObject(String.valueOf(object.get(key)));
model.setExternalId(Integer.parseInt(key));
model.setUser(value.getString("user"));
model.setSend(value.getString("send"));
ev.setText(model.user);
ev2.setText(model.send);
return model;
} catch (JSONException e) {
// Something went wrong!
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return model;
}
}
My Model;
public class Model {
int externalId;
int id;
String type;
String user;
String exchangeName;
Transactions transactions;
List<certificate> certificateList;
public int getExternalId() {
return externalId;
}
public void setExternalId(int externalId) {
this.externalId = externalId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getExchangeName() {
return exchangeName;
}
public void setExchangeName(String exchangeName) {
this.exchangeName = exchangeName;
}
public Transactions getTransactions() {
return transactions;
}
public void setTransactions(Transactions transactions) {
this.transactions = transactions;
}
public List<certificate> getCertificateList() {
return certificateList;
}
public void setCertificateList(List<certificate> certificateList) {
this.certificateList = certificateList;
}
class Transactions{
String send;
String get;
public String getSend() {
return send;
}
public void setSend(String send) {
this.send = send;
}
public String getGet() {
return get;
}
public void setGet(String get) {
this.get = get;
}
}
class certificate{
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
First of all you could have found this answer easily in the hundreds of tutorials and guides available.
To achieve this you will need to create a custom adapter and a custom view for the adapter item.
To preface this answer. I wasn't sure if you want to show multiple Model items in the RecyclerView, or some other data. This example assumes that you use a List<Model>, however, it's an easy change to make it work with another list of objects.
Example of how the adapter could look like
public class MyAdapter extends RecyclerView.Adapter
{
private Context _context;
private List<Model> _items;
public void setItems(List<Model> items)
{
this._items = items;
notifyDataSetChanged();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
_context = parent.getContext();
return new MyAdapter.ItemViewHolder(parent);
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position)
{
final MyAdapter.ItemViewHolder viewHolder = (MyAdapter.ItemViewHolder) holder;
final Model item = _items.get(position);
viewHolder._user.setText(item.user);
viewHolder._exchangeName.setText(item.exchangeName);
}
#Override
public int getItemCount()
{
return _items != null ? _items.size() : 0;
}
private static class ItemViewHolder extends RecyclerView.ViewHolder
{
private TextView _user;
private TextView _exchangeName;
private ItemViewHolder(ViewGroup parent)
{
super(LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_view, parent, false));
this._user = itemView.findViewById(R.id.user);
this._exchangeName = itemView.findViewById(R.id.exchange_name);
}
}
}
R.layout.adapter_view
This needs to be a view containing at least the two TextView views references from the MyAdapter above. Simple example:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#drawable/content_container"
android:orientation="vertical"
android:animateLayoutChanges="true"
android:padding="#dimen/padding_view_large"
android:layout_marginBottom="#dimen/padding_view_small">
<TextView
android:id="#+id/user"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/placeholder"
android:textColor="#color/black"
android:textSize="#dimen/text_size_medium"
android:layout_marginTop="#dimen/padding_view_small"/>
<TextView
android:id="#+id/exchange_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/placeholder"
android:textColor="#color/black"
android:textSize="#dimen/text_size_medium"
android:layout_marginTop="#dimen/padding_view_small"/>
</LinearLayout>
Binding the adapter
//First we set up the adapter and add our List<Model> object.
MyAdapter adapter = new MyAdapter();
adapter.setItems(... List<Model> items);
//Set up our RecyclerView and set the adapter.
final RecyclerView recyclerView = rootView.findViewById(R.id.model_list);
recyclerView.setLayoutManager(new LinearLayoutManager(_context));
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
You need to first understand (and later create) the following things
RecyclerView Adapter
RecyclerView ViewHolder
After you read up on those two things the solution will be pretty clear. Just to point you in the right direction, you will have to create a custom adapter which you will use to populate your custom viewholders. Hope this helps get you going. Feel free to ask if you need any more help in this.

Showing Json response in `RecyclerView` using `CardView` in Android Studio in Java

I have to show my JSON response in a recycler view using card view with use of volley library .My JSON response is something like
{
"id": 87,
"parent_id": 0,
"shipping": {
"first_name": "JPbrajesh",
"last_name": "kumar",
},
"payment_method": "COD",
"line_items": [
{
"id": 16,
"name": "abc",
"price": 85
},
{
"id": 17,
"name": "zxc",
"price": 38
},
{
"id": 18,
"name": "asd",
"price": 136
}
],
"tax_lines": [],
"shipping_lines": [
{
"id": 19,
}
],
"fee_lines": [],
"_links": {
"self": [
{
"href": "https://example.com/wp-json/wc/v2/orders/87"
}
],
"collection": [
{
"href": "https://example.com/wp-json/wc/v2/orders"
}
]
}
}
`i have to show (Line_items) in a recycler view using volley Library.Please provide some related steps.Thankyou in advance for kind support.
You can first create a class LineItem as model for lineitems.
Then in the activity where you want the data to be used, create a list of line items and fill that list with data from you json object.
create a layout for that lineitem
create an adapter class
declare the adapter and pass it the list and then attach the adapter to the recyclerview.
Something like this:
ProductCategory class
package com.pesabay.pesabay;
/**
* Created by Valentin_Kavakure on 20-Jun-17.
*/
public class ProductCategory {
private int id,niveau,order,premier,nbrProduits;
private String name;
private String image;
public ProductCategory() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ProductCategory(int id) {
this.id = id;
}
public int getId() {
return id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
Then the layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
app:cardElevation="6dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="150dp"
app:srcCompat="#drawable/bluebg" />
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
The adapter:
public class CatGridAdapter extends RecyclerView.Adapter<CatGridAdapter.ViewHolder> {
private List<ProductCategory> categoryList;
private Context context;
private RecyclerViewClickListener recyclerViewClickListener;
public void setRecyclerViewClickListener(RecyclerViewClickListener recyclerViewClickListener) {
this.recyclerViewClickListener = recyclerViewClickListener;
}
public CatGridAdapter(List<ProductCategory> categoryList, Context context) {
this.categoryList = categoryList;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.category_grid_layout,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(categoryList.get(position).getName());
}
#Override
public int getItemCount() {
return categoryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;TextView title;
public ViewHolder(final View itemView) {
super(itemView);
title=(TextView)itemView.findViewById(R.id.title);
imageView=(ImageView)itemView.findViewById(R.id.image);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (recyclerViewClickListener!=null) {
recyclerViewClickListener.recyclerViewItemClicked(v, getAdapterPosition());
}
}
});
}
}
}
And the in my activity:
recyclerView=(RecyclerView)findViewById(R.id.recycler_data);
categoryList=new ArrayList<>();
catGridAdapter=new CatGridAdapter(categoryList,CategoryGrid.this);
pg=(ProgressBar)findViewById(R.id.pg);
catGridAdapter.setRecyclerViewClickListener(new RecyclerViewClickListener() {
#Override
public void recyclerViewItemClicked(View view, int position) {
/* some code*/
});
gridLayoutManager=new GridLayoutManager(CategoryGrid.this,2);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setAdapter(catGridAdapter);
Volley is the library for request the information. When Volley succeed, you get this this JSON response. After that, you need to parse Line_items and pass them to the RecyclerView Adapter.
Hope it helps.

Resources$NotFoundException When calling a Rest API using RetroFit 2

I am calling a REST Api with RetroFit 2 and trying to display it with a RecyclerView but for some reason I am getting a Resources$NotFoundException.
The JSON generated That i want to read and display in a RecyclerView is:
{
"generated_at": "2018-05-31T12:10:29+00:00",
"schema": "http:\/\/schemas.sportradar.com\/bsa\/soccer\/v1\/json\/endpoints\/soccer\/tournament_standings.json",
"tournament": {
"id": "sr:tournament:17",
"name": "Premier League",
"sport": {
"id": "sr:sport:1",
"name": "Soccer"
},
"category": {
"id": "sr:category:1",
"name": "England",
"country_code": "ENG"
},
"current_season": {
"id": "sr:season:40942",
"name": "Premier League 17\/18",
"start_date": "2017-08-11",
"end_date": "2018-05-14",
"year": "17\/18"
}
},
"season": {
"id": "sr:season:40942",
"name": "Premier League 17\/18",
"start_date": "2017-08-11",
"end_date": "2018-05-14",
"year": "17\/18",
"tournament_id": "sr:tournament:17"
},
"standings": [{
"tie_break_rule": "In the event that two (or more) teams have an equal number of points, the following rules break the tie:\r\n1. Goal difference\r\n2. Goals scored",
"type": "total",
"groups": [{
"team_standings": [{
"team": {
"id": "sr:competitor:17",
"name": "Manchester City"
},
"rank": 1,
"current_outcome": "Champions League",
"played": 38,
"win": 32,
"draw": 4,
"loss": 2,
"goals_for": 106,
"goals_against": 27,
"goal_diff": 79,
"points": 100
}]
}]
}]}
So I created a Response which is :
public class StandingsResponse {
#SerializedName("generated_at")
#Expose
private String mGeneratedAt;
#SerializedName("schema")
#Expose
private String mSchema;
#SerializedName("standings")
private List<Standings> mStandings;
public String getGeneratedAt() {
return mGeneratedAt;
}
public void setGeneratedAt(String generatedAt) {
mGeneratedAt = generatedAt;
}
public String getSchema() {
return mSchema;
}
public void setSchema(String schema) {
mSchema = schema;
}
public List<Standings> getStandings() {
return mStandings;
}
public void setStandings(List<Standings> standings) {
mStandings = standings;
}
The Response has a List of Standings, The standings POJO has a list of groups:
public class Standings {
#SerializedName("groups")
#Expose
private List<Group> mGroup;
public List<Group> getGroup() {
return mGroup;
}
public void setGroup(List<Group> group) {
mGroup = group;
}
The Groups POJO has a list of TeamStandings:
public class Group {
#SerializedName("team_standings")
#Expose
private List<TeamStandings> mTeamStandings;
public List<TeamStandings> getTeamStandings() {
return mTeamStandings;
}
public void setTeamStandings(List<TeamStandings> teamStandings) {
mTeamStandings = teamStandings;
}
And TeamStandings has all the data I want to display:
public class TeamStandings {
#SerializedName("team")
#Expose
private Team mTeam;
#SerializedName("rank")
#Expose
private Integer mRank;
#SerializedName("played")
#Expose
private Integer mPlayed;
#SerializedName("win")
#Expose
private Integer mWin;
#SerializedName("draw")
#Expose
private Integer mDraw;
#SerializedName("lose")
#Expose
private Integer mLose;
#SerializedName("goals_for")
#Expose
private Integer mGoalsFor;
#SerializedName("goals_against")
#Expose
private Integer mGoalsAgainst;
#SerializedName("goal_diff")
#Expose
private Integer mGoalsDiff;
#SerializedName("points")
#Expose
private Integer mPoints;
public Integer getGoalsFor() {
return mGoalsFor;
}
public void setGoalsFor(Integer goalsFor) {
mGoalsFor = goalsFor;
}
public Integer getGoalsAgainst() {
return mGoalsAgainst;
}
public void setGoalsAgainst(Integer goalsAgainst) {
mGoalsAgainst = goalsAgainst;
}
public Integer getGoalsDiff() {
return mGoalsDiff;
}
public void setGoalsDiff(Integer goalsDiff) {
mGoalsDiff = goalsDiff;
}
public Integer getRank() {
return mRank;
}
public void setRank(Integer rank) {
mRank = rank;
}
public Integer getPlayed() {
return mPlayed;
}
public void setPlayed(Integer played) {
mPlayed = played;
}
public Integer getWin() {
return mWin;
}
public void setWin(Integer win) {
mWin = win;
}
public Integer getDraw() {
return mDraw;
}
public void setDraw(Integer draw) {
mDraw = draw;
}
public Integer getLose() {
return mLose;
}
public void setLose(Integer lose) {
mLose = lose;
}
public Integer getPoints() {
return mPoints;
}
public void setPoints(Integer points) {
mPoints = points;
}
public Team getTeam() {
return mTeam;
}
public void setTeam(Team team) {
mTeam = team;
}
I am calling the response and correctly attaching the response body to the Adapter but for some reason the App crashes and I see this error in the Logcat:
android.content.res.Resources$NotFoundException: String resource ID #0x1
at android.content.res.Resources.getText(Resources.java:339)
at android.widget.TextView.setText(TextView.java:5496)
at com.mad.footstats.ui.adapters.StandingsAdapter.onBindViewHolder(StandingsAdapter.java:62)
Edit: this is my Adapter:
public class StandingsAdapter extends RecyclerView.Adapter<StandingsAdapter.StandingsViewHolder> {
private List<Standings> mStandings;
private int mRowLayout;
private Context mContext;
public class StandingsViewHolder extends RecyclerView.ViewHolder {
LinearLayout standingsLayout;
TextView teamRank, teamName, teamPlayed, teamWon, teamDraw,
teamLose, teamFor, teamAgainst, teamGd, teamPts;
public StandingsViewHolder(View itemView) {
super(itemView);
standingsLayout = itemView.findViewById(R.id.standings_layout);
teamRank = itemView.findViewById(R.id.standings_team_rank);
teamName = itemView.findViewById(R.id.standings_team_name);
teamPlayed = itemView.findViewById(R.id.standings_team_played);
teamWon = itemView.findViewById(R.id.standings_team_won);
teamDraw = itemView.findViewById(R.id.standings_team_draw);
teamLose = itemView.findViewById(R.id.standings_team_lost);
teamFor = itemView.findViewById(R.id.standings_team_for);
teamAgainst = itemView.findViewById(R.id.standings_team_against);
teamGd = itemView.findViewById(R.id.standings_team_gd);
teamPts = itemView.findViewById(R.id.standings_team_pts);
}
}
public StandingsAdapter (List<Standings> standings, int rowLayout,
Context context){
mStandings = standings;
mRowLayout = rowLayout;
mContext = context;
}
#Override
public StandingsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(mRowLayout, parent, false);
StandingsViewHolder holder = new StandingsViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(StandingsViewHolder holder, int position) {
holder.teamRank.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getRank());
holder.teamName.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getTeam().getName());
holder.teamPlayed.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getPlayed());
holder.teamWon.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getWin());
holder.teamDraw.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getDraw());
holder.teamLose.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getLose());
holder.teamFor.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getGoalsFor());
holder.teamAgainst.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getGoalsAgainst());
holder.teamGd.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getGoalsDiff());
holder.teamPts.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getPoints());
}
#Override
public int getItemCount() {
return mStandings.size();
}
This exception come because you set integer value in textview so you should be do type casting of String .
For Example
you doing
mTxtView.setText(mList.get(position).getMETHOD_WHICH_RETURN_INT())
you should be do
mTxtView.setText(""+mList.get(position).getMETHOD_WHICH_RETURN_INT())
You should be
holder.teamRank.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getRank());
holder.teamPlayed.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getPlayed());
holder.teamWon.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getWin());
holder.teamDraw.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getDraw());
holder.teamLose.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getLose());
holder.teamFor.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getGoalsFor());
holder.teamAgainst.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getGoalsAgainst());
holder.teamGd.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getGoalsDiff());
holder.teamPts.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getPoints());

Make a Recyclerview Android from API but, it doesn't work

I've been working with Recycler view Android. I try to make a Recycler view from API Response. But, the list didn't show up, my adapter was not working. When i tried to debug this program, I got List<Produclist> list is null.
This my JSON Response from API
{
"code": 0,
"data": [
{
"product_list": [
{
"return_level": 0,
"image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
"risk_level": "Aggresive",
"code": "P0011",
"price": {
"date": null,
"value": 0
},
"name": "Dana Ekuitas Prima"
},
{
"return_level": 0,
"image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
"risk_level": "Aggresive",
"code": "P0001",
"price": {
"date": "2017-01-03T11:44:52.6152Z",
"value": 150000
},
"name": "Manulife Dana Saham"
},
{
"return_level": 0,
"image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
"risk_level": "Aggresive",
"code": "P0008",
"price": {
"date": null,
"value": 0
},
"name": "Trim Kapital Plus"
},
{
"return_level": 0,
"image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
"risk_level": "Aggresive",
"code": "P0004",
"price": {
"date": "2017-01-03T11:44:52.6152Z",
"value": 150000
},
"name": "Manulife Syariah Sektoral Amanah"
}
],
"type": "Reksa Dana Saham"
}
],
"info": "Product list successfully loaded"
}
This My setter getter
public class ProductListResponse {
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("info")
#Expose
private String info;
#SerializedName("data")
#Expose
private List<CategoryType> listCategory = new ArrayList<>();
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public List<CategoryType> getListCategory() {
return listCategory;
}
public void setListCategory(List<CategoryType> listCategory) {
this.listCategory = listCategory;
}
}
Setter getter of category type
public class CategoryType {
#SerializedName("type")
#Expose
private String type;
#SerializedName("product_list")
#Expose
private List<ProductList> productList = new ArrayList<ProductList>();
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<ProductList> getProductList() {
return productList;
}
public void setProductList(List<ProductList> productList) {
this.productList = productList;
}
}
Setter getter of ProductList
public class ProductList implements Serializable {
#SerializedName("code")
#Expose
private String code;
#SerializedName("name")
#Expose
private String name;
#SerializedName("price")
#Expose
private Price price;
#SerializedName("risk_level")
#Expose
private String riskLevel;
#SerializedName("return_level")
#Expose
private Double returnLevel;
#SerializedName("image")
#Expose
private String image;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getRiskLevel() {
return riskLevel;
}
public void setRiskLevel(String riskLevel) {
this.riskLevel = riskLevel;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Price getPrice() {
return price;
}
public void setPrice(Price price) {
this.price = price;
}
public Double getreturnLevel() {
return returnLevel;
}
public void setReturnLevel(Double returnLevel) {
this.returnLevel = returnLevel;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
This my Activity
public class ProductActivity extends AppCompatActivity {
private RecyclerView rvView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
public List<ProductList> list;
Context context;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.f_list_of_product);
request(constructSignUpRequest());
rvView = (RecyclerView) findViewById(R.id.rv);
rvView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvView.setLayoutManager(layoutManager);
adapter = new ProductAdapter(context, list);
rvView.setAdapter(adapter);
}
public BTNService.Api getApi() {
return getBTNService().getApi();
}
public BTNService getBTNService() {
return new BTNService(this);
}
void request(final ProductListRequest productListRequest) {
getApi().loadproductlist(productListRequest.getCode())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<ProductListResponse>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
Timber.e(e.getLocalizedMessage());
}
#Override
public void onNext(ProductListResponse response) {
if (response != null) {
Intent intent = new Intent(ProductActivity.this, ProductList.class);
startActivity(intent);
}
}
});
}
public ProductListRequest constructSignUpRequest() {
ProductListRequest request = new ProductListRequest();
request.setCode(Category);
return request;
}
}
This my Adapter
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.CatalogueHolder> {
private Context context;
private List<ProductList> list;
public ProductAdapter(Context context, List<ProductList> list) {
this.context = context;
this.list = list;
}
#Override
public CatalogueHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_product, parent, false);
CatalogueHolder catalogueHolder = new CatalogueHolder(itemView);
return catalogueHolder;
}
#Override
public void onBindViewHolder(CatalogueHolder holder, int position) {
final ProductList item = list.get(position);
holder.itemView.setTag(item);
holder.productName.setText(item.getName());
}
#Override
public int getItemCount() {
return list != null ? list.size() : 0;
}
public static class CatalogueHolder extends RecyclerView.ViewHolder {
#Bind(R.id.productname)
TextView productName;
#Bind(R.id.typeProduct)
TextView typeProduct;
#Bind(R.id.price)
TextView price;
#Bind(R.id.date)
TextView date;
public CatalogueHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
Sorry, if it's quite long. I have to show all my code to make it clear. I really need your help guys. Thanks
Set adapter inside onComplete method:
void request(final ProductListRequest productListRequest) {
getApi().loadproductlist(productListRequest.getCode())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<ProductListResponse>() {
#Override
public void onCompleted() {
rvView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvView.setLayoutManager(layoutManager);
adapter = new ProductAdapter(context, list);
rvView.setAdapter(adapter);
}
#Override
public void onError(Throwable e) {
Timber.e(e.getLocalizedMessage());
}
#Override
public void onNext(ProductListResponse response) {
if (response != null) {
Intent intent = new Intent(ProductActivity.this, ProductList.class);
startActivity(intent);
}
}
});
}

Expected STRING but was BEGIN_ARRAY, Realm and JSON

I have write JSON file:
[
{ "name" : "Sir",
"votes" : 23,
"imageURL" : "http://img.prntscr.com/img?url=http://i.imgur.com/5ogv5yJ.png" },
{ "name" : "Bar",
"votes" : 21,
"imageURL" : [
"http://img.prntscr.com/img?url=http://i.imgur.com/G1qQb9Q.png",
"http://www.dreamhost.com/blog/wp-content/uploads/2015/10/DHC_blog-image-01-300x300.jpg",
"http://lh5.ggpht.com/yt6SnO_2jOIot1FhQYGiVXd_IQWBOCmQ1UJBddyau3Wzw1ZgpdeQwpO7TRFnux3Dirk=w300",
"http://i.vimeocdn.com/portrait/4728693_300x300.jpg",
"http://www.raspberrypi.org/wp-content/themes/mind-control/images/octocat.jpg"
]
},
{ "name" : "Buildings",
"votes" : 19,
"imageURL" : "http://img.prntscr.com/img?url=http://i.imgur.com/brzudoL.png"}
]
Model class
public class City extends RealmObject {
private String name;
private long votes;
private String imageURL;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getVotes() {
return votes;
}
public void setVotes(long votes) {
this.votes = votes;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
}
And Adapter
public class CityAdapter extends BaseAdapter {
//private final Context context;
private LayoutInflater inflater;
private List<City> cities = null;
/* public CityAdapter(Context context) {
this.context = context; */
public CityAdapter(Context context) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(List<City> details) {
this.cities = details;
}
#Override
public int getCount() {
if (cities == null) {
return 0;
}
return cities.size();
}
#Override
public Object getItem(int position) {
if (cities == null || cities.get(position) == null) {
return null;
}
return cities.get(position);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View currentView, ViewGroup parent) {
if (currentView == null) {
currentView = inflater.inflate(R.layout.city_listitem, parent, false);
}
City city = cities.get(position);
ImageView photo = (ImageView) currentView.findViewById(R.id.picture);
if (city != null) {
Picasso.with(inflater.getContext()).load(city.getImageURL()).placeholder(R.drawable.internet_access_placeholder).into(photo);
((TextView) currentView.findViewById(R.id.name)).setText(city.getName());
((TextView) currentView.findViewById(R.id.votes)).setText(String.format(Locale.US, "%d", city.getVotes()));
}
return currentView;
}
}
down there in adapter I setup picasso:
Picasso.with(inflater.getContext()).load(city.getImageURL()).placeholder(R.drawable.internet_access_placeholder).into(photo);
And project is working when I got only one photo in JSON like image from object "name" : "Sir"
But When I write multiple URLs like in 2nd object "name" : "Bar" I get that error: "Expected STRING but was BEGIN_ARRAY"
I understand what is problem but I don't know how to fix it...
I want to have more than one photo in some objects like in 2nd
then always expect / send an array and map it to a list and check for the list size
final List<String> urls = city.getImageURLs();
if (urls.size() > 1) {
// add code for more images
} else {
Picasso.with(inflater.getContext()).load(urls.get(0)).placeholder(R.drawable.internet_access_placeholder).into(photo);
}
imageURL must be Json array
[
{ "name" : "Sir",
"votes" : 23,
"imageURL" : [ "http://img.prntscr.com/img?url=http://i.imgur.com/5ogv5yJ.png" ] },
{ "name" : "Bar",
"votes" : 21,
"imageURL" : [
"http://img.prntscr.com/img?url=http://i.imgur.com/G1qQb9Q.png",
"http://www.dreamhost.com/blog/wp-content/uploads/2015/10/DHC_blog-image-01-300x300.jpg",
"http://lh5.ggpht.com/yt6SnO_2jOIot1FhQYGiVXd_IQWBOCmQ1UJBddyau3Wzw1ZgpdeQwpO7TRFnux3Dirk=w300",
"http://i.vimeocdn.com/portrait/4728693_300x300.jpg",
"http://www.raspberrypi.org/wp-content/themes/mind-control/images/octocat.jpg"
]
}
]
and your model must be like that
public class City extends RealmObject {
private String name;
private long votes;
private List<String> imageURL;
.
.
.
}

Categories

Resources