java.lang.NullPointerException error on Retrofit onResponse - java

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

Related

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

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.

Get values From ViewModel MutableLiveData and display them on textfields

I am trying to get a hang of the Android Architecture Library and i have been trying to display texts from retrofit via a ViewModel using Mutable LiveData on my Main Activity but i cant seem to do it, i would really appreciate some assistance.
Here is my Model Class
public class User {
#SerializedName("name")
#Expose
private String name;
#SerializedName("email")
#Expose
private String email;
#SerializedName("phone")
#Expose
private String phone;
public User() {
}
public String getUserName() {
return name;
}
public void setUserName(String name) {
this.name = name;
}
public String getUserEmail() {
return email;
}
public void setUserEmail(String email) {
this.email = email;
}
public String getUserPhone() {
return phone;
}
public void setUserPhone(String phone) {
this.phone = phone;
}
}
My View model
public class UserViewModel extends AndroidViewModel {
private NodeAuthService api;
private SharedPreferences pref;
private static MutableLiveData<List<User>> userDetails = new
MutableLiveData<>();
private Call<List<User>> call;
public UserViewModel(#NonNull Application application) {
super(application);
api = AuthRetrofitClient.getInstance().create(NodeAuthService.class);
}
private String email = pref.getString("email", "");
public void loadUser(){
call = api.getUser(email);
call.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, Response<List<User>>
response) {
List<User> users = response.body();
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
Log.d("USER",t.getMessage());
}
});
}
public MutableLiveData<List<User>> getUserDetails(){
return userDetails;
}
}
Simplified version of my MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView navName = (TextView) findViewById(R.id.navigation_name);
TextView navEmail = (TextView) findViewById(R.id.navigation_email);
}
Kindly assist
In your viewModel
public void loadUser(){
call = api.getUser(email);
call.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, Response<List<User>>
response) {
userDetails.postValue(response.body())
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
Log.d("USER",t.getMessage());
}
});
}
And in your Activity observe the changes
yourVm.getUserDetails().observe(this, models -> {
if (models != null) {
for(int = 0; i<models.size();i++){
/*you will get your list here now iterate through list and get
your email_id here.*/
}
}
});
instead of this
List<User> users = response.body();
use this
userDetails.postValue(response.body())
also, remove static before livedata
inside activity oncreate() init your viewModel instance.
then viewModel.getUserDEtails().obsever(this, data-> // your stuff);

Unable to start activity ComponentInfo : Attempt to invoke virtual method on a null object reference [duplicate]

This question already has answers here:
NullPointerException addToRequestQueue(com.android.volley.Request, java.lang.String)' on a null object reference
(8 answers)
Closed 4 years ago.
This is a barcode scanning app. It crashes when I scanned the code. If anyone knows how to fix help me out.
It crashes after I scanned the code from the ScanActivity.java and pass the object to the TicketResultActivity.javato display the result.
error
java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.movietickets/info.androidhive.movietickets.TicketResultActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void info.androidhive.movietickets.MyApplication.addToRequestQueue(com.android.volley.Request)' on a null object reference
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
// making toolbar transparent
transparentToolbar();
setContentView(R.layout.activity_main);
findViewById(R.id.btn_scan).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, ScanActivity.class));
}
});
}
private void transparentToolbar() {
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true);
}
if (Build.VERSION.SDK_INT >= 19) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
if (Build.VERSION.SDK_INT >= 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
}
private void setWindowFlag(Activity activity, final int bits, boolean on) {
Window win = activity.getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
}
ScanActivity.java
public class ScanActivity extends AppCompatActivity implements BarcodeReader.BarcodeReaderListener{
BarcodeReader barcodeReader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
// get the barcode reader instance
barcodeReader = (BarcodeReader) getSupportFragmentManager().findFragmentById(R.id.barcode_scanner);
}
#Override
public void onScanned(Barcode barcode) {
// playing barcode reader beep sound
barcodeReader.playBeep();
// ticket details activity by passing barcode
Intent intent = new Intent(ScanActivity.this, TicketResultActivity.class);
intent.putExtra("code", barcode.displayValue);
startActivity(intent);
}
#Override
public void onScannedMultiple(List<Barcode> list) {
}
#Override
public void onBitmapScanned(SparseArray<Barcode> sparseArray) {
}
/*#Override
public void onCameraPermissionDenied() {
finish();
}*/
#Override
public void onScanError(String s) {
Toast.makeText(getApplicationContext(), "Error occurred while scanning " + s, Toast.LENGTH_SHORT).show();
}
}
TicketResultActivity.java
public class TicketResultActivity extends AppCompatActivity {
private static final String TAG = TicketResultActivity.class.getSimpleName();
// url to search barcode
private static final String URL = "https://api.androidhive.info/barcodes/search.php?code=";
private TextView txtName, txtDuration, txtDirector, txtGenre, txtRating, txtPrice, txtError;
private ImageView imgPoster;
private Button btnBuy;
private ProgressBar progressBar;
private TicketView ticketView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_result);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
txtName = findViewById(R.id.name);
txtDirector = findViewById(R.id.director);
txtDuration = findViewById(R.id.duration);
txtPrice = findViewById(R.id.price);
txtRating = findViewById(R.id.rating);
imgPoster = findViewById(R.id.poster);
txtGenre = findViewById(R.id.genre);
btnBuy = findViewById(R.id.btn_buy);
imgPoster = findViewById(R.id.poster);
txtError = findViewById(R.id.txt_error);
ticketView = findViewById(R.id.layout_ticket);
progressBar = findViewById(R.id.progressBar);
String barcode = getIntent().getStringExtra("code");
// close the activity in case of empty barcode
if (TextUtils.isEmpty(barcode)) {
Toast.makeText(getApplicationContext(), "Barcode is empty!", Toast.LENGTH_LONG).show();
finish();
}
// search the barcode
searchBarcode(barcode);
}
/**
* Searches the barcode by making HTTP call
* Request was made using Volley network library but the library is
* not suggested in production, consider using Retrofit
*/
private void searchBarcode(String barcode) {
// making volley's json request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
URL + barcode, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Ticket response: " + response.toString());
// check for success status
if (!response.has("error")) {
// received movie response
renderMovie(response);
} else {
// no movie found
showNoTicket();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
showNoTicket();
}
});
MyApplication.getInstance().addToRequestQueue(jsonObjReq);
}
private void showNoTicket() {
txtError.setVisibility(View.VISIBLE);
ticketView.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
}
/**
* Rendering movie details on the ticket
*/
private void renderMovie(JSONObject response) {
try {
// converting json to movie object
Movie movie = new Gson().fromJson(response.toString(), Movie.class);
if (movie != null) {
txtName.setText(movie.getName());
txtDirector.setText(movie.getDirector());
txtDuration.setText(movie.getDuration());
txtGenre.setText(movie.getGenre());
txtRating.setText("" + movie.getRating());
txtPrice.setText(movie.getPrice());
Glide.with(this).load(movie.getPoster()).into(imgPoster);
if (movie.isReleased()) {
btnBuy.setText(getString(R.string.btn_buy_now));
btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
} else {
btnBuy.setText(getString(R.string.btn_coming_soon));
btnBuy.setTextColor(ContextCompat.getColor(this, R.color.btn_disabled));
}
ticketView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
} else {
// movie not found
showNoTicket();
}
} catch (JsonSyntaxException e) {
Log.e(TAG, "JSON Exception: " + e.getMessage());
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// exception
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private class Movie {
String name;
String director;
String poster;
String duration;
String genre;
String price;
float rating;
#SerializedName("released")
boolean isReleased;
public String getName() {
return name;
}
public String getDirector() {
return director;
}
public String getPoster() {
return poster;
}
public String getDuration() {
return duration;
}
public String getGenre() {
return genre;
}
public String getPrice() {
return price;
}
public float getRating() {
return rating;
}
public boolean isReleased() {
return isReleased;
}
}
}
MyApplication.java
public class MyApplication extends Application {
public static final String TAG = MyApplication.class
.getSimpleName();
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
To initialize MyApplication properly you have to add the following in the AndroidManifest.xml
<application android:name="com.package.subpackage.MyApplication">
...
</application>

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

Geofire query with Firebase adding duplicate objects to Arraylist

Been stuck here for a bit, I've tried to used the Firebase UI FirebaseRecyclerAdapter, but it wont take multiple references for the keys generated by the GeoQuery. So i used a typical Array adapter. The problem is that whenever the object is updated/changed in Firebase, it creates duplicates of the object in the array. I've tried to use if(!arrayofcars.contains(car)), but it doesn't change as technically the objects are different. Here's a bit of the code..
GeoFire geoFire = new GeoFire(mDatabaseReference.child("cars_location"));
GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(userLat, userLong), 20);
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(String key, GeoLocation location) {
Toast.makeText(CarHopActivity.this, "Key: " + key, Toast.LENGTH_SHORT).show();
tempDataRef = FirebaseDatabase.getInstance().getReference("/cars/" + key);
tempDataRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Car car = dataSnapshot.getValue(Car.class);
Log.d(TAG, "this is the object"+ car.getCarName());
arrayOfCars.add(car);
nearestCars.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
and here is the Object class...
public class Car {
private String carName;
private int carCount;
private int carCap;
private String carAddress;
private String carPhotoURI;
private String userId;
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
private double latitude;
private double longitude;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getCarPhotoURI() {
return carPhotoURI;
}
public void setCarPhotoURI(String carPhotoURI) {
this.carPhotoURI = carPhotoURI;
}
public String getcarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public int getCarCount() {
return carCount;
}
public void setCarCount(int carCount) {
this.carCount = carCount;
}
public int getCarCap() {
return carCap;
}
public void setCarCap(int carCap) {
this.carCap = carCap;
}
public String getCarAddress() {
return carAddress;
}
public void setCarAddress(String carAddress) {
this.carAddress = carAddress;
}
public Car() {
}
public Car(String carName, int carCount, int carCap, String carAddress, String carPhotoURI, double latitude, double longitude, String userId) {
this.carCap = carCap;
this.carCount = carCount;
this.carName = carName;
this.carAddress = carAddress;
this.carPhotoURI = carPhotoURI;
this.latitude = latitude;
this.longitude = longitude;
this.userId = userId;
}

Categories

Resources