This question already has answers here:
Android: Firebase Search Query not working properly
(2 answers)
Firebase observe key contains
(2 answers)
Closed 4 months ago.
I want to search items by their names using Material SearchBar Android Github, also I want that when I search only "bihari" it give me food item of "Bihari Boti" its means it should not case sensitive.
Please help me and guide me how can I search any item by using their name.
Here is my Items.class (model class) :
public class Items {
String name, desc,image, category;
int price;
boolean pin;
public Items(String name, String desc, String image, String category, int price, boolean pin) {
this.name = name;
this.desc = desc;
this.image = image;
this.category = category;
this.price = price;
this.pin = pin;
}
public Items() {
}
public boolean isPin() {
return pin;
}
public void setPin(boolean pin) {
this.pin = pin;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
this is my search bar code :
binding.searchBar.setOnSearchActionListener(new SimpleOnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
super.onSearchStateChanged(enabled);
}
#Override
public void onSearchConfirmed(CharSequence text) {
super.onSearchConfirmed(text);
Intent intent = new Intent(MainActivity.this,SearchActivity.class);
intent.putExtra("query",text.toString());
startActivity(intent);
}
#Override
public void onButtonClicked(int buttonCode) {
super.onButtonClicked(buttonCode);
}
});
this is my database code :
list = new ArrayList<>();
binding.searchRecView.setLayoutManager(new LinearLayoutManager(this));
adapter = new PinAdapter(this, list);
binding.searchRecView.setAdapter(adapter);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("admin");
Query search = reference.orderByChild("name").startAt(query).endAt(query+"\uf8ff");
search.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.getClass();
for (DataSnapshot categorySnapshot : snapshot.getChildren()) {
for (DataSnapshot itemSnapshot : categorySnapshot.getChildren()) {
Items items = itemSnapshot.getValue(Items.class);
list.add(items);
}
}
adapter.notifyDataSetChanged();
Toast.makeText(SearchActivity.this, list.toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Data base image :
Related
This question already has an answer here:
How can I get document values from a collection for the logged in user into a using Firestore?
(1 answer)
Closed 3 months ago.
I have this structure in my Firestore, I want the logged-in user to be able to get all image URLs and other fields such as name, price, and description that are associated with that userID. This info will be loaded into a recyclerView.
This is the Item Model
package com.bac.shoesrecyclerview;
public class Item {
private String itemName;
private String itemPrice;
private String itemDescription;
private String itemImage;
public Item(String itemName, String itemPrice, String itemDescription, String itemImage) {
this.itemName = itemName;
this.itemPrice = itemPrice;
this.itemDescription = itemDescription;
this.itemImage = itemImage;
}
public Item(){
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemPrice() {
return itemPrice;
}
public void setItemPrice(String itemPrice) {
this.itemPrice = itemPrice;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
public String getItemImage() {
return itemImage;
}
public void setItemImage(String itemImage) {
this.itemImage = itemImage;
}
}
This is the code i tried and crushes my app :
fStore.collection("images").document(FirebaseAuth.getInstance().getCurrentUser().getUid()).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
Item item = new Item();
itemList = new ArrayList<>();
while (document.exists()){
item.setItemName(document.getString("name"));
item.setItemPrice(document.getString("price"));
item.setItemDescription(document.getString("description"));
item.setItemImage(document.getString("image"));
itemList.add(item);
}
shoeAdapter = new ShoeAdapter(MainActivity.this, itemList);
recyclerView.setAdapter(shoeAdapter);
shoeAdapter.notifyDataSetChanged();
}
}
Try below query to get multiple document for single user-
db.collection("images")
.whereEqualTo("user_id", FirebaseAuth.getInstance().getCurrentUser().getUid())
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Item item = new Item();
item.setItemName(document.getString("name"));
item.setItemPrice(document.getString("price"));
item.setItemDescription(document.getString("description"));
item.setItemImage(document.getString("image"));
itemList.add(item);
}
shoeAdapter = new ShoeAdapter(MainActivity.this, itemList);
recyclerView.setAdapter(shoeAdapter);
shoeAdapter.notifyDataSetChanged();
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
Check document for more such queries - https://firebase.google.com/docs/firestore/query-data/queries
There is no need to get the value of each field separately. You can directly map a child in the Realtime Database into an object of type Item. In order to be able to do that, you have to change the declaration of the class like this:
public class Item {
private String name;
private String price;
private String description;
private String image;
private String userId;
public Item(String name, String price, String description, String image, String userId) {
this.name = name;
this.price = price;
this.description = description;
this.image = image;
this.userId = userId;
}
public Item(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
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 getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
Why? Because the name of the fields inside the class should name the name that exists in the database.
Now, in order to get the images that correspond to a logged-in user, you have to initialize the list, the adapter, and the RecyclerView and create a query that looks like this:
itemList = new ArrayList<>();
shoeAdapter = new ShoeAdapter(MainActivity.this, itemList);
recyclerView.setAdapter(shoeAdapter);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
Query queryByUserId = db.collection("images").whereEqualTo("userId", uid);
queryByUserId.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
if (document != null) {
Item item = document.toObject(Item.class);
itemList.add(item);
Log.d("TAG", item.getName());
}
}
shoeAdapter.notifyDataSetChanged();
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The changes that I made:
There is no need to use a while loop. You only have to check against nullity.
I have added the declaration related to UI outside the async operation. Once the operation for getting the Item objects is complete we only notify the adapter about the changes.
Always handle errors.
I am working on an application where I have a wishlist checkbox(heart icon) on my recyclerview items at Home Fragment, So when the user clicks on the heart icon it adds that particular item to the Wishlist Fragment, and when the user again clicks it, I want it to delete the item from the wishlist fragment. While adding the item it is working properly but when I try to delete it, it is not working and gives me a null pointer error.
CODE IS HERE
holder.wishlist.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
Boolean isCheck = compoundButton.isChecked();
//CODE TO ADD THE ITEM TO THE WISHLIST THROUGH HOME FRAGMENT
if(isCheck)
{
firebaseFirestore.collection("wishlistDetails").document(uid).set(wishMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
holder.wishlist.setButtonDrawable(R.drawable.ic_favorite_filled);
Toast.makeText(context, "item added to wishlist" + pos , Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
//CODE TO DELETE THE ITEM FROM WISHLIST THROUGH HOME FRAGMENT
}else {
firebaseFirestore.collection("wishlistDetails").document(wishlist_models.get(position).getUid())
.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(context, "item removed from wishlist", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
WISHLIST MODEL CODE
public class Wishlist_Model {
private List<String> images;
private String name;
private String email;
private String delete;
private String uid;
public Wishlist_Model() {
}
public Wishlist_Model(List<String> images, String name, String email, String delete, String uid) {
this.images = images;
this.name = name;
this.email = email;
this.delete = delete;
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDelete() {
return delete;
}
public void setDelete(String delete) {
this.delete = delete;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
FIRESTORE COLLECTION
ERROR IT IS THROWING
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
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"
JSON Image Link
i want to get all the images from my firebase database with this code
FirebaseDatabase mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseInstance.getReference("actors").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To solve this, you need to loop through the DataSnapshot object using getChildren() method. So please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("actors").orderByChild("image");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String image = ds.child("image").getValue(String.class);
Log.d(TAG, image);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
query.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat, will be all the image urls.
You can better use addListenerForSingleValueEvent instead of addValueEventListener as it will be called once so it will be very helpful, please try below code
ArrayList<String> arr_imageList = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("actors").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
arr_imageList.clear();
if (dataSnapshot.exists()) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
ActorsModel actorsModel = dataSnapshot1.getValue(ActorsModel.class);
if (actorsModel != null && actorsModel.getImage() != null) {
arr_imageList.add(actorsModel.getImage());
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
and please add model class for ActorsModel which is below
public class ActorsModel implements Serializable {
private String children;
private String country;
private String description;
private String dob;
private String height;
private String image;
private String name;
private String spouse;
public ActorsModel() {
}
public ActorsModel(String children, String country, String description, String dob, String height, String image, String name, String spouse) {
this.children = children;
this.country = country;
this.description = description;
this.dob = dob;
this.height = height;
this.image = image;
this.name = name;
this.spouse = spouse;
}
public String getChildren() {
return children;
}
public void setChildren(String children) {
this.children = children;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSpouse() {
return spouse;
}
public void setSpouse(String spouse) {
this.spouse = spouse;
}
}
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!