how to get selected value from listview - java

I want to select finance Name and after clicked finance Name i want to get code of same finance. The finance Name is listed into listview.
My Firebase database structure is below:
financeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
//Map<String, Object> data = (Map<String, Object>) snapshot.getValue();
String value = new Gson().toJson(snapshot.getValue());
progressBar.setVisibility(View.GONE);
try {
JSONObject object = new JSONObject(String.valueOf(value));
f = object.getString("Finance Name");
name = snapshot.getKey();
} catch (JSONException e) {
e.printStackTrace();
}
financeName.add(f);
adapter.notifyDataSetChanged();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(FinanceNameListActivity.this, CodeAndNameActivity.class);
String abc = (String) ((TextView) view).getText();
intent.putExtra("Name",abc);
startActivity(intent);
finish();
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Get response from firebase and set it to model call or hashmap or array up to you then implement interface for list view click event or simple click event with get position and get value from where you set firebase response.

Related

How to stop automatic scroll up in recycler view when increment button is clicked in recycler view item?

When I click the increment/decrement quantity button in recycler view, the recycler view is getting scrolled up automatically. How do I avoid scrolling up automatically??
Below is my code. Please help me.
This is the code in my main activity for recycler view adapter setup
private void loadCartItems() {
//init list
//get orders
shopNameTv.setText(shopname);
cartList = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(firebaseAuth.getUid()).child("Cart")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//clear list before adding item
cartList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
CartModel cartModel = ds.getValue(CartModel.class);
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object price = map.get("Item_Price");
int cost = Integer.parseInt(String.valueOf(price));
allTotalPrice += cost ;
sTotalTv.setText("₹" + allTotalPrice);
allTotalPriceTv.setText("₹" + (allTotalPrice + Integer.parseInt(deliveryFee.replace("₹", ""))));
cartList.add(cartModel);
}
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
cartItemsRv.setLayoutManager(mLayoutManager);
cartItemsRv.setItemAnimator(null);
//setup adapter
cartAdapter = new CartAdapter(CartActivity.this, cartList);
//set adapter
cartItemsRv.scrollToPosition(cartList.size());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
//allTotalPrice = allTotalPrice + Integer.parseInt(price);
dFeeTv.setText("₹" + deliveryFee);
sTotalTv.setText("₹" + allTotalPrice);
allTotalPriceTv.setText("₹" + (allTotalPrice + Integer.parseInt(deliveryFee.replace("₹", ""))));
}
This is my adapter code
if (Integer.parseInt(stk) == 0) {
Toast.makeText(context, "Product Stock Limit reached", Toast.LENGTH_SHORT).show();
}
else {
holder.incrementBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int number = 0;
number = Integer.parseInt(holder.itemQuantityTv.getText().toString().trim());
number++;
//((CartActivity)context).reload();
holder.itemQuantityTv.setText(""+number);
int pe = number * Integer.parseInt(holder.itemPriceEachTv.getText().toString().trim());
holder.itemPriceTv.setText(""+pe);
double tx = Double.parseDouble((((CartActivity)context).allTotalPriceTv.getText().toString().trim().replace("₹","")));
double totalPrice = tx + Double.parseDouble(cartModel.getItem_Price().replace("₹",""));
double deliveryFee = Double.parseDouble((((CartActivity)context).deliveryFee.replace("₹","")));
double sTotalPrice = Double.parseDouble(String.format("%.0f", totalPrice));
((CartActivity)context).allTotalPrice = 0;
((CartActivity)context).sTotalTv.setText("₹"+String.format("%.0f", sTotalPrice));
((CartActivity)context).allTotalPriceTv.setText("₹"+String.format("%.0f", Double.parseDouble(String.format("%.0f", sTotalPrice))));
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("Item_Price", "" + pe);
hashMap.put("Item_Quantity", "" + number);
hashMap.put("Available_Stock", "" + availableStock);
//update db
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.child(firebaseAuth.getUid()).child("Cart").child(cartModel.getItem_PID()).updateChildren(hashMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//db updated
// Toast.makeText(context, "Cart updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//failed updating db
Toast.makeText(context, "Cart not updated", Toast.LENGTH_SHORT).show();
}
});
//To update stock value in cart
int stk_number = 0;
stk_number = Integer.parseInt(holder.stock.getText().toString().trim());
if (stk_number >0 ){
stk_number--;
holder.stock.setText(""+stk_number);
HashMap<String, Object> hashMap1 = new HashMap<>();
hashMap1.put("Stock_left", "" + stk_number);
//update db
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(firebaseAuth.getUid()).child("Cart").child(cartModel.getItem_PID()).updateChildren(hashMap1)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//db updated
// Toast.makeText(context, "Cart updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//failed updating db
Toast.makeText(context, "Cart not updated", Toast.LENGTH_SHORT).show();
}
});
}
else {
stk_number = 0;
}
}
});
}
Whenever I click increment/decrement button in recycler view item, the recycler view is scrolled up automatically. If I need to increment again, I need to scroll down again every time. So, how to stop this auto-scroll up and make it stay in the same position.
You have to remove the ValueEventListener after successful loading and populating the Adapter. Otherwise, you get an update event after updating the value. This creates a new Adapter which is scrolled to the top.
You can use .get() if you want to read the DB only once:
mDatabase.child("users").child(userId).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (!task.isSuccessful()) {
Log.e("firebase", "Error getting data", task.getException());
}
else {
Log.d("firebase", String.valueOf(task.getResult().getValue()));
}
}
});
Source: https://firebase.google.com/docs/database/android/read-and-write#read_data_once
In your case:
reference.child(firebaseAuth.getUid()).child("Cart").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
...
}

