Geofire query with Firebase adding duplicate objects to Arraylist - java

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

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.

Data from collectionGroup document not loading into TextView Firestore

I hope you are well. I am trying to add text to a text view from a document in Firestore. I was told you cant query a document by id withing a collection group, so I created a field "id" with the documentID and queried that, but still nothing and no errors.
Here is my activity:
public class FoodItemPage extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
ElegantNumberButton number_button;
Button addtocart;
TextView food_name, food_description;
EditText extra_notes;
String foodId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_item_page);
foodId = getIntent().getStringExtra("foodid");
//firestore
Query singlefoodref = db.collectionGroup("Foods").whereEqualTo("id", foodId);
Log.d(TAG, "well hello there" + foodId);
//init view
number_button = (ElegantNumberButton) findViewById(R.id.number_button);
addtocart = (Button) findViewById(R.id.addToCart);
food_name = (TextView) findViewById(R.id.food_name1);
food_description = (TextView) findViewById(R.id.food_description);
singlefoodref.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (queryDocumentSnapshots.isEmpty()){
Toast.makeText(FoodItemPage.this, "document not there", Toast.LENGTH_SHORT);
Log.d(TAG, "NOT WORKING");
}else{
FoodModel foodModel = queryDocumentSnapshots.getDocuments().get(0).toObject(FoodModel.class);
food_name.setText(foodModel.getName());
Log.d(TAG, "WORKING");
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(FoodItemPage.this, "Error", Toast.LENGTH_SHORT);
}
});
}
}
My model (i am also using the same Model in another activity, that shouldn't be a problem right?) :
package com.example.hostapp.Models;
public class FoodModel {
private String name;
private String description;
private String image;
private String price;
private String discount;
private String categoryid;
public FoodModel() {
}
public FoodModel(String name, String description, String image, String price, String discount, String categoryid) {
this.name = name;
this.description = description;
this.image = image;
this.price = price;
this.discount = discount;
this.categoryid = categoryid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public String getCategoryid() {
return categoryid;
}
public void setCategoryid(String categoryid) {
this.categoryid = categoryid;
}
}
Edit:
My database structure, each restaurant has its own "Foods" collections with the food items i am trying to load.
SO I fixed this, the error was in my database, the id in the database had a space in it so it wasn't matching the document ID from the previous activity.
so from " 123456" to "123456"

Latitude and Longitude coordinates are incorrect coming from Firebase and identical for all posts

The location that a user retrieves from Firebase for a specific post is always coming back as the same erroneous location, always the same one. I have tried various alternatives for this code trying to work it around so that the specific location that user created for their event saved to the GoogleMap comes back, but keep getting same location for all posts and it's incorrect.
I've been using a few other posts with location problems on here, but haven't helped me.
Please tell me what I am doing wrong.
Firebase
MapActivityUser.java
public class MapsActivityUser extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_user);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.hasChild("location")) {
Post post = snapshot.getValue(Post.class);
double latitude = post.getLatitude();
double longitude = post.getLongitude();
LatLng location = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions().position(location).title("Event location"));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 10));
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
PostActivity.java
package com.e.events.Model;
public class Post {
private String postid;
private String postimage;
private String description;
private String publisher;
private String text_event;
private String text_location;
private String text_date_time;
private Long timestamp;
private MyLocation location;
public Post(String description, String postId, String postImage, String publisher, Long timestamp,
String text_event, String text_location, String text_date_time, MyLocation location) {
this.postid = postid;
this.postimage = postimage;
this.description = description;
this.publisher = publisher;
this.text_event = text_event;
this.text_location = text_location;
this.text_date_time = text_date_time;
this.timestamp = timestamp;
this.location = location;
}
public class MyLocation {
private double latitude;
private double longitude;
}
public Post() {
}
public String getPostid() {
return postid;
}
public void setPostid(String postid) {
this.postid = postid;
}
public String getPostimage() {
return postimage;
}
public void setPostimage(String postimage) {
this.postimage = postimage;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getText_event() {
return text_event;
}
public void setText_event(String text_event) {
this.text_event = text_event;
}
public String getText_location() {
return text_location;
}
public void setText_location(String text_location) {
this.text_location = text_location;
}
public String getText_date_time() {
return text_date_time;
}
public void setText_date_time(String text_date_time) {
this.text_date_time = text_date_time;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public MyLocation getLocation() {
return location;
}
public void setLocation(MyLocation location) {
this.location = location;
}
}
You didn't set your model correctly. Update your Post like below:
Post.java:
public class Post {
private String postid;
private String postimage;
private String description;
private String publisher;
private String text_event;
private String text_location;
private String text_date_time;
private Long timestamp;
private MyLocation location;
//getter-setter
}
MyLocation.java:
public class MyLocation {
private double latitude;
private double longitude;
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;
}
}
And then parse like
Post post = snapshot.getValue(Post.class);
double latitude = post.getLocation().getLatitude();
double longitude = post.getLocation().getLongitude();

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

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!

Categories

Resources