Resources$NotFoundException When calling a Rest API using RetroFit 2 - android

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

Related

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 2 column 1 error

I'm new to android programming. I have a class where retrofit API call is done to parse and display few attributes JSON file. But I get:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING
at line 2 column 1
Kindly help. I searched for answers but I couldn't find anything wrong with the JSON response. Posted my JSON response and JAVA class:
JSON Response:
{
"status": 1,
"active_requests": [
{
"id": "12",
"driver_id": "2",
"booking_id": "12",
"request_status": "1",
"created_on": "2018-09-13 19:57:29",
"updated_on": "2018-09-13 19:57:29",
"customer_id": "1",
"pickup_location": "GN Mills",
"drop_location": "Vadavalli",
"pickup_latitude": "11.025625",
"pickup_longitude": "76.955467",
"drop_latitude": "18.5645654",
"drop_longitude": "17.5645654",
"pickup_date_time": "2018-09-28 15:25:00",
"drop_date_time": "2018-09-28 15:25:00",
"package_weight": "55.5",
"package_type": "1",
"package_description": "fdasd dsaD YDASYD",
"vechicle_type": "car",
"service_status": "1",
"total_distance": "0",
"service_fare": "3460.6110936131",
"driver_fare": "2768.4888748905",
"paid_amount": "0",
"card_id": "0",
"picked_time": "0000-00-00 00:00:00",
"dropped_time": "0000-00-00 00:00:00"
}
]
}
JAVA File:
public class DriverDashboardFragment extends Fragment {
View root_view;
#BindView(R.id.linear_detail)
LinearLayout linearDetail;
#BindView(R.id.img_back)
ImageView imgBack;
#BindView(R.id.txt_title)
TextView txt_title;
SharedPreferences sharedPreferences;
Unbinder unbinder;
Context context;
RecyclerView recyclerView;
DriverDashboardAdapter driverDashboardAdapter;
List<DriverRequestModel> driver_list;
String id;
public static DriverDashboardFragment newInstance() {
DriverDashboardFragment fragment = new DriverDashboardFragment();
return fragment;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.driverfragment_dashboard, container, false);
unbinder = ButterKnife.bind(this, root_view);
context = getContext();
sharedPreferences = getActivity().getSharedPreferences("MyPref", 0); // 0 - for private mode
id = PrefConnect.readString(getActivity(), PrefConnect.CUSTOMER_ID, "");
String msg= sharedPreferences.getString("message","");
Log.i("TAG",msg);
txt_title.setText("Dashboard");
imgBack.setVisibility(View.GONE);
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
ApiService apiService = (ApiService) RetrofitSingleton.getApiService();
Call<DriverRequestModel> call = apiService.getdriverrequest();
call.enqueue(new Callback<DriverRequestModel>() {
#Override
public void onResponse(Call<DriverRequestModel> call, Response<DriverRequestModel> response) {
driver_list = new ArrayList<>();
DriverRequestModel promo=response.body();
driver_list = promo.getActiveRequests();
Log.e("Response = ",new Gson().toJson(response.body()));
PrefConnect.writeString(context,PrefConnect.CUSTOMER_ID,response.body().getCustomerId()+"");
recyclerView = (RecyclerView)root_view.findViewById(R.id.recyclerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
driverDashboardAdapter = new DriverDashboardAdapter(getContext(),driver_list);
recyclerView.setAdapter(driverDashboardAdapter);
}
#Override
public void onFailure(Call<DriverRequestModel> call, Throwable t) {
Log.e("TAG","Response = "+t.toString());
}
});
return root_view;
}
#OnClick({R.id.linear_detail})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.linear_detail:
Intent detail = new Intent(context, DriverServiceDetailActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("key_1", 1);
detail.putExtras(bundle);
startActivity(detail);
break;
}
}
}
Model Class:
public class DriverRequestModel {
#SerializedName("status")
#Expose
public Integer status;
#SerializedName("active_requests")
#Expose
public List<ActiveRequest> activeRequests = null;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public List<ActiveRequest> getActiveRequests() {
return activeRequests;
}
public void setActiveRequests(List<ActiveRequest> activeRequests) {
this.activeRequests = activeRequests;
}
public class ActiveRequest {
#SerializedName("id")
#Expose
public String id;
#SerializedName("driver_id")
#Expose
public String driverId;
#SerializedName("booking_id")
#Expose
public String bookingId;
#SerializedName("request_status")
#Expose
public String requestStatus;
#SerializedName("created_on")
#Expose
public String createdOn;
#SerializedName("updated_on")
#Expose
public String updatedOn;
#SerializedName("customer_id")
#Expose
public String customerId;
#SerializedName("pickup_location")
#Expose
public String pickupLocation;
#SerializedName("drop_location")
#Expose
public String dropLocation;
#SerializedName("pickup_latitude")
#Expose
public String pickupLatitude;
#SerializedName("pickup_longitude")
#Expose
public String pickupLongitude;
#SerializedName("drop_latitude")
#Expose
public String dropLatitude;
#SerializedName("drop_longitude")
#Expose
public String dropLongitude;
#SerializedName("pickup_date_time")
#Expose
public String pickupDateTime;
#SerializedName("drop_date_time")
#Expose
public String dropDateTime;
#SerializedName("package_weight")
#Expose
public String packageWeight;
#SerializedName("package_type")
#Expose
public String packageType;
#SerializedName("package_description")
#Expose
public String packageDescription;
#SerializedName("vechicle_type")
#Expose
public String vechicleType;
#SerializedName("service_status")
#Expose
public String serviceStatus;
#SerializedName("total_distance")
#Expose
public String totalDistance;
#SerializedName("service_fare")
#Expose
public String serviceFare;
#SerializedName("driver_fare")
#Expose
public String driverFare;
#SerializedName("paid_amount")
#Expose
public String paidAmount;
#SerializedName("card_id")
#Expose
public String cardId;
#SerializedName("picked_time")
#Expose
public String pickedTime;
#SerializedName("dropped_time")
#Expose
public String droppedTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDriverId() {
return driverId;
}
public void setDriverId(String driverId) {
this.driverId = driverId;
}
public String getBookingId() {
return bookingId;
}
public void setBookingId(String bookingId) {
this.bookingId = bookingId;
}
public String getRequestStatus() {
return requestStatus;
}
public void setRequestStatus(String requestStatus) {
this.requestStatus = requestStatus;
}
public String getCreatedOn() {
return createdOn;
}
public void setCreatedOn(String createdOn) {
this.createdOn = createdOn;
}
public String getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(String updatedOn) {
this.updatedOn = updatedOn;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getPickupLocation() {
return pickupLocation;
}
public void setPickupLocation(String pickupLocation) {
this.pickupLocation = pickupLocation;
}
public String getDropLocation() {
return dropLocation;
}
public void setDropLocation(String dropLocation) {
this.dropLocation = dropLocation;
}
public String getPickupLatitude() {
return pickupLatitude;
}
public void setPickupLatitude(String pickupLatitude) {
this.pickupLatitude = pickupLatitude;
}
public String getPickupLongitude() {
return pickupLongitude;
}
public void setPickupLongitude(String pickupLongitude) {
this.pickupLongitude = pickupLongitude;
}
public String getDropLatitude() {
return dropLatitude;
}
public void setDropLatitude(String dropLatitude) {
this.dropLatitude = dropLatitude;
}
public String getDropLongitude() {
return dropLongitude;
}
public void setDropLongitude(String dropLongitude) {
this.dropLongitude = dropLongitude;
}
public String getPickupDateTime() {
return pickupDateTime;
}
public void setPickupDateTime(String pickupDateTime) {
this.pickupDateTime = pickupDateTime;
}
public String getDropDateTime() {
return dropDateTime;
}
public void setDropDateTime(String dropDateTime) {
this.dropDateTime = dropDateTime;
}
public String getPackageWeight() {
return packageWeight;
}
public void setPackageWeight(String packageWeight) {
this.packageWeight = packageWeight;
}
public String getPackageType() {
return packageType;
}
public void setPackageType(String packageType) {
this.packageType = packageType;
}
public String getPackageDescription() {
return packageDescription;
}
public void setPackageDescription(String packageDescription) {
this.packageDescription = packageDescription;
}
public String getVechicleType() {
return vechicleType;
}
public void setVechicleType(String vechicleType) {
this.vechicleType = vechicleType;
}
public String getServiceStatus() {
return serviceStatus;
}
public void setServiceStatus(String serviceStatus) {
this.serviceStatus = serviceStatus;
}
public String getTotalDistance() {
return totalDistance;
}
public void setTotalDistance(String totalDistance) {
this.totalDistance = totalDistance;
}
public String getServiceFare() {
return serviceFare;
}
public void setServiceFare(String serviceFare) {
this.serviceFare = serviceFare;
}
public String getDriverFare() {
return driverFare;
}
public void setDriverFare(String driverFare) {
this.driverFare = driverFare;
}
public String getPaidAmount() {
return paidAmount;
}
public void setPaidAmount(String paidAmount) {
this.paidAmount = paidAmount;
}
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public String getPickedTime() {
return pickedTime;
}
public void setPickedTime(String pickedTime) {
this.pickedTime = pickedTime;
}
public String getDroppedTime() {
return droppedTime;
}
public void setDroppedTime(String droppedTime) {
this.droppedTime = droppedTime;
}
}
}
Are you using the right model for mapping your response? Should it be:
DriverRequestModel driverRequestModel = response.body();

Set Image array in recyclerview from json data in 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);
}
}

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

RecyclerView setting text

I have just jumped to android with a very limited knowledge about recyclerview. I have used a a bit, but faced a situation where setting a text inside onBindViewHolder.Please bear with me.Check the following codes:
1.This is the json, here:
[
{
"restaurantSubscriptionType_Id": 1,
"noOfDaysPlan": "1 Day Trial Meal",
"restaurantSubscriptionEntity": [
{
"restaurantSubscriptionId": 39,
"subscriptionPlan": "Breakfast & Lunch",
"subscriptionImagePath": null,
"subscriptionDays": 1,
"subscriptionAmount": 150,
"restaurant_Subscription_Type_Id": 1
}
],
"restaurantId": 224
},
{
"restaurantSubscriptionType_Id": 2,
"noOfDaysPlan": "5 Days Weekly Plan",
"restaurantSubscriptionEntity": [
{
"restaurantSubscriptionId": 40,
"subscriptionPlan": "Breakfast & Lunch",
"subscriptionImagePath": null,
"subscriptionDays": 5,
"subscriptionAmount": 650,
"restaurant_Subscription_Type_Id": 2
},
{
"restaurantSubscriptionId": 41,
"subscriptionPlan": "Only Lunch",
"subscriptionImagePath": null,
"subscriptionDays": 5,
"subscriptionAmount": 500,
"restaurant_Subscription_Type_Id": 2
}
],
"restaurantId": 224
}
]
I have pojo2schema site
2.RestaurantSubscriptionEntity
public class RestaurantSubscriptionEntity {
private Integer restaurantSubscriptionId;
private String subscriptionPlan;
private String subscriptionImagePath;
private Integer subscriptionDays;
private Long subscriptionAmount;
private Integer restaurantSubscriptionTypeId;
public RestaurantSubscriptionEntity(){
}
public Integer getRestaurantSubscriptionId() {
return restaurantSubscriptionId;
}
public void setRestaurantSubscriptionId(Integer restaurantSubscriptionId) {
this.restaurantSubscriptionId = restaurantSubscriptionId;
}
public String getSubscriptionPlan() {
return subscriptionPlan;
}
public void setSubscriptionPlan(String subscriptionPlan) {
this.subscriptionPlan = subscriptionPlan;
}
public String getSubscriptionImagePath() {
return subscriptionImagePath;
}
public void setSubscriptionImagePath(String subscriptionImagePath) {
this.subscriptionImagePath = subscriptionImagePath;
}
public Integer getSubscriptionDays() {
return subscriptionDays;
}
public void setSubscriptionDays(Integer subscriptionDays) {
this.subscriptionDays = subscriptionDays;
}
public Long getSubscriptionAmount() {
return subscriptionAmount;
}
public void setSubscriptionAmount(Long subscriptionAmount) {
this.subscriptionAmount = subscriptionAmount;
}
public Integer getRestaurantSubscriptionTypeId() {
return restaurantSubscriptionTypeId;
}
public void setRestaurantSubscriptionTypeId(Integer restaurantSubscriptionTypeId) {
this.restaurantSubscriptionTypeId = restaurantSubscriptionTypeId;
}
3.DemoItemAll:
public class DemoItemAll {
private Integer restaurantSubscriptionTypeId;
private String noOfDaysPlan;
private List<RestaurantSubscriptionEntity> restaurantSubscriptionEntity = new ArrayList<RestaurantSubscriptionEntity>();
private Long restaurantId;
public DemoItemAll(){
}
public Integer getRestaurantSubscriptionTypeId() {
return restaurantSubscriptionTypeId;
}
public void setRestaurantSubscriptionTypeId(Integer restaurantSubscriptionTypeId) {
this.restaurantSubscriptionTypeId = restaurantSubscriptionTypeId;
}
public String getNoOfDaysPlan() {
return noOfDaysPlan;
}
public void setNoOfDaysPlan(String noOfDaysPlan) {
this.noOfDaysPlan = noOfDaysPlan;
}
public List<RestaurantSubscriptionEntity> getRestaurantSubscriptionEntity() {
return restaurantSubscriptionEntity;
}
public void setRestaurantSubscriptionEntity(List<RestaurantSubscriptionEntity> restaurantSubscriptionEntity) {
this.restaurantSubscriptionEntity = restaurantSubscriptionEntity;
}
public Long getRestaurantId() {
return restaurantId;
}
public void setRestaurantId(Long restaurantId) {
this.restaurantId = restaurantId;
}
4.Here my class which extends RecyclerView
public class DemoAdapter extends RecyclerView.Adapter<DemoAdapter.MyViewHolder> {
private List<DemoItemAll> demoItemAllArrayList = new ArrayList<>();
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView title_tv,price_tv;
private Button drop_down_button;
public MyViewHolder(View itemView) {
super(itemView);
title_tv = (TextView) itemView.findViewById(R.id.day_plan_demo_tv_id);
price_tv = (TextView) itemView.findViewById(R.id.price_demo_tv_id);
drop_down_button = (Button) itemView.findViewById(R.id.demo_drop_down_btn_id);
}
}
public DemoAdapter(List<DemoItemAll> demoItemAllArrayList) {
this.demoItemAllArrayList = demoItemAllArrayList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.demo_adapter, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
DemoItemAll demoItemAll=new DemoItemAll();
//noOfDays
holder.title_tv.setText(demoItemAll.getNoOfDaysPlan());
}
#Override
public int getItemCount() {
return demoItemAllArrayList.size();
}
}
now here inside onBindView,I need to set this but "subscriptionAmount"
belongs to RestaurantSubscriptionEntity class.How do I access it
holder.price_tv.setText //subscriptionAmount.
You just create new empty DemoItemAll object.
You need to use
DemoItemAll demoItemAll = demoItemAllArrayList.get(position);
instead of
DemoItemAll demoItemAll = new DemoItemAll();
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
DemoItemAll demoItemAll = demoItemAllArrayList.get(position);
List<RestaurantSubscriptionEntity> entity = demoItemAll.getRestaurantSubscriptionEntity();
holder.title_tv.setText(demoItemAll.getNoOfDaysPlan());
holder.price_tv.setText(String.valueOf(entity.getSubscriptionAmount()))
}

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