How do I retrieve data under UID for the signed in user with Firebase

I saved some data under a node with the currently signed in user UID, along with the post timestamp.I successfully manage to retrieve all the data under this node, but I would only like to retrieve the data for the currently signed in user, I am trying to create something similar to how amazon stores an item in the cart and when the user clicks the cart it shows the items they have added there, not all the items for every user. Can someone assist me with this problem?
public void addItemToCart(){
SimpleDateFormat formatter = new SimpleDateFormat(" HH:mm:ss ");
Date date = new Date(System.currentTimeMillis());
timeStamp = loggedInUserId + formatter.format(date);
userDictionary.put("itemPrice", selectedPrice);
userDictionary.put("productname",productNameText);
userDictionary.put("description", selectedStringProductDescrtipon);
userDictionary.put("uid",loggedInUserId);
userDictionary.put("productImage", selectedImage);
userDictionary.put("datee",date.toString());
userDictionary.put("name",loggedInUserName);
userDictionary.put("timestamp",timeStamp);
uploadPostRef.child("Cart").child(timeStamp).setValue(userDictionary).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Log.i("sucessfully added","sucesssfully added to cart..");
getLoggedInUserData();
}
});
numberInCartIv.setVisibility(View.VISIBLE);
public void downloadCartData(){
cartDb.child("Cart").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
if (data.exists()) {
Log.i("data",data.toString());
// cartModel = data.getValue(CartModel.class);
// cartModelArrayList.add(cartModel);
// LinearLayoutManager horizontalLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
// cartRecyleView.setLayoutManager(horizontalLayoutManager);
// cartAdapter = new CartAdapter(cartModelArrayList, getContext());
// cartRecyleView.setAdapter(cartAdapter);
} else {
Log.i("error", "Error Loading JSON data..");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
String error = databaseError.getDetails();
Log.i("error", error);
}
});
}
First of all, you need to change your DB json to this one.
Cart
-userUid
-cartUid
-datee
-description
-andSoOn
That's mean, when you are storing the item into Cart. You need to include the userUid.
//Getting userUid
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
final String userUid = firebaseUser.getUid();
uploadPostRef.child("Cart").child(userUid).child(timeStamp).setValue(userDictionary).addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Void unused) {
Log.i("sucessfully added","sucesssfully added to cart..");
getLoggedInUserData();
}
});
}
To retrieve the Cart according to the user. You just call them like this.
public void downloadCartData(){
cartDb.child("Cart").child(userUid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
if (data.exists()) {
Log.i("data",data.toString());
} else {
Log.i("error", "Error Loading JSON data..");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
String error = databaseError.getDetails();
Log.i("error", error);
}
});
}

How to get last node in Firebase?

