Retrieve data from Firebase with complex model and print it inside adapter - java

How can i get branch Choix from Sondage and print it into my Adapter class.
Here's my ModelClass
AccueilItem
public class AccueilItem {
private String idSondage;
private String publisher;
private String titreSondage;
private ArrayList<ChoixItem> choix;
public AccueilItem() {
}
public AccueilItem(String idSondage, String publisher, String titreSondage, ArrayList<ChoixItem> choix) {
this.idSondage = idSondage;
this.publisher = publisher;
this.titreSondage = titreSondage;
this.choix = choix;
}
public String getIdSondage() {
return idSondage;
}
public void setIdSondage(String idSondage) {
this.idSondage = idSondage;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getTitreSondage() {
return titreSondage;
}
public void setTitreSondage(String titreSondage) {
this.titreSondage = titreSondage;
}
public ArrayList<ChoixItem> getChoix() {
return choix;
}
public void setChoix(ArrayList<ChoixItem> choix) {
this.choix = choix;
}
}
ChoixItem
public class ChoixItem extends ArrayList<ChoixItem> {
private String idChoix;
private String titreChoix;
public ChoixItem() {
}
public ChoixItem(String idChoix, String titreChoix) {
this.idChoix = idChoix;
this.titreChoix = titreChoix;
}
public String getIdChoix() {
return idChoix;
}
public void setIdChoix(String idChoix) {
this.idChoix = idChoix;
}
public String getTitreChoix() {
return titreChoix;
}
public void setTitreChoix(String titreChoix) {
this.titreChoix = titreChoix;
}
}
Inside my main class, I retreive my data successfully, but i can't get the branch Choix to print it
AcceilActivity
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
accueilItems.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
AccueilItem accueilModel = dataSnapshot.getValue(AccueilItem.class);
accueilItems.add(accueilModel);
}
accueilAdapter = new AccueilAdapter(AccueilActivity.this, (ArrayList<AccueilItem>) accueilItems);
recyclerView.setAdapter(accueilAdapter);
accueilAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(AccueilActivity.this, "Error:" + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
If anyone can help, I would be so grateful, i'm suck in this for 2 days.

Related

Problem: Can't convert object of type java.lang.String to type

I have a problem running this part of my application, I am using a recyclerwiew with its adapter inside this activity, but this error occurs:
Can not convert object of type java.lang.String to type.
I have used this same code many times and it always worked for me, I do not know what happens.
Part of problem:
homeModelList = new ArrayList<>();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("Listas").child(post.getLid());
Toast.makeText(ProductListActivity.this, post.getLid(), Toast.LENGTH_SHORT).show();
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
homeModelList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
HomeModel homeModel = snapshot.getValue(HomeModel.class);
if (post.getLid().equals(post.getUidL())){
homeModelList.add(homeModel);
}
}
mAdapter = new ProductoAdapter(getApplicationContext(), homeModelList);
recycler_viewLista.setAdapter(mAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Class:
import java.io.Serializable;
public class HomeModel implements Serializable {
private String Titulo;
private String Uid;
private String Lid;
private String Producto;
private Integer Cantidad;
private String UidL;
public HomeModel() {
}
public HomeModel(String titulo, String uid, String lid, String producto, Integer cantidad, String uidL) {
Titulo = titulo;
Uid = uid;
Lid = lid;
Producto = producto;
Cantidad = cantidad;
UidL = uidL;
}
public String getTitulo() {
return Titulo;
}
public void setTitulo(String titulo) {
Titulo = titulo;
}
public String getUid() {
return Uid;
}
public void setUid(String uid) {
Uid = uid;
}
public String getLid() {
return Lid;
}
public void setLid(String lid) {
Lid = lid;
}
public String getProducto() {
return Producto;
}
public void setProducto(String producto) {
Producto = producto;
}
public Integer getCantidad() {
return Cantidad;
}
public void setCantidad(Integer cantidad) {
Cantidad = cantidad;
}
public String getUidL() {
return UidL;
}
public void setUidL(String uidL) {
UidL = uidL;
}
}
Change the following:
public void onDataChange(DataSnapshot dataSnapshot) {
homeModelList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
HomeModel homeModel = snapshot.getValue(HomeModel.class);
if (post.getLid().equals(post.getUidL())){
homeModelList.add(homeModel);
}
}
into this:
public void onDataChange(DataSnapshot dataSnapshot) {
homeModelList.clear();
HomeModel homeModel = dataSnapshot.getValue(HomeModel.class);
if (post.getLid().equals(post.getUidL())){
homeModelList.add(homeModel);
}

How to fill the RecyclerView with nested object from firebase

This is the event object that I want to inflate with RecyclerView:
public class Event {
private String mName;
private String mId;
private String mDate;
private String mPlace;
private User mUser;
private Category mCat;
private String mDescription;
public void setmEventCat(Map<String, Category> mEventCat) {
this.mEventCat = mEventCat;
}
public Map<String, Category> getmEventCat() {
return mEventCat;
}
private Map<String,Category> mEventCat;
public String getmDescription() {
return mDescription;
}
public void setDescription(String mDescription) {
this.mDescription = mDescription;
}
public Category getCat() {
return mCat;
}
public void setCat(Category mCat) {
this.mCat = mCat;
}
public String getDate() {
return mDate;
}
public String getPlace() {
return mPlace;
}
private ArrayList<User> mList;
public Event() {
}
public String getName() {
return mName;
}
public void setName(String mName) {
this.mName = mName;
}
public void setDate(String mDate) {
this.mDate = mDate;
}
public void setPlace(String mPlace) {
this.mPlace = mPlace;
}
public String getId() {
return mId;
}
public void setId(String mId) {
this.mId = mId;
}
}
The nested Category object:
public class Category implements Serializable{
private String mCatName;
private String mCatID;
public Category() {
}
public Category(String mCatName) {
this.mCatName = mCatName;
}
public String getCatName() {
return mCatName;
}
public String getCatID() {
return mCatID;
}
public void setCatName(String mCatName) {
this.mCatName = mCatName;
}
public void setCatID(String mCatID) {
this.mCatID = mCatID;
}
}
How I retrieve the data from firebase:
mDataBase = FirebaseDatabase.getInstance().getReference("Event");
mEvents = new ArrayList<Event>();
mEvent=new Event();
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mDataBase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
try {
for (DataSnapshot eventSnapshot : dataSnapshot.getChildren()) {
Event event = eventSnapshot.getValue(Event.class);
String id = eventSnapshot.getKey();
mEvents.add(event);
mRecyclerView.scrollToPosition(mEvents.size() - 1);
mAdapter.notifyItemInserted(mEvents.size() - 1);
}
}
catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mAdapter = new EventAdapter(mContext, mEvents);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
My EventAdapter:
#Override
public void onBindViewHolder(EventAdapter.ViewHolder holder, int position) {
mEvent = mEvents.get(position);
holder.mEventName.setText(mEvent.getName());
//Every time I tried to add this line to set category name
//the NullPointerException error occurs
holder.mEventCategory.setText(mEvent.getCat().getCatName());
holder.mEventDate.setText(mEvent.getDate());
}
The ViewHolder Class:
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView mEventName, mEventDate,mEventCategory;
public ViewHolder(View itemView) {
super(itemView);
mEventName = itemView.findViewById(R.id.eventName_tv);
mEventDate = itemView.findViewById(R.id.date_tv);
mEventCategory = itemView.findViewById(R.id.categoryTv);
}
}
#Override
public EventAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_event, parent, false);
return new ViewHolder(view);
}
The problem is the Event is displayed as I expected, but I cannot get the category inside the event and bind it to my widget by simply calling the getCat(). I know this may caused by asynchronous Firebase API. How can I set up the TextView with the nested category object.
This is my FINAL piece of my application, any hints would be a great help.
Thanks in advance!
I figure out the question that may be useful for other people. Before adding the event object to the list, I retrieve the nested object by key and assign it to category object. Finally, linking it with event...
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
try {
for (DataSnapshot eventSnapshot : dataSnapshot.getChildren()) {
Event event = eventSnapshot.getValue(Event.class);
String id = eventSnapshot.getKey();
mCategory = eventSnapshot.child(id).getValue(Category.class);
event.setCat(mCategory);
mEvents.add(event);
mRecyclerView.scrollToPosition(mEvents.size() - 1);
mAdapter.notifyItemInserted(mEvents.size() - 1);
}
}
catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
}
Then binding the desired data with widget by calling the pojo getter method (nothing's changed here).
#Override
public void onBindViewHolder(EventAdapter.ViewHolder holder, int position) {
mEvent = mEvents.get(position);
holder.mEventName.setText(mEvent.getName());
holder.mEventCategory.setText(mEvent.getCat().getCatName());
holder.mEventDate.setText(mEvent.getDate());
}

NullPointerException when i want to GET my data from my model class

In my Application in android i want to GET data from my web service to my recycle view, instead i got my data i got an error, here is my code
public class UserMenuActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_menu);
retrofit = new Retrofit.Builder().baseUrl("http://172.31.32.17:9290/")
.addConverterFactory(GsonConverterFactory.create())
.build();
afs = retrofit.create(AdminFullService.class);
responseLoginHome = (ResponseLoginHome) getIntent().getSerializableExtra("data");
initViews();
getCustomer = new getCustomer();
}
private void initViews() {
recyclerViewCustomer = (RecyclerView) findViewById(R.id.recycler_view_user_menu);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerViewCustomer.setLayoutManager(layoutManager);
recyclerViewCustomer.setHasFixedSize(true);
adapterCustomer = new DataAdapterCustomer(this, getCustomerList);
loadData();
}
private void loadData() {
Call<ResponseCustomerData> callCustomer = afs.customerDataView("bearer " + responseLoginHome.getData().getAuth_token());
callCustomer.enqueue(new Callback<ResponseCustomerData>() {
#Override
public void onResponse(Call<ResponseCustomerData> call, Response<ResponseCustomerData> response) {
ResponseCustomerData responseCustomerData = response.body();
getCustomerList.clear();
getCustomerList.addAll(responseCustomerData.getData()); //this is where i got error in my logcat
recyclerViewCustomer.setAdapter(adapterCustomer);
adapterCustomer.notifyDataSetChanged();
getCustomer.getTanggalLahir().substring(0,10);
Toast.makeText(UserMenu.this, getCustomer.getTanggalLahir(), Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ResponseCustomerData> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
}
and i have got this error
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.ipul.aprovementfullservice.Model.ResponseCustomerData.getData()' on a null object reference
at com.example.ipul.aprovementfullservice.UI.UserMenu$1.onResponse(UserMenu.java:77)
when i use my debug mode the responseCustomerData is null, and then i got confused why i got error like this, i create my model response just like my web service ask
sorry for bad grammar, English is not my native language
So i hope you all hand me your help, thank you
EDIT this is my list getCustomer
public class getCustomer{
public String getNoHP() {
return noHP;
}
public void setNoHP(String noHP) {
this.noHP = noHP;
}
public String getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(String registrationDate) {
this.registrationDate = registrationDate;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getNoID() {
return noID;
}
public void setNoID(String noID) {
this.noID = noID;
}
public String getJenisID() {
return jenisID;
}
public void setJenisID(String jenisID) {
this.jenisID = jenisID;
}
public String getTanggalLahir() {
return tanggalLahir;
}
public void setTanggalLahir(String tanggalLahir) {
this.tanggalLahir = tanggalLahir;
}
public String getJenisKelamin() {
return jenisKelamin;
}
public void setJenisKelamin(String jenisKelamin) {
this.jenisKelamin = jenisKelamin;
}
public String getNamaIbuKandung() {
return namaIbuKandung;
}
public void setNamaIbuKandung(String namaIbuKandung) {
this.namaIbuKandung = namaIbuKandung;
}
public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public String getProvinsi() {
return provinsi;
}
public void setProvinsi(String provinsi) {
this.provinsi = provinsi;
}
public String getKota() {
return kota;
}
public void setKota(String kota) {
this.kota = kota;
}
public String getKecamatan() {
return kecamatan;
}
public void setKecamatan(String kecamatan) {
this.kecamatan = kecamatan;
}
public String getKelurahan() {
return kelurahan;
}
public void setKelurahan(String kelurahan) {
this.kelurahan = kelurahan;
}
public String getKodepos() {
return kodepos;
}
public void setKodepos(String kodepos) {
this.kodepos = kodepos;
}
public String getAlamatDomosili() {
return alamatDomosili;
}
public void setAlamatDomosili(String alamatDomosili) {
this.alamatDomosili = alamatDomosili;
}
public String getProvinsiDomisili() {
return provinsiDomisili;
}
public void setProvinsiDomisili(String provinsiDomisili) {
this.provinsiDomisili = provinsiDomisili;
}
public String getKotaDomisili() {
return kotaDomisili;
}
public void setKotaDomisili(String kotaDomisili) {
this.kotaDomisili = kotaDomisili;
}
public String getKecamatanDomisili() {
return kecamatanDomisili;
}
public void setKecamatanDomisili(String kecamatanDomisili) {
this.kecamatanDomisili = kecamatanDomisili;
}
public String getKelurahanDomisili() {
return kelurahanDomisili;
}
public void setKelurahanDomisili(String kelurahanDomisili) {
this.kelurahanDomisili = kelurahanDomisili;
}
public String getKodeposDomisili() {
return kodeposDomisili;
}
public void setKodeposDomisili(String kodeposDomisili) {
this.kodeposDomisili = kodeposDomisili;
}
public String getFotoID() {
return fotoID;
}
public void setFotoID(String fotoID) {
this.fotoID = fotoID;
}
public String getRegisterStatus() {
return registerStatus;
}
public void setRegisterStatus(String registerStatus) {
this.registerStatus = registerStatus;
}
public String getKeterangan() {
return keterangan;
}
public void setKeterangan(String keterangan) {
this.keterangan = keterangan;
}
public String getFotoTandaTangan() {
return fotoTandaTangan;
}
public void setFotoTandaTangan(String fotoTandaTangan) {
this.fotoTandaTangan = fotoTandaTangan;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
and this my model ResponseCustomerData
public class ResponseCustomerData{
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public List<getCustomer> getData() {
return data;
}
public void setData(List<getCustomer> data) {
this.data = data;
}
}
Please try this, you have to check if your response is null or not.
Call<ResponseCustomerData> callCustomer = afs.customerDataView("bearer " + responseLoginHome.getData().getAuth_token());
callCustomer.enqueue(new Callback<ResponseCustomerData>() {
#Override
public void onResponse(Call<ResponseCustomerData> call, Response<ResponseCustomerData> response) {
ResponseCustomerData responseCustomerData = response.body();
getCustomerList.clear();
if(responseCustomerData!=null){ // check data retrive or not
if(responseCustomerData.getData()!=null){
getCustomerList.addAll(responseCustomerData.getData());
recyclerViewCustomer.setAdapter(adapterCustomer);
adapterCustomer.notifyDataSetChanged();
getCustomer.getTanggalLahir().substring(0,10);
Toast.makeText(UserMenu.this, getCustomer.getTanggalLahir(), Toast.LENGTH_SHORT).show();
} else {
Log.d("Error", responseCustomerData.getError());
}
}
}
#Override
public void onFailure(Call<ResponseCustomerData> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});

Firebase getKey returning long, Failed to convert a value of type java.lang.String to long

I'm trying to retrieve values from the database to display on views but im getting this crash right here
FATAL EXCEPTION: main
Process: com.example.ahmad.carrental, PID: 15975
com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to long
at com.google.android.gms.internal.zzear.zzb(Unknown Source)
at com.google.android.gms.internal.zzear.zza(Unknown Source)
at com.google.android.gms.internal.zzear.zzb(Unknown Source)
at com.google.android.gms.internal.zzeas.zze(Unknown Source)
at com.google.android.gms.internal.zzear.zzb(Unknown Source)
at com.google.android.gms.internal.zzear.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at com.example.ahmad.carrental.Utilities.FirebaseUtilities.getCarData(FirebaseUtilities.java:178)
at com.example.ahmad.carrental.CarPost.CreatePostActivity$1$1.onDataChange(CreatePostActivity.java:100)
at com.google.android.gms.internal.zzduz.zza(Unknown Source)
at com.google.android.gms.internal.zzdwu.zzbvb(Unknown Source)
at com.google.android.gms.internal.zzdxa.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6605)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:999)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:889)
The classes are as follows
Car Model
public class Car {
private String brand;
private String id;
private int price;
private String model;
private long distance;
private String status;
private String picture;
private String location;
private String description;
public Car() {
}
public Car(String brand, String id, int price, String model, long distance, String status, String picture, String location, String description) {
this.brand = brand;
this.id = id;
this.price = price;
this.model = model;
this.distance = distance;
this.status = status;
this.picture = picture;
this.location = location;
this.description = description;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public long getDistance() {
return distance;
}
public void setDistance(long distance) {
this.distance = distance;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
User Model
public class User {
private String email;
private String id;
private String name;
private int phonenumber;
public User(String email, String id, String name,int phonenumber) {
this.email = email;
this.id = id;
this.name = name;
this.phonenumber = phonenumber;
}
public User(){
}
public int getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(int phonenumber) {
this.phonenumber = phonenumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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;
}
}
Database Querying Function
public Car getCarData(DataSnapshot dataSnapshot) {
Log.i(TAG,"getCardData: Getting car data from database");
Car data = new Car();
for(DataSnapshot ds :dataSnapshot.getChildren()){
if(ds.getKey().equals(context.getString(R.string.dbname_car_post))){
try{
data.setId(ds.child(userID).getValue(Car.class).getId());
data.setBrand(ds.child(userID).getValue(Car.class).getBrand());
data.setDescription(ds.child(userID).getValue(Car.class).getDescription());
data.setModel(ds.child(userID).getValue(Car.class).getModel());
data.setDistance(ds.child(userID).getValue(Car.class).getDistance());
data.setPicture(ds.child(userID).getValue(Car.class).getPicture());
data.setStatus(ds.child(userID).getValue(Car.class).getStatus());
data.setLocation(ds.child(userID).getValue(Car.class).getLocation());
data.setPrice(ds.child(userID).getValue(Car.class).getPrice());
}catch (NullPointerException e){
Log.d(TAG, "getCarData: NullPointerException : " + e.getMessage());
}
}
}
return data;
}
Activity that im retrieving the data from
CreateCarPost Activity
public class CreatePostActivity extends AppCompatActivity implements CreatePostView,AdapterView.OnItemSelectedListener{
//Activity Tag
private static final String TAG ="CreateCarPost";
//Spinners
Spinner statusSpinner;
Spinner brandSpinner;
//Adapter of spinners
ArrayAdapter mArrayAdapter;
ArrayAdapter mArrayAdapter2;
//views
private TextView tvDistance;
private EditText etDistance;
private AutoCompleteTextView etCarLocation;
private CircleImageView civPicture;
private EditText etPrice;
private EditText etDescription;
private EditText etModel;
private ImageView checkButton;
//Strings
private String carLoactionStr;
private String carBrandStr;
private String carStatusStr;
//layout containg the views
private LinearLayout layoutContainer;
//To adjust dynamic views margins
LinearLayout.LayoutParams layoutParamsTv,layoutParamsEt;
//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mDatabaseReference;
private ValueEventListener singleValueEventListener;
private FirebaseUtilities mFirebaseUtilities;
Context mContext;
CreatePostPresenter createPostPresenter;
private Car car;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_post);
initialization();
setupFirebaseAuth();
setUpLocationSpinner();
//Assigning Car object with its data from database.
io.reactivex.Observable.create(new ObservableOnSubscribe() {
#Override
public void subscribe(ObservableEmitter emitter) throws Exception {
singleValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
car = mFirebaseUtilities.getCarData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "CANCELLED.");
}
};
mDatabaseReference.addValueEventListener(singleValueEventListener);
}
}).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe();
checkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createPostPresenter.onSaveChanges(car);
}
});
}
//initalizing everything necessary here
public void initialization(){
mContext = getApplicationContext();
createPostPresenter = new CreatePostPresenter(this,this);
//Adapter set up for spinners
mArrayAdapter2 = ArrayAdapter.createFromResource(this,R.array.car_brands,android.R.layout.simple_spinner_item);
mArrayAdapter = ArrayAdapter.createFromResource(this,R.array.car_status_array,android.R.layout.simple_spinner_item);
//Status spinner set up
statusSpinner = findViewById(R.id.createPostCarStatusSpinner_ID);
statusSpinner.setAdapter(mArrayAdapter);
statusSpinner.setOnItemSelectedListener(this);
//Brand spinner set up
brandSpinner = findViewById(R.id.createPostCarBrandSpinner_ID);
brandSpinner.setAdapter(mArrayAdapter2);
brandSpinner.setOnItemSelectedListener(this);
layoutContainer = findViewById(R.id.createPostLinearLayout_ID);
tvDistance = new TextView(this);
tvDistance.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
tvDistance.setText("Distance Travelled");
etDistance = new EditText(this);
etDistance.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//margin settings editText
layoutParamsEt = (LinearLayout.LayoutParams)etDistance.getLayoutParams();
layoutParamsEt.setMargins(0,10,0,0);
etDistance.setLayoutParams(layoutParamsEt);
//margin settings textView
layoutParamsTv = (LinearLayout.LayoutParams)tvDistance.getLayoutParams();
layoutParamsTv.setMargins(0,10,0,0);
tvDistance.setLayoutParams(layoutParamsTv);
etCarLocation = findViewById(R.id.createPostCarLocation_ID);
etDescription = findViewById(R.id.createPostCarDes_ID);
etPrice = findViewById(R.id.createPostCarPrice_ID);
etModel = findViewById(R.id.createPostCarModel_ID);
checkButton = findViewById(R.id.check_ID);
mFirebaseUtilities = new FirebaseUtilities(this);
}
private void setUpLocationSpinner() {
ArrayAdapter<String> listOfCities = new ArrayAdapter<>(getBaseContext(),
android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.TR_cities));
//--- to ensure user is restricted to selections from drop-down menu
etCarLocation.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
carLoactionStr = etCarLocation.getAdapter().getItem(position).toString();
}
});
etCarLocation.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
for (int i = 0; i < etCarLocation.getAdapter().getCount(); i++) {
if (etCarLocation.getText().toString().equals(etCarLocation.getAdapter().getItem(i))) {
carLoactionStr = etCarLocation.getAdapter().getItem(i).toString();
} else
carLoactionStr = null;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
//start autocomplete after 1 letter
etCarLocation.setThreshold(1);
etCarLocation.performCompletion();
etCarLocation.setAdapter(listOfCities);
}
/**
* Listener for car status spinner
* #param parent
* #param view
* #param position
* #param id
*/
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Spinner spinner = (Spinner)parent;
if(spinner.getId() == R.id.createPostCarStatusSpinner_ID){
TextView textView = (TextView) view;
carStatusStr = textView.getText().toString();
addDynamicViews(position);
}
else if(spinner.getId() == R.id.createPostCarBrandSpinner_ID){
TextView textView = (TextView) view;
carBrandStr = textView.getText().toString();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
/**
* Dynamic views creation done by handling user spinner selection for first hand or second hand car status.
*#param position: position of selected value from spinner
*/
public void addDynamicViews(int position){
if(position == 1){
layoutContainer.addView(tvDistance);
layoutContainer.addView(etDistance);
}
else if(position == 0){
mFirebaseUtilities.removeNodeDynamically();
layoutContainer.removeView(tvDistance);
layoutContainer.removeView(etDistance);
}
}
#Override
public void setBrand(String brand) {
}
#Override
public void setPrice(int price) {
}
#Override
public void setLocation(String location) {
}
#Override
public void setDescription(String description) {
}
#Override
public void setModel(String model) {
}
#Override
public void setDistance(long distance) {
}
#Override
public void setStatus(String status) {
}
#Override
public void setPicture(String picture) {
}
#Override
public String getBrand() {
return carBrandStr;
}
#Override
public String getDescription() {
return etDescription.getText().toString();
}
#Override
public String getLocation() {
return carLoactionStr;
}
#Override
public String getModel() {
return etModel.getText().toString();
}
#Override
public String getStatus() {
return carStatusStr;
}
#Override
public String getPicture() {
return null;
}
#Override
public int getPrice() {
String priceViewTemp = etPrice.getText().toString();
if (priceViewTemp.equals("")) {
return 0;
} else {
return Integer.valueOf(etPrice.getText().toString());
}
}
#Override
public long getDistance() {
String distanceViewTemp = etDistance.getText().toString();
if (distanceViewTemp.equals("")) {
return 0;
} else {
return Integer.valueOf(etDistance.getText().toString());
}
}
/*************************************** Firebase *******************************************/
private void setupFirebaseAuth() {
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference();
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//User is signed in
Log.d(TAG, "onAuthStateChanged: user signed in : " + user.getUid());
} else {
//User is signed out
Log.d(TAG, "onAuthStateChanged: user signed out");
}
}
};
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onPause() {
super.onPause();
if (singleValueEventListener != null) {
mDatabaseReference.removeEventListener(singleValueEventListener);
}
}
#Override
public void onResume(){
super.onResume();
mDatabaseReference.addListenerForSingleValueEvent(singleValueEventListener);
}
}
Firebase Structure
Firebase Structure
Haven't read if much, but i first noticed something here.
for(DataSnapshot ds :dataSnapshot.getChildren()){
if(ds.getKey().equals(context.getString(R.string.dbname_car_post))){
try{ }
The key you're trying to retrieve is an Object. So i would propose we convert it string first, sample down here.
for(DataSnapshot ds :dataSnapshot.getChildren()){
Object myKey=ds.getKey;
if(myKey.toString().equals(context.getString(R.string.dbname_car_post))){
try{ }
}}
Let me know what happens next!

java.lang.NullPointerException error on Retrofit onResponse

Good day, I'm using Retrofit for the first time and I can't seem to get it to work. working on an app that get crypto currency rates in local currencies, here is the api link, JSON format
{
"BTC": {
"USD": 6019.1,
"EUR": 5139.44,
"NGN": 2136243.25
},
"ETH": {
"USD": 290.98,
"EUR": 250.03,
"NGN": 103031.01
}
}
Here are my models (from http://www.jsonschema2pojo.org/): UPDATED
public class CryptoCurrency {
#SerializedName("BTC")
#Expose
private BTC BTC;
#SerializedName("ETH")
#Expose
private ETH ETH;
public BTC getBTC() {
return BTC;
}
public void setBTC(BTC BTC) {
this.BTC = BTC;
}
public ETH getETH() {
return ETH;
}
public void setETH(ETH ETH) {
this.ETH = ETH;
}
public class BTC {
#SerializedName("USD")
#Expose
private Double USD;
#SerializedName("EUR")
#Expose
private Double EUR;
#SerializedName("NGN")
#Expose
private Double NGN;
public Double getUSD() {
return USD;
}
public void setUSD(Double USD) {
this.USD = USD;
}
public Double getEUR() {
return EUR;
}
public void setEUR(Double EUR) {
this.EUR = EUR;
}
public Double getNGN() {
return NGN;
}
public void setNGN(Double NGN) {
this.NGN = NGN;
}
}
public class ETH {
#SerializedName("USD")
#Expose
private Double USD;
#SerializedName("EUR")
#Expose
private Double EUR;
#SerializedName("NGN")
#Expose
private Double NGN;
public Double getUSD() {
return USD;
}
public void setUSD(Double USD) {
this.USD = USD;
}
public Double getEUR() {
return EUR;
}
public void setEUR(Double EUR) {
this.EUR = EUR;
}
public Double getNGN() {
return NGN;
}
public void setNGN(Double NGN) {
this.NGN = NGN;
}
}
}
My interface:
public interface CurrencyInterface {
#GET("/data/pricemulti/")
Call<CryptoCurrency.BTC> currency(#Query("crypto") String crypto, #Query("local") String local);
}
my onResponse method:
call.enqueue(new Callback<CryptoCurrency.BTC>() {
#Override
public void onResponse(Call<CryptoCurrency.BTC> call, Response<CryptoCurrency.BTC> response) {
String currency = response.body().toString();
Toast.makeText(getApplicationContext(), "result " + currency, Toast.LENGTH_LONG).show();
Log.i("MainActivity", currency);
}
#Override
public void onFailure(Call<CryptoCurrency.BTC> call, Throwable t) {
}
});
When I run the code and check my log I get this error:
java.lang.NullPointerException
at com.example.raynold.cryptorates.MainActivity$1.onResponse(MainActivity.java:53)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
UPDATED---------
My MainActivity class
public class MainActivity extends AppCompatActivity {
private RecyclerView mCurrencyRecycler;
private Button mclickMe;
private CurrencyAdapter mCurrencyAdapter;
private List<CryptoCurrency> mCurrencyList;
private CurrencyInterface mCurrencyInterface;
private LinearLayoutManager mLinearLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCurrencyRecycler = (RecyclerView) findViewById(R.id.rv_rates);
mLinearLayoutManager = new LinearLayoutManager(this);
mCurrencyRecycler.setLayoutManager(mLinearLayoutManager);
mCurrencyRecycler.setHasFixedSize(true);
mclickMe = (Button) findViewById(R.id.click_me);
mCurrencyInterface = ApiClient.getApiClient().create(CurrencyInterface.class);
Call<CryptoCurrency.BTC> call = mCurrencyInterface.currency("BTC", "NGN");
call.enqueue(new Callback<CryptoCurrency.BTC>() {
#Override
public void onResponse(Call<CryptoCurrency.BTC> call, Response<CryptoCurrency.BTC> response) {
String currency = response.body().toString();
Toast.makeText(getApplicationContext(), "result " + currency, Toast.LENGTH_LONG).show();
Log.i("MainActivity", currency);
}
#Override
public void onFailure(Call<CryptoCurrency.BTC> call, Throwable t) {
}
});
mclickMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
I will also like to know how i can get it to work with a recyclerview since the JSON is of object type not Array.
public class CryptoCurrency {
#SerializedName("BTC")
#Expose
private BTC BTC;
#SerializedName("ETH")
#Expose
private ETH ETH;
public BTC getBTC() {
return BTC;
}
public void setBTC(BTC BTC) {
this.BTC = BTC;
}
public ETH getETH() {
return ETH;
}
public void setETH(ETH ETH) {
this.ETH = ETH;
}
class ETH {
...
}
class BTC {
...
}
}
In your interface CurrencyInterface use like
#GET("/data/pricemulti")
Call<CryptoCurrency> currency(#Query("fsyms") String crypto, #Query("tsyms") String local);
Handle like
Call<CryptoCurrency> call = mCurrencyInterface.currency("BTC", "NGN");
call.enqueue(new Callback<CryptoCurrency>() {
#Override
public void onResponse(Call<CryptoCurrency> call, Response<CryptoCurrency> response) {
BTC btc = response.body().getBTC();
Toast.makeText(getApplicationContext(), "result " + btc.getNGN(), Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<CryptoCurrency.BTC> call, Throwable t) {
}
});
You should not use backslash at the start and end of URLs.
Try
#GET("data/pricemulti")
instead of
#GET("/data/pricemulti/")
Change your onResponse method like this:
...........
call.enqueue(new Callback<CryptoCurrency.BTC>() {
#Override
public void onResponse(Call<CryptoCurrency.BTC> call, Response<CryptoCurrency.BTC> response) {
String currency = response.getUSD().toString();
Toast.makeText(getApplicationContext(), "result " + currency, Toast.LENGTH_LONG).show();
Log.i("MainActivity", currency);
}
#Override
public void onFailure(Call<CryptoCurrency.BTC> call, Throwable t) {
}
});
Try this solve your issue.
check if response.body() not null before this line
String currency = response.body().toString();
if response code not equal 200 your response will be null

Categories

Resources