I want to get data from my localhost with retrofit library. I want to make it so that when I click the button, all TextView will set new value. For example, TextView username will change "developer" in my json file. However, when I clicked the button I guess json returned null because I can not see anything. Can you help me solve this problem?
JSON File :
{"USERS":[{"_id":"587c0346f8469d38a0ea46bf",
"username":"developer",
"name":"Akif",
"surname":"Demirezen",
"tel":"023656565",
"age":"25",
"location_id":{"_id":"587c0346f8469d38a0ea46be",
"il":"istanbul",
"ilce":"cevizlibağ"},
"__v":0}]}
Example.class :
public class Example {
#SerializedName("USERS")
#Expose
private List<USER> uSERS = null;
public List<USER> getUSERS() {
return uSERS;
}
public void setUSERS(List<USER> uSERS) {
this.uSERS = uSERS;
}
}
LocationID Class :
public class LocationId {
#SerializedName("_id")
#Expose
private String id;
#SerializedName("il")
#Expose
private String il;
#SerializedName("ilce")
#Expose
private String ilce;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIl() {
return il;
}
public void setIl(String il) {
this.il = il;
}
public String getIlce() {
return ilce;
}
public void setIlce(String ilce) {
this.ilce = ilce;
}
}
Main Activity Class :
public class MainActivity extends AppCompatActivity {
TextView tid,tusername,tname,tsurname,tage,ttel,tlocationid;
Button butonverilerigoster;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tid = (TextView) findViewById(R.id.t_id);
tusername = (TextView) findViewById(R.id.t_username);
tname = (TextView) findViewById(R.id.t_name);
tsurname = (TextView) findViewById(R.id.t_surname);
tage = (TextView) findViewById(R.id.t_age);
ttel = (TextView) findViewById(R.id.t_tel);
tlocationid = (TextView) findViewById(R.id.t_locationid);
butonverilerigoster = (Button) findViewById(R.id.butonusergetir);
butonverilerigoster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Thread(new Runnable() {
public void run() {
ApiService.Factory.getInstance().getuse().enqueue(new Callback<USER>() {
#Override
public void onResponse(Call<USER> call, Response<USER> response) {
tid.setText(response.body().getId());
tusername.setText(response.body().getUsername());
tname.setText(response.body().getName());
tsurname.setText(response.body().getSurname());
tage.setText(response.body().getAge());
ttel.setText(response.body().getTel());
tlocationid.setText((CharSequence) response.body().getLocationId());
}
#Override
public void onFailure(Call<USER> call, Throwable t) {
Log.e("Failed", t.getMessage());
}
});
}
}).start();
}
});
}
}
User class :
public class USER {
#SerializedName("_id")
#Expose
private String id;
#SerializedName("username")
#Expose
private String username;
#SerializedName("name")
#Expose
private String name;
#SerializedName("surname")
#Expose
private String surname;
#SerializedName("tel")
#Expose
private String tel;
#SerializedName("age")
#Expose
private String age;
#SerializedName("location_id")
#Expose
private LocationId locationId;
#SerializedName("__v")
#Expose
private Integer v;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public LocationId getLocationId() {
return locationId;
}
public void setLocationId(LocationId locationId) {
this.locationId = locationId;
}
public Integer getV() {
return v;
}
public void setV(Integer v) {
this.v = v;
}
}
Related
I am trying to insert realm lists to my realmdb in my first insert there is no problem but when I insert another realmList with a different class, my old values are deleted. So how can I insert a realmlist to DB? inserts are done separately.
RealmList<Product> insertedProduct = new RealmList<Product>();
RealmList<ProductSubCategory> insertedSubCategory = new RealmList<ProductSubCategory>();
RealmList<ProductMainCategory> insertedMainCategory = new RealmList<ProductMainCategory>();
... inserting to realm list firt time ...
insertRealmList(insertedProduct); //inserting to realmDB first time
insertRealmList(insertedSubCategory); //inserting to realmDB first time
insertRealmList(insertedMainCategory); //inserting to realmDB first time
first insert to realmDB
RealmList insert function
private void insertRealmList(final RealmList realmObject) {
mRealm = Realm.getDefaultInstance();
realmTask = mRealm.executeTransactionAsync(
new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(realmObject);
}
},
new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Log.i(TAG, "onSuccess: successfully inserted data");
}
},
new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Log.i(TAG, "onError: error while inserting " + "error: " + error);
}
}
);
}
... inserting to realm list second time...
insertRealmList(insertedLanguages); //insert realmDB second time
second insert to realmDB
PRODUCT MODEL
package Model;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.Ignore;
import io.realm.annotations.Index;
import io.realm.annotations.PrimaryKey;
public class Product extends RealmObject {
#PrimaryKey
#Index
private int ID;
#Index
private int PLU_NO;
private String PRODUCT_NAME;
private String MAIN_CATEGORY;
private String SUB_CATEGORY;
private String TYPE;
private String TUS;
private Double PRICE;
private String CALORIE;
private String COOKING_TIME;
private RealmList<String> PRODUCT_NAME_LANGUAGES;
private RealmList<String> PRODUCT_DESCRIPTION_LANGUAGES;
private String IMAGE_BASE_HORIZONTAL; //4/3
private String IMAGE_BASE_VERTICAL; //16/9
private String VIDEO_NAME; //video name
#Ignore
private int AMOUNT;
#Ignore
private int WINDOW_AMOUNT = 1;
public Product(int ID, int PLU_NO, String PRODUCT_NAME, String MAIN_CATEGORY, String SUB_CATEGORY, String TYPE, String TUS, Double PRICE, String CALORIE, String COOKING_TIME, RealmList<String> PRODUCT_NAME_LANGUAGES, RealmList<String> PRODUCT_DESCRIPTION_LANGUAGES, String IMAGE_BASE_HORIZONTAL, String IMAGE_BASE_VERTICAL, String VIDEO_NAME) {
this.ID = ID;
this.PLU_NO = PLU_NO;
this.PRODUCT_NAME = PRODUCT_NAME;
this.MAIN_CATEGORY = MAIN_CATEGORY;
this.SUB_CATEGORY = SUB_CATEGORY;
this.TYPE = TYPE;
this.TUS = TUS;
this.PRICE = PRICE;
this.CALORIE = CALORIE;
this.COOKING_TIME = COOKING_TIME;
this.PRODUCT_NAME_LANGUAGES = PRODUCT_NAME_LANGUAGES;
this.PRODUCT_DESCRIPTION_LANGUAGES = PRODUCT_DESCRIPTION_LANGUAGES;
this.IMAGE_BASE_HORIZONTAL = IMAGE_BASE_HORIZONTAL;
this.IMAGE_BASE_VERTICAL = IMAGE_BASE_VERTICAL;
this.VIDEO_NAME = VIDEO_NAME;
}
public Product() {
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public int getPLU_NO() {
return PLU_NO;
}
public void setPLU_NO(int PLU_NO) {
this.PLU_NO = PLU_NO;
}
public String getPRODUCT_NAME() {
return PRODUCT_NAME;
}
public void setPRODUCT_NAME(String PRODUCT_NAME) {
this.PRODUCT_NAME = PRODUCT_NAME;
}
public String getMAIN_CATEGORY() {
return MAIN_CATEGORY;
}
public void setMAIN_CATEGORY(String MAIN_CATEGORY) {
this.MAIN_CATEGORY = MAIN_CATEGORY;
}
public String getSUB_CATEGORY() {
return SUB_CATEGORY;
}
public void setSUB_CATEGORY(String SUB_CATEGORY) {
this.SUB_CATEGORY = SUB_CATEGORY;
}
public String getTYPE() {
return TYPE;
}
public void setTYPE(String TYPE) {
this.TYPE = TYPE;
}
public String getTUS() {
return TUS;
}
public void setTUS(String TUS) {
this.TUS = TUS;
}
public Double getPRICE() {
return PRICE;
}
public void setPRICE(Double PRICE) {
this.PRICE = PRICE;
}
public String getCALORIE() {
return CALORIE;
}
public void setCALORIE(String CALORIE) {
this.CALORIE = CALORIE;
}
public String getCOOKING_TIME() {
return COOKING_TIME;
}
public void setCOOKING_TIME(String COOKING_TIME) {
this.COOKING_TIME = COOKING_TIME;
}
public RealmList<String> getPRODUCT_NAME_LANGUAGES() {
return PRODUCT_NAME_LANGUAGES;
}
public void setPRODUCT_NAME_LANGUAGES(RealmList<String> PRODUCT_NAME_LANGUAGES) {
this.PRODUCT_NAME_LANGUAGES = PRODUCT_NAME_LANGUAGES;
}
public RealmList<String> getPRODUCT_DESCRIPTION_LANGUAGES() {
return PRODUCT_DESCRIPTION_LANGUAGES;
}
public void setPRODUCT_DESCRIPTION_LANGUAGES(RealmList<String> PRODUCT_DESCRIPTION_LANGUAGES) {
this.PRODUCT_DESCRIPTION_LANGUAGES = PRODUCT_DESCRIPTION_LANGUAGES;
}
public String getIMAGE_BASE_HORIZONTAL() {
return IMAGE_BASE_HORIZONTAL;
}
public void setIMAGE_BASE_HORIZONTAL(String IMAGE_BASE_HORIZONTAL) {
this.IMAGE_BASE_HORIZONTAL = IMAGE_BASE_HORIZONTAL;
}
public String getIMAGE_BASE_VERTICAL() {
return IMAGE_BASE_VERTICAL;
}
public void setIMAGE_BASE_VERTICAL(String IMAGE_BASE_VERTICAL) {
this.IMAGE_BASE_VERTICAL = IMAGE_BASE_VERTICAL;
}
public String getVIDEO_NAME() {
return VIDEO_NAME;
}
public void setVIDEO_NAME(String VIDEO_NAME) {
this.VIDEO_NAME = VIDEO_NAME;
}
public int getAMOUNT() {
return AMOUNT;
}
public void setAMOUNT(int AMOUNT) {
this.AMOUNT = AMOUNT;
}
public int getWINDOW_AMOUNT() {
return WINDOW_AMOUNT;
}
public void setWINDOW_AMOUNT(int WINDOW_AMOUNT) {
this.WINDOW_AMOUNT = WINDOW_AMOUNT;
}
public void setDEFAULT_WINDOW_AMOUNT() {
this.WINDOW_AMOUNT = 1;
}
}
LANGUAGE MODEL
package Model;
import io.realm.RealmObject;
public class Language extends RealmObject {
#PrimaryKey
#Index
private int ID;
private String ICON;
private String NAME;
public Language(){
}
public Language(int ID, String ICON, String NAME) {
this.ID = ID;
this.ICON = ICON;
this.NAME = NAME;
}
public int getId() {
return ID;
}
public void setId(int id) {
this.ID = id;
}
public String getICON() {
return ICON;
}
public void setICON(String ICON) {
this.ICON = ICON;
}
public String getName() {
return NAME;
}
public void setName(String name) {
this.NAME = name;
}
}
Other two models are similar with product.
Please try the following method:
private <T extends RealmModel> void insertRealmList(final List<T> objects) {
try (Realm realmInstance = Realm.getDefaultInstance()) {
realmInstance.executeTransaction(realm -> {
for (T object : objects) {
realmInstance.insertOrUpdate(object);
}
});
}
}
Hope this helps!
I want fetch data from this link https://api.androidhive.info/contacts/.
Using Volley i am able to fetch this data but it is not working for list.
that's way i am using Retrofit but retrofit is not working for multiple class.
Api
public interface Api {
String BASE_URL = "https://api.androidhive.info";
#GET("/contacts")
Call<List<Contacts>> getHeroes();
#GET("phone")
Call<List<Phone>> getphone();
}
Jsonparser class
public class json_pas extends Fragment{
List<Contacts> herolist;
Retrofit retrofit;
TextView textView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.json_,null);
}
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textView= view.findViewById(R.id.json_tv);
herolist = new ArrayList <>();
retrofit= new Retrofit.Builder().baseUrl(Api.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
Api api = retrofit.create(Api.class);
Call<List<Contacts>> call= api.getHeroes();
call.enqueue(new Callback <List <Contacts>>() {
#Override
public void onResponse(Call <List <Contacts>> call, retrofit2.Response <List <Contacts>> response) {
Log.e("pass","1");
herolist = response.body();
}
#Override
public void onFailure(Call <List <Contacts>> call, Throwable t) {
Log.e("error","Retrofit error"+t.getMessage());
}
});
}
}
class model
class Contact {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("email")
#Expose
private String email;
#SerializedName("address")
#Expose
private String address;
#SerializedName("gender")
#Expose
private String gender;
#SerializedName("phone")
#Expose
private Phone phone;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Phone getPhone() {
return phone;
}
public void setPhone(Phone phone) {
this.phone = phone;
}
}
class Contacts {
#SerializedName("contacts")
#Expose
private List<Contact> contacts = null;
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
}
class Phone {
#SerializedName("mobile")
#Expose
private String mobile;
#SerializedName("home")
#Expose
private String home;
#SerializedName("office")
#Expose
private String office;
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getHome() {
return home;
}
public void setHome(String home) {
this.home = home;
}
public String getOffice() {
return office;
}
public void setOffice(String office) {
this.office = office;
}
}
please help me
You need to parse it in a JsonObject and get the contacts field which have the array! as now it's expecting a list of Contacts object as stated in the error message
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Contacts {
#SerializedName("contacts")
#Expose
private List<Contact> contacts = null;
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
}
and in the retrofit interface
#GET("/contacts")
Call<Contacts> getHeroes();
I am reading a JSON like this:
{
"matches": [{
"id": 246119,
"utcDate": "2018-08-17T18:15:00Z",
"status": "FINISHED",
"homeTeam": {
"id": 298,
"name": "Girona FC"
},
"awayTeam": {
"id": 250,
"name": "Real Valladolid CF"
},
"score": {
"winner": "DRAW",
"duration": "REGULAR"
}
}]
}
I must say that the JSON is valid. I am consuming this JSON through an API. I can correctly read the properties "id", "utc" and "status", but I could not with "score", "awayTeam" and "homeTeam". I don't really know how to work those properties. I'd like to handle each propertie of score, awayTeam, and homeTeam individually, for example, I want to get just the name of awayTeam and homeTeam and the 2 properties of score.
This, is my code:
MainActivity
public class MainActivity extends AppCompatActivity {
private Retrofit retrofit;
private static final String TAG = "Football";
private RecyclerView recyclerView;
private ListaPartidosAdapter listaPartidosAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
listaPartidosAdapter = new ListaPartidosAdapter(this);
recyclerView.setAdapter(listaPartidosAdapter);
recyclerView.setHasFixedSize(true);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this, VERTICAL, true);
recyclerView.setLayoutManager(layoutManager);
retrofit = new Retrofit.Builder()
.baseUrl("http://api.football-data.org/v2/")
.addConverterFactory(GsonConverterFactory.create())
.build();
obtenerDatos();
}
private void obtenerDatos() {
footballdataService service = retrofit.create(footballdataService.class);
Call<PartidosRespuesta> partidosRespuestaCall = service.obtenerlistaPartidos();
partidosRespuestaCall.enqueue(new Callback<PartidosRespuesta>() {
#Override
public void onResponse(Call<PartidosRespuesta> call, Response<PartidosRespuesta> response) {
if(response.isSuccessful()) {
PartidosRespuesta partidosRespuesta = response.body();
ArrayList<Partido> listaPartidos = partidosRespuesta.getMatches();
listaPartidosAdapter.adicionarListaPartidos(listaPartidos);
}
else {
Log.e(TAG, "onResponse: " + response.errorBody());
}
}
#Override
public void onFailure(Call<PartidosRespuesta> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
}
}
Now this is my interface. footballdataService
public interface footballdataService {
#GET("competitions/2014/matches")
Call<PartidosRespuesta> obtenerlistaPartidos();
}
This is PartidosRespuestas class
public class PartidosRespuesta {
private ArrayList<Partido> matches;
public ArrayList<Partido> getMatches() {
return matches;
}
public void setMatches(ArrayList<Partido> matches) {
this.matches = matches;
}
}
This, is the adapter.
public class ListaPartidosAdapter extends RecyclerView.Adapter<ListaPartidosAdapter.ViewHolder> {
private static final String TAG = "Football_Adapter";
private ArrayList<Partido> dataset;
private Context context;
public ListaPartidosAdapter(Context context) {
this.context = context;
dataset = new ArrayList<Partido>();
}
#Override
public ListaPartidosAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_partidos, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ListaPartidosAdapter.ViewHolder holder, int position) {
Partido p = dataset.get(position);
holder.status.setText(p.getId());
}
#Override
public int getItemCount() {
return dataset.size();
}
public void adicionarListaPartidos(ArrayList<Partido> listaPartidos){
dataset.addAll(listaPartidos);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView status;
public ViewHolder(View itemView) {
super(itemView);
status = (TextView) itemView.findViewById(R.id.status);
}
}
}
And this.., is Partido class
public class Partido {
private String id;
private String utcDate;
private String status;
private EquipoCasa homeTeam;
private EquipoVisita AwayTeam;
private Puntaje score;
public String getId() {
return id;
}
public String getUtcDate() {
return utcDate;
}
public String getStatus() {
return status;
}
public EquipoCasa getHomeTeam() {
return homeTeam;
}
public EquipoVisita getAwayTeam() {
return AwayTeam;
}
public Puntaje getScore() {
return score;
}
public void setId(String id) {
this.id = id;
}
public void setUtcDate(String utcDate) {
this.utcDate = utcDate;
}
public void setStatus(String status) {
this.status = status;
}
public void setHomeTeam(EquipoCasa homeTeam) {
this.homeTeam = homeTeam;
}
public void setAwayTeam(EquipoVisita awayTeam) {
AwayTeam = awayTeam;
}
public void setScore(Puntaje score) {
this.score = score;
}
public class EquipoCasa {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class EquipoVisita {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Puntaje {
private String winner;
private String duration;
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
}
POJO classes of your code should this:
AwayTeam.java
//AwayTeam
public class AwayTeam {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
PartidosRespuesta.java
//Object response
public class PartidosRespuesta {
#SerializedName("matches")
#Expose
private List<Match> matches = null;
public List<Match> getMatches() {
return matches;
}
public void setMatches(List<Match> matches) {
this.matches = matches;
}
}
HomeTeam.java
//HomeTeam
public class HomeTeam {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Score.java
//Score
public class Score {
#SerializedName("winner")
#Expose
private String winner;
#SerializedName("duration")
#Expose
private String duration;
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
Edit:
#Override
public void onBindViewHolder(ListaPartidosAdapter.ViewHolder holder, int position) {
Partido p = dataset.get(position);
HomeTeam homeTeam = p.getHomeTeam();
String nameHomeTeam = homeTeam.getName();
}
And tool convert json to java code: http://www.jsonschema2pojo.org/
try
public class Puntaje {
public String winner;
public String duration;
}
It's seems like you've problems with your models. Use this link to convert your json to java object.
I am trying to download data from the url ( JSON ) =
https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json
for the networking i have used retrofit, and these are my classes, whenever i try to access the nested classes or lists, it throws a fatal error.
MainActivity
public class MainActivity extends AppCompatActivity {
ArrayList<Recipe> mRecipies = new ArrayList<>();
public TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView)findViewById(R.id.text);
IRecipe iRecipe = RetrofitBuilder.Retrieve();
Call<ArrayList<Recipe>> recipe = iRecipe.getRecipe();
recipe.enqueue(new Callback<ArrayList<Recipe>>() {
#Override
public void onResponse(Call<ArrayList<Recipe>> call, Response<ArrayList<Recipe>> response) {
mRecipies = response.body();
text.setText(mRecipies.get(3).getIngredients().size());
}
#Override
public void onFailure(Call<ArrayList<Recipe>> call, Throwable t) {
}
});
MyRecipe class
public class Recipe {
private String id;
private String name;
private List<Ingredients> ingredients = new ArrayList<>();
private List<Steps> steps = new ArrayList<>();
private String servings;
public Recipe(String id, String name, String servings, List<Ingredients> ingredients, List<Steps> steps) {
this.id = id;
this.name = name;
this.ingredients = ingredients;
this.steps = steps;
this.servings = servings;
}
public Recipe(){
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Ingredients> getIngredients() {
return ingredients;
}
public void setIngredients(List<Ingredients> ingredients) {
this.ingredients = ingredients;
}
public List<Steps> getSteps() {
return steps;
}
public void setSteps(List<Steps> steps) {
this.steps = steps;
}
public String getServings() {
return servings;
}
public void setServings(String servings) {
this.servings = servings;
}
}
My ingredients class
public class Ingredients {
private String quantity;
private String measure;
private String ingredient;
public Ingredients(String quantity, String measure, String ingredient) {
this.quantity = quantity;
this.measure = measure;
this.ingredient = ingredient;
}
public Ingredients(){
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getMeasure() {
return measure;
}
public void setMeasure(String measure) {
this.measure = measure;
}
public String getIngredient() {
return ingredient;
}
public void setIngredient(String ingredient) {
this.ingredient = ingredient;
}
}
Retrofit classes
Builder
public final class RetrofitBuilder {
static IRecipe iRecipe;
public static IRecipe Retrieve() {
Gson gson = new GsonBuilder().create();
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
iRecipe = new Retrofit.Builder()
.baseUrl("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/")
.addConverterFactory(GsonConverterFactory.create(gson))
.callFactory(httpClientBuilder.build())
.build().create(IRecipe.class);
return iRecipe;
}
}
Interface
public interface IRecipe {
#GET("baking.json")
Call<ArrayList<Recipe>> getRecipe();
}
Stack Trace
FATAL EXCEPTION: main
Process: com.example.vamshi.retrofittrial, PID: 20350
android.content.res.Resources$NotFoundException: String resource ID #0x9
at android.content.res.Resources.getText(Resources.java:328)
at android.content.res.MiuiResources.getText(MiuiResources.java:123)
at android.widget.TextView.setText(TextView.java:4432)
at com.example.vamshi.retrofittrial.MainActivity$1.onResponse(MainActivity.java:34)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:742)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5527)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
07-08 19:07:00.145 20350-20350/com.example.vamshi.retrofittrial E/MQSEventManagerDelegate: failed to get MQSService.
Well, setText doesnt allow integers.
So instead of
text.setText(mRecipies.get(3).getIngredients().size());
use
text.setText(String.valueof(mRecipies.get(3).getIngredients().size()));
this is my first post and I'm newbie in firebase, sorry if i'm doing some stupid question. Hope you can help me.
This is my bean:
public class Fornecedor implements Comparable{
private int id;
private String nome;
private String email;
private int logo;
private Set<Produto> produtos;
private Set<Representante> representantes;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getLogo() {
return logo;
}
public void setLogo(int logo) {
this.logo = logo;
}
public Set<Produto> getProdutos() {
return produtos;
}
public void setProdutos(HashSet<Produto> produtos) {
this.produtos = produtos;
}
public Set<Representante> getRepresentantes() {
return representantes;
}
public void setRepresentantes(HashSet<Representante> representantes) {
this.representantes = representantes;
}
}
This is my firebase data structure:
{
"fornecedores" : {
"avon" : {
"email" : "contato#avon.com.br",
"logo" : "avon.jpg",
"nome" : "Avon Cosméticos",
"produtos" : {
"cremex" : true,
"perfumex" : true
},
"representantes" : {
"jao" : true,
"ze" : true
}
},
... other nodes like above ...
}
}
This is what I'm trying to do:
Firebase ref = new Firebase("https://nasuakz.firebaseio.com/fornecedores");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println("Tem " + snapshot.getChildrenCount() + " fornecedores");
for (DataSnapshot fornecedorSnapshot : snapshot.getChildren()) {
Fornecedor fornecedor = fornecedorSnapshot.getValue(Fornecedor.class);
System.out.println(fornecedor.getNome() + " - " + fornecedor.getEmail());
}
}
}
and this is the error that happens on line 7 of above code:
Can not deserialize instance of java.util.HashSet
i know that is something wrong with mapping the json to my bean, but this works when i use parcelable, so i'm not understanding why this happen.
Your produtos and representantes are not sets, but maps. They map a String key to a Boolean value.
So you need to provide the proper mapping for them:
public class Fornecedor implements Comparable{
private int id;
private String nome;
private String email;
private int logo;
private Map<String, Boolean> produtos;
private Map<String, Boolean> representantes;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getNome() { return nome; }
public void setNome(String nome) { this.nome = nome; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public int getLogo() { return logo; }
public void setLogo(int logo) { this.logo = logo; }
public Map<String, Boolean> getProdutos() { return produtos; }
public Map<String, Boolean> getRepresentantes() { return representantes; }
}
You can of course add helper methods to look up the correct Produto and Representante objects. Just be sure to mark then as #JsonIgnore, so that Jackson doesn't try to serialize them.