I'm working on a chat app where user can see last message of conversation. But I am stuck with this situation where i am unable to get last message.
I have tried this query like
DatabaseReference getLastMessageRef =
FirebaseDatabase.getInstance().getReference("FriendsMessages");
Query query1 = getLastMessageRef.child(common.currentUser.getPhone()).child(id).orderByKey().limitToLast(1);
Where common.currentUser.getPhone is number/id of current user and id is id of other person.
And database structure is like DATABASE STRUCTURE PICTURE
private void getAllMessages() {
Query query = FirebaseDatabase.getInstance().getReference("FriendsMessages").child(common.currentUser.getPhone());
FirebaseRecyclerOptions<MessageModel> options = new FirebaseRecyclerOptions.Builder<MessageModel>()
.setQuery(query,MessageModel.class)
.build();
adapter = new FirebaseRecyclerAdapter<MessageModel, ShowAllMessageViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ShowAllMessageViewHolder holder, int position, #NonNull final MessageModel model) {
String id = adapter.getRef(position).getKey();
DatabaseReference getFriendDataRef = FirebaseDatabase.getInstance().getReference("User");
DatabaseReference getLastMessageRef = FirebaseDatabase.getInstance().getReference("FriendsMessages");
getFriendDataRef.child(id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String dp = dataSnapshot.child("img").getValue().toString();
String name = dataSnapshot.child("name").getValue().toString();
holder.MessageName.setText(name);
Picasso.with(getBaseContext()).load(dp).into(holder.messageDp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Query query1 = getLastMessageRef.child(common.currentUser.getPhone()).child(id).orderByKey().limitToLast(1);
query1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String mesaage = (String) dataSnapshot.child("message").getValue();
Toast.makeText(mContext, ""+mesaage, Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ShowAllMessageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_message_view,parent,false);
return new ShowAllMessageViewHolder(view);
}
};
showAllMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
I am getting null string.
One thing to remember is that Firebase keys are always Strings. And when strings are ordered, are ordered lexicographically.
If you want to get the last element, add to each message object a new property that can hold a timestamp. This is how you can add it to the database and get it back. In the end, simply create a query and order the elements according to this new timestamp property and call limitToLast(1). That's it!

Firebase reading data from multiple references

I am trying to fetch data from Firebase database from multiple child in single function. I have two child nodes in Firebase Favorites and Users
I am using RecyclerView to show list of Favorites User but i want to fetch one value name "Online" from Users node.
I add addValueEventListener on Favorites and add addListenerForSingleValueEvent on Users within Favorites addValueEventListener, but my addListenerForSingleValueEvent give null value.
There is my code:
mFavouriteDBRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mList.clear();
if(dataSnapshot.getChildrenCount() > 0){
for(DataSnapshot snap: dataSnapshot.getChildren()){
final Favourites user = snap.getValue(Favourites.class);
final FavouritesList[] holdObj = null;
//if not current user, as we do not want to show ourselves then chat with ourselves lol
try {
if(mAuth.getCurrentUser().getUid().equals(user.getUserId())){
//Firebase Reading data
mUsersDBRef = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDBRef.child(mAuth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUsersDBRef.child(mAuth.getCurrentUser().getUid()).child("online").onDisconnect().setValue(false);
String local =dataSnapshot.child(mAuth.getCurrentUser().getUid()).child("online").getValue().toString();
if(local.equals("true")){
holdObj[0] = new FavouritesList(mAuth.getCurrentUser().getUid(),user.getFavouriteId(),user.getFavouriteName(),user.getFavouriteCity(),user.getFavouriteCountry(),user.getFavouriteAge(),user.getFavouriteGender(),user.getFavouriteKeyword(),user.getPushKey(), "true","Link");
}else{
holdObj[0] = new FavouritesList(mAuth.getCurrentUser().getUid(),user.getFavouriteId(),user.getFavouriteName(),user.getFavouriteCity(),user.getFavouriteCountry(),user.getFavouriteAge(),user.getFavouriteGender(),user.getFavouriteKeyword(),user.getPushKey(), "false","Link");
}
mList.add(holdObj[0]);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
populaterecyclerView();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here my populaterecyclerView(); Class
private void populaterecyclerView(){
adapter = new UserFavouritesMeHomeListAdapter(context,mList);
adapter.setClickListener(UserFavouritesMeListHomeFragment.this);
recyclerView.setAdapter(adapter);
}
Thanks
Link of Image:
http://userdata.in/singls/images/profile/WobiUh7Zb2bjszmYN0LofK7Pm0z1_20180124042847_file_cover.jpg
Data want to fetch from while reading Favorite
http://userdata.in/singls/images/profile/WobiUh7Zb2bjszmYN0LofK7Pm0z1_20180124044659_file_cover.jpg

firebase get data as array

I am trying to implement firebase into my Android app and I want to be able to pull all the entries in firebase in the order they display in into one string array to be put into a ListView
Here is the raw JSON:
[ 5, "quot", "waaaaa", "also a quote", "oh this one is a little longer man", "gosh really long. wow. im very inspired. golly gee wiz" ]
and the code I am using to try and get it:
public class MyActivity extends ListActivity {
ArrayList<String> LIST = new ArrayList<String>();
Boolean wow = true;
Context context = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(context);
updateList();
}
public void makeList(ArrayList<String> input){
setListAdapter(new ArrayAdapter<String>(this, R.layout.mylist,input));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
public void updateList() {
Firebase myFirebaseRef = new Firebase("https://admin1.firebaseio.com/");
myFirebaseRef.child("0").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue());
int length = Integer.parseInt(snapshot.getValue().toString());
Firebase myFirebaseRef = new Firebase("https://admin1.firebaseio.com/");
for(int i=1; i<length; i++) {
String doIt = Integer.toString(i);
myFirebaseRef.child(doIt).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue());
LIST.add(snapshot.getValue().toString());
}
#Override
public void onCancelled(FirebaseError error) {
}
});
}makeList(LIST);
}
#Override
public void onCancelled(FirebaseError error) {
}
});
}
}
I was thinking that I could set the first (0th) object to be the number of entries and then cycle through the entire file using .getValue but when this is run I get out of memory exceptions and the app force closes. All I am sure of is that the relevant firebase stuff is the issue and not the ListView. Thanks for any tips.
Firstly, your data is stored in a JSON data object (i.e. not an array). You do not want to store sequential, numeric ids in distributed data.
To listen for the first n objects, utilize the query methods and limitToFirst.
int n = 10;
String URL = "https://<your instance>.firebaseio.com";
Firebase ref = new Firebase(URL);
Query queryRef = ref.orderByKey().limitToFirst(n);
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChild) {
Map<String, String> value = (Map<String, String)snapshot.getValue();
System.out.println(snapshot.getKey() + " was " + value.get("message"));
}
// ....
});

Categories