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;
.
.
.
}
Related
Hello I'm trying to get Data by using Model class and
show data in recyclerview by using Model class too.
I got thumbnail data for ArrayList, I think this caused the error but I don't know What should I do.
I have adapter and I tested if thumbnail data is just string (not list), It worked well.
What's wrong and How can I retrieve thumbnail data list?? It's too difficult to beginner....
This is my part of Fragment java code
Query newPlaceDatabaseQuery = FirebaseDatabase.getInstance().getReference(dataA).child(placeA).limitToLast(5);
newPlaceDatabaseQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnap) {
homeNewArrayList.clear();
for (DataSnapshot snapshot : dataSnap.getChildren()) {
//Error caused in here.
ItemHomeNew itemHomeNew = snapshot.getValue(ItemHomeNew.class);
homeNewArrayList.add(itemHomeNew);
}
newRecyclerView.setAdapter(newAdapter);
newAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
This is my model class ItemHomeNew code
public class ItemHomeNew {
private ArrayList<String> thumbnail;
private String placeAddress;
private String placeName;
private String placeStyle;
public ItemHomeNew(){
}
public ArrayList<String> getThumbnail() {
return thumbnail;
}
public void setThumbnail(ArrayList<String> thumbnail) {
this.thumbnail = thumbnail;
}
public String getPlaceAddress() {
return placeAddress;
}
public void setPlaceAddress(String placeAddress) {
this.placeAddress = placeAddress;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public String getPlaceStyle() {
return placeStyle;
}
public void setPlaceStyle(String placeStyle) {
this.placeStyle = placeStyle;
}
#Override
public String toString() {
return "thumbnail" + thumbnail + ',' ;
}
}
Adapter code
public class AdapterHomeNew extends RecyclerView.Adapter<AdapterHomeNew.ViewHolder>{
ArrayList<ItemHomeNew> array;
Context context;
#ColorInt int starColor;
#ColorInt int startextColor;
public AdapterHomeNew(ArrayList<ItemHomeNew> array, Context context) {
this.array = array;
this.context =context;
}
#NonNull
#Override
public AdapterHomeNew.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_home_new,parent,false);
return new AdapterHomeNew.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull AdapterHomeNew.ViewHolder holder, int position) {
Glide.with(context)
.load(array.get(position).getThumbnail())
.centerCrop()
.dontAnimate()
.into(holder.homeNewPlaceImg);
holder.homeNewAddress.setText(String.valueOf(array.get(position).getPlaceAddress()));
holder.homeNewplaceName.setText(String.valueOf(array.get(position).getPlaceName()));
holder.homeNewPlaceStyle.setText(String.valueOf(array.get(position).getPlaceStyle()));
}
#Override
public int getItemCount() {
return array.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView homeNewPlaceImg;
TextView homeNewAddress;
TextView homeNewplaceName;
TextView homeNewPlaceStyle;
public ViewHolder(#NonNull View itemView) {
super(itemView);
homeNewPlaceImg =itemView.findViewById(R.id.homeNewPlaceImg);
homeNewAddress =itemView.findViewById(R.id.homeNewAddress);
homeNewplaceName =itemView.findViewById(R.id.homeNewplaceName);
homeNewPlaceStyle =itemView.findViewById(R.id.homeNewPlaceStyle);
}
}
}
For reference my data structure
"dataA" : {
"placeA" : {
"20210411130750241" : {
"call" : "02020",
"extraD" : "TEST ExtraD",
"mapx" : "2380",
"mapy" : "505",
"memberTag" : [ "ga, na, gren" ],
"placeAddress" : "Ave Unit D 07072",
"placeCategory" : "restaurant",
"placeFootprint" : 0,
"placeName" : "hihihi",
"placeStyle" : "Visit",
"placeUploader" : "OYyLCJxiNiZAaEK0T6jVnZW69kg1",
"runningTime" : "Mon: 09:00-20:00\nTue: 09:09-19:00\n",
"shortD" : "TestShortD",
"thumbnail" : [ "https://search.pstatic.net/common/?autoRotate=true&quality=95&type=w750&src=https%3A%2F%2Fldb-phinf.pstatic.net%2F20200501_166%2F1588260117507zY7Er_JPEG%2FyLWif5MfrxciIvUrODQsKxkb.jpeg.jpg", "https://search.pstatic.net/common/?autoRotate=true&quality=95&type=w750&src=https%3A%2F%2Fldb-phinf.pstatic.net%2F20200501_159%2F1588260202284uxxDL_JPEG%2FjMEr_bE2PYkwwTccqGYPVptF.jpeg.jpg" ]
}
}
You can use HashMap in such cases:
HashMap<String,Objects> map = new HashMap<>();
and you can retrieve thumbnail from hashmap using below code:
map.get("thumbnail");
I have am trying to fetch Different types of List data using Retrofit.
I have make a List and put data on that.
Can anyone suggest me how I can fetch Different Type of Model Data? I have When I tried to put Object List to my Custom model list I got this error :
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to .....
Model Class
public class WorkType {
#SerializedName("type")
#Expose
private String type;
#SerializedName("worklist")
#Expose
private List<Object> worklist = null;
/**
* No args constructor for use in serialization
*
*/
public WorkType() {
}
/**
*
* #param worklist
* #param type
*/
public WorkType(String type, List<Object> worklist) {
super();
this.type = type;
this.worklist = worklist;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Object> getWorkList() {
return worklist;
}
public void setWorkList(List<Object> worklist) {
this.worklist = worklist;
}
}
Retrofit Interface
#FormUrlEncoded
#POST("worklist")
Call<ArrayList<WorkType>> worklist(
#Field("teamid") String teamID
);
Fragment from where I make a API request
public class WorkTypeListFragment extends Fragment {
private FragmentWorkTypeListBinding binding;
private LoadingDialog loadingDialog;
private Context context;
public WorkTypeListFragment() {
// Required empty public constructor
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
this.context = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
binding = DataBindingUtil.inflate(inflater,R.layout.fragment_work_type_list,container,false);
init();
String teamID = getActivity().getIntent().getStringExtra("teamid");
fetchClientDetails("team1");
return binding.getRoot();
}
private void init() {
loadingDialog = new LoadingDialog(getActivity());
}
private void fetchClientDetails(String teamID){
loadingDialog.startLoadingDialog(); // Added Loading Screen
Call<ArrayList<WorkType>> call = RetrofitClient
.getInstance()
.getRetrofitApi()
.worklist(teamID);
call.enqueue(new Callback<ArrayList<WorkType>>() {
#Override
public void onResponse(Call<ArrayList<WorkType>> call, Response<ArrayList<WorkType>> response) {
try{
if(response.code() == 200){
ArrayList<WorkType> workTypeArrayList = response.body();
//Log.d("TAG", "onResponse: "+workTypeArrayList.get(1).getWorkList().get(0).getClientname());
assert workTypeArrayList != null;
bindDataToView(workTypeArrayList);
} else {
Toast.makeText(getContext(), "Response Code is no 200", Toast.LENGTH_SHORT).show();
loadingDialog.dismissDialog();
}
}catch(Exception e){
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ArrayList<WorkType>> call, Throwable t) {
Toast.makeText(getContext(), "Something Went wrong! Please try again later!", Toast.LENGTH_SHORT).show();
loadingDialog.dismissDialog();
}
});
}
private void bindDataToView(ArrayList<WorkType> workTypeArrayList) {
WorkTypesAdapter adapter = new WorkTypesAdapter(context,workTypeArrayList);
binding.workTypeRv.setLayoutManager(new LinearLayoutManager(context));
binding.workTypeRv.setAdapter(adapter);
}
}
RecyclearView Adapter Class
public class WorkTypesAdapter extends RecyclerView.Adapter<WorkTypesAdapter.ViewHolder> {
private Context mCtx;
private List<WorkType> workTypeList;
private final static int survey = 1;
private final static int service = 2;
private final static int maintain = 3;
public WorkTypesAdapter(Context mCtx, List<WorkType> modelServiceList) {
this.mCtx = mCtx;
this.workTypeList = modelServiceList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.layout_worktype, null);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
WorkType currentWorkType = workTypeList.get(position);
String modelClass = currentWorkType.getType();
List<Object> objectList = currentWorkType.getWorkList();
switch (modelClass){
/*case "survey":
List<SurveyWorkList> surveyWorkLists = new ArrayList<>();
for (Object object : objectList) {
surveyWorkLists.add((SurveyWorkList) object);
holder.workType.setText(currentWorkType.getType());
holder.workTypeCount.setText(surveyWorkLists.size());
}
break;*/
case "service":
List<ServiceWorkList> serviceWorkLists = new ArrayList<>();
for (Object object : objectList) {
serviceWorkLists.add((ServiceWorkList) object);
}
/*holder.workType.setText(currentWorkType.getType());
holder.workTypeCount.setText(serviceWorkLists.size());*/
break;
/*case "maintain":
List<MaintainWorkList> maintainWorkLists = new ArrayList<>();
for (Object object : objectList) {
maintainWorkLists.add((MaintainWorkList) object);
}
holder.workType.setText(currentWorkType.getType());
holder.workTypeCount.setText(maintainWorkLists.size());
break;*/
default:
//Do nothing
}
/*holder.workType.setText(modelService.getType());
holder.workTypeCount.setText(workTypeList.size());*/
}
#Override
public int getItemCount() {
return workTypeList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView workType, workTypeCount;
public ViewHolder(#NonNull View itemView) {
super(itemView);
workType = itemView.findViewById(R.id.work_type_tv);
workTypeCount = itemView.findViewById(R.id.work_type_count_tv);
}
}
}
API response
[
{
"type": "survey",
"worklist": []
},
{
"type": "service",
"worklist": [
{
"serviceid": "HS2020031613054318",
"clientid": "R2020031612594874",
"clientname": "********",
"companyname": "",
"membership": "",
"phone": [
"*********"
],
"**************",
"account": 2,
"slot": "morning",
"orderstatus": "Completed",
"orderstatuscode": "8",
"remarks": ""
}
]
},
{
"type": "maintain",
"worklist": []
}
]
The survey and maintain will have different Parameter.
I have found the answer.
First, you have to make a model class:
#SerializedName("contents")
#Expose
private JsonElement contents = null;
In my API I got an element type. So you know in which type you have to parse the data. Let's say you have three types. So we will create a Type object:
switch(type)
case 1:
Type type = new TypeToken<ArrayList<Banner>>() {
}.getType();
ArrayList<Banner> bannerList = new Gson().fromJson(baseModel.getContents(), type);
I am setting up the recyclerview to show some data from the server and this is how my jsonpojo looks alike :
public class JSON {
public class MainCard {
#SerializedName("Cards")
public List<Cards> cards;
}
public class Cards {
#SerializedName("Title")
public String title;
#SerializedName("Items")
public List<ItemData> items;
}
public class ItemData {
#SerializedName("Name")
public String name;
#SerializedName("Thumb")
public String thumb;
#SerializedName("Link")
public String link;
}
}
and here is the adapter :
public class API_Adpater extends RecyclerView.Adapter<API_Adpater.CardsHolder> {
private List<JSON.ItemData> mlist;
private List<JSON.Cards> mCards;
private Context mcontext;
public API_Adpater(List<JSON.ItemData> mlists, List<JSON.Cards> titles, Context context) {
this.mlist = mlists;
this.mcontext = context;
this.mCards = titles;
}
#NonNull
#Override
public CardsHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.singleitems,viewGroup,false);
return new CardsHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CardsHolder cardsHolder, int i) {
final JSON.ItemData singleitem = mlist.get(i);
final JSON.Cards Title = mCards.get(i);
cardsHolder.textView.setText(Title.title);
cardsHolder.textView2.setText(singleitem.name);
cardsHolder.url = singleitem.thumb;
Glide.with(this.mcontext).load(cardsHolder.url).into(cardsHolder.imageView);
}
#Override
public int getItemCount() {
return mlist.size();
}
class CardsHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView;
TextView textView2;
String url;
CardsHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textView = itemView.findViewById(R.id.textView);
textView2 = itemView.findViewById(R.id.textView2);
}
}
}
and this is the mainactivity :
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(APIService.url)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<JSON.MainCard> call = service.getCards();
call.enqueue(new Callback<JSON.MainCard>() {
#Override
public void onResponse(Call<JSON.MainCard> call, Response<JSON.MainCard> response) {
if (response.isSuccessful()) {
JSON.MainCard mainCard = response.body();
if (mainCard != null && mainCard.cards !=null) {
List<JSON.ItemData> ru = mainCard.cards.items;
// Here on Above Line it can't get the mainCard.Cards.items; it is not showing the `.items` in the code;
setupRV(ru);
}
} else {
Toast.makeText(MainActivity.this, "Reposnce Error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<JSON.MainCard> call, Throwable t) {
Toast.makeText(MainActivity.this, "Check Internet Connectivity", Toast.LENGTH_SHORT).show();
}
});
}
private void setupRV(List<JSON.ItemData> list) {
RecyclerView recyclerView = findViewById(R.id.rv);
LinearLayoutManager lm = new LinearLayoutManager(this);
recyclerView.setLayoutManager(lm);
recyclerView.setAdapter(new API_Adpater(list,this));
}
}
On response of retrofit, I need to set the line like
List<JSON.ItemData> ru = mainCard.cards.items;
but it is not working as the codeeditor is not getting the .items variable
where is the error?
Can't set the recylcer view.
This is how my json looks alike :
{
"Cards": [
{
"Title": "Title",
"Items": [
{
"Name": "Name",
"Thumb": "Thumb",
"Link": "link"
}
]
},
{
"Title": "Title",
"Items": [
{
"Name": "Name",
"Thumb": "Thumb",
"Link": "link"
}
]
}
]
}
And this the error it can't find the items from the maincards.cards
I need to set the image from the url and name and title in the recycler view.
You're accessing items directly on list in this line
List<JSON.ItemData> ru = mainCard.cards.items;
here cards is a list, that's why you can't access items directly
Get the object of Cards and then use it
List<JSON.ItemData> ru = mainCard.cards.get(index).items;
Based on your requirements
you need to iterate over
if (mainCard != null && mainCard.cards !=null) {
List<JSON.ItemData> ru = new ArrayList();
for(Cards itemCard : mainCard.cards)
{
ru.addAll(itemCard.items);
}
setupRV(ru);
}
Try this..
List<MoviesApi.ItemData> ru = mainCard.cards.getItems();
Make separate class for each model as below.
-----------------------------------com.example.Card.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Card {
#SerializedName("Title")
#Expose
public String title;
#SerializedName("Items")
#Expose
public List<Item> items = null;
}
-----------------------------------com.example.Item.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Item {
#SerializedName("Name")
#Expose
public String name;
#SerializedName("Thumb")
#Expose
public String thumb;
#SerializedName("Link")
#Expose
public String link;
}
-----------------------------------com.example.MainCard.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MainCard {
#SerializedName("Cards")
#Expose
public List<Card> cards = null;
}
To create these pojos I used this site http://www.jsonschema2pojo.org/
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());
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);
}
}
});
}