I have an algorithm looking for Firebase data but it doesn't work and records an error to me, I want to register into Edittext Value and it will bring me the appropriate card
I use the recylerView
recyclerView= findViewById(R.id.recycleview);
getmRootFLY = FirebaseDatabase.getInstance().getReference("FLY");
list = new ArrayList<>();
arrayList = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
myAdapter = new MyAdapter(this,list);
recyclerView.setAdapter(myAdapter);
getmRootFLY.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren())
{
Fly fly = dataSnapshot.getValue(Fly.class);
list.add(fly);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
databaseReference = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mRootRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid()).child("First Name");
mRootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.getValue().toString();
TextView myLoginTextFromDB = (TextView)findViewById(R.id.hello_name_from_db);
myLoginTextFromDB.setText(name);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
EditText editTextTextPersonName = (EditText) findViewById(R.id.editTextTextPersonName);
editTextTextPersonName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
Query query = databaseReference.child("FLY").equalTo(editable.toString());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
{
list.clear();
for (DataSnapshot dss: snapshot.getChildren())
{
final Fly fly = dss.getValue(Fly.class);
list.add(fly);
}
MyAdapter myAdapter1 = new MyAdapter(getApplicationContext(),list);
recyclerView.setAdapter(myAdapter1);
myAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
It is important to note Getmrootfly adds the card to the array and basically shows me the data available in Firebase
And all code that appears as an edittexttexteonname is a code that needs to look for the data
Related
public class c_Fragment_Chat extends Fragment {
private RecyclerView recyclerView;
private UserAdapter userAdapter;
private List<User> mUsers;
EditText s_search_student;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.c_fragment_chat, container, false);
recyclerView = view.findViewById(R.id.c_recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mUsers = new ArrayList<>();
readUsers();
s_search_student = view.findViewById(R.id.s_search_student);
s_search_student.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
searchUsers(charSequence.toString().toLowerCase());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return view;
}
private void searchUsers(String s) {
Query query = FirebaseDatabase.getInstance().getReference("User").orderByChild("search")
.startAt(s)
.endAt(s+"\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(s_search_student.getText().toString().equals("")){
mUsers.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
mUsers.add(user);
}
userAdapter = new UserAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(userAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readUsers() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("User");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUsers.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
mUsers.add(user);
}
userAdapter = new UserAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(userAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero-length
I don't know why my edit text can't able to detect the data changed from the string. Please give me a hand~ thank you very much. And the above is the error problem that I get.
I want the items to appear only when the user starts typing something on the EditText
Here's my Adapter:
#NonNull
#Override
public UserAdapter.ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item, parent, false);
return new UserAdapter.ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final UserAdapter.ImageViewHolder holder, final int position) {
...
}
Here's the Search Fragment:
userList = new ArrayList<>();
userAdapter = new UserSearchMessageAdapter(getContext(), userList, true);
recyclerView.setAdapter(userAdapter);
readUsers();
search_bar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
searchUsers(charSequence.toString().toLowerCase());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return view;
}
private void searchUsers(String s){
Query query = FirebaseDatabase.getInstance().getReference("Users").orderByChild("username")
.startAt(s)
.endAt(s+"\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
userList.add(user);
}
userAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readUsers() {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
userList.add(user);
}
userAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
EDIT
You can hide the recyclerview when the user hasnt typed anything in the edittext
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(charSeqeunce.equals(""))recyclerView.setVisibility(View.GONE);
else {searchUsers(charSequence.toString().toLowerCase());
recyclerView.setVisibility(View.VISIBLE);
}
}
and you can just show an empty state image instead.
When the user types something in the edittext then you can show them the recyclerview back and hide the empty state image!
Hope this helps!
I'm trying to get the key of a certain child value by allowing the user to choose from a Spinner.
The Spinner has "Product_Name" values as its choices. By choosing one, the program should get its key and use it to get another child value for other uses.
Example:
PRODUCTS->
-LoUXnfUCEj4k4A3dkte->
Product_Name:"Steak"
By choosing "Steak" in the Spinner, I have to get "-LoUXnfUCEj4k4A3dkte"
databaseRefSelectItem = FirebaseDatabase.getInstance().getReference("PRODUCTS");
final DatabaseReference mDatabase = databaseRefSelectItem;
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot) {
//We create an array list to hold the values brought from the database and show them in the spinner
final List<String> titleList = new ArrayList<String>();
for(final DataSnapshot snapshot : dataSnapshot.getChildren()) {
titleProduct = snapshot.child("Product_Name").getValue(String.class);
//populate the spinner with that array list
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(AddTransactionActivity.this, android.R.layout.simple_spinner_item, titleList);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectProduct.setAdapter(arrayAdapter);
titleList.add(titleProduct);
//Click event for each spinner element
selectProduct.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//pass the reference from that value into another snapshot in order to query those values, here you need to get your node id and inside just get your number , name and so on
selectItem = titleList.get(i);
mDatabase.child(selectItem).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot2) {
key = dataSnapshot2.getKey();
currentItemStock = dataSnapshot2.child(key).child("Current_Stock").getValue(String.class);
currentStk.setText(key);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
How can I get "-LoUXnfUCEj4k4A3dkte"?
Notes:
-LoUXnfUCEj4k4A3dkte is randomly generated.
Use .getKey() to get the key of the snapshot like:
for(final DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.child("Product_Name").getValue(String.class).equals("Steak")){
String theKey = snapshot.getKey(); //This will return -LoUXnfUCEj4k4A3dkte
}
}
Will return key of the snapshot at that reference.
Found a solution.
Thank you as well to Yash Krishan for the code snippet :).
databaseRefSelectItem = FirebaseDatabase.getInstance().getReference("PRODUCTS");
final DatabaseReference mDatabase = databaseRefSelectItem;
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot) {
//We create an array list to hold the values brought from the database and show them in the spinner
final List<String> titleList = new ArrayList<String>();
for(final DataSnapshot snapshot : dataSnapshot.getChildren()) {
titleProduct = snapshot.child("Product_Name").getValue(String.class);
//populate the spinner with that array list
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(AddTransactionActivity.this, android.R.layout.simple_spinner_item, titleList);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectProduct.setAdapter(arrayAdapter);
titleList.add(titleProduct);
//Click event for each spinner element
selectProduct.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//pass the reference from that value into another snapshot in order to query those values, here you need to get your node id and inside just get your number , name and so on
selectItem = titleList.get(i);
if (titleProduct.equals(selectItem)){
key = dataSnapshot.child(selectItem).getKey(); //This will return -LoUXnfUCEj4k4A3dkte
}
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot2) {
for(final DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.child("Product_Name").getValue(String.class).equals(selectItem)){
key = snapshot.getKey().toString();
}
keyholder = dataSnapshot.child(key).child("Current_Stock").getValue(String.class);
}
currentStk.setText(keyholder);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
For my chat application, I have saved EditText data to firebase but not I am not able to display the same in ListView. I am able to see the EditText data in Firebase database and I want to retrieve it in a ListView. Anybody can help me?
public class Chatbox extends AppCompatActivity {
private DatabaseReference databaseReference;
private Button btnsend;
private EditText editText;
private ListView listView;
private ArrayList<String> arrayList = new ArrayList<>();
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatbox);
databaseReference = FirebaseDatabase.getInstance().getReference();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
btnsend = findViewById(R.id.sendbutton);
editText = findViewById(R.id.typemessage);
listView = findViewById(R.id.listmessages);
btnsend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseReference.child("Chat").child("Name").push().setValue(editText.getText().toString());
}
});
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DatabaseReference chatreference=databaseReference.child("Chat");
chatreference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String chatmsg = snapshot.child("Name").getKey();
Toast.makeText(Chatbox.this, "keys " + chatmsg, Toast.LENGTH_SHORT).show();
arrayList.add(chatmsg);
}
listView.setAdapter(adapter);
}
catch (Exception ex)
{
Toast.makeText(Chatbox.this, "Error " + ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Try this
FirebaseDatabase.getInstance()
.getReference("Chat")
.child("Name")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<String> chatMessages = new ArrayList<>();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
try {
String chatMessage = String.valueOf(dataSnapshot.child(dataSnapshot1.getKey()).getValue());
chatMessages.add(chatMessage);
} catch (DatabaseException e) {
e.printStackTrace();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
callback.onFailure(null);
}
});
i guess you want to retrive data not the key:
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DatabaseReference chatreference=databaseReference.child("Chat");
chatreference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String chatmsg = snapshot.child("Name").getValue();
Toast.makeText(Chatbox.this, "keys " + chatmsg, Toast.LENGTH_SHORT).show();
arrayList.add(chatmsg);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
or want you to store both in a array list key and value together?
You're adding the messages to the database with:
databaseReference.child("Chat").child("Name")
That means you must also read the messages from the same path:
databaseReference.child("Chat").child("Name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String chatmsg = snapshot.getValue(String.class);
arrayList.add(chatmsg);
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException()l
}
});
The changes:
Listen to the same node as you're adding the messages to.
Removed the nested listener, which is not needed.
Get the value from each child snapshot, instead of trying to read a non-existing Name property.
Removed the try...catch as the default behavior is to write messages to logcat, which is more useful than showing them in a toast.
Implemented onCancelled, because you should never ignore errors.
I retrieved data from firebase database in recylerview. But I have in post node "postimg" has a another list item.
For this I use one more listener in onBindViewHolder. But this does not seem right to me.
So how to do all this works in mainactivity and pass in adapter?
Here is my code:
#Override
public void onBindViewHolder(#NonNull final PostHolder postHolder, final int i) {
postHolder.setData(mPost.get(i));
final String PostKey=mPost.get(i).getPostid();
FirebaseAuth mAuth=FirebaseAuth.getInstance();
final String currentUserID=mAuth.getCurrentUser().getUid();
final DatabaseReference post=FirebaseDatabase.getInstance().getReference().child("Posts");
post.child(PostKey).child("postimg").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
{
String postimagelink =dataSnapshot1.getValue().toString();
postimagelist.add(postimagelink);
}
String[] urls =postimagelist.toArray(new String[postimagelist.size()]);
postHolder.mPager.setAdapter(new SlidingImage_Adapter(mContext,urls));
postHolder.indicator.setViewPager(postHolder.mPager);
final float density = mContext.getResources().getDisplayMetrics().density;
postHolder.indicator.setRadius(5 * density);
postHolder.NUM_PAGES = urls.length;
postHolder.indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageSelected(int position) {
postHolder.currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
this my query in MainActivity.
mAdapter = new PostAdapter(MainActivity.this);
query = PostRef
.orderByChild("timestamp")
.limitToLast(mPostsPerPage);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Post> userModels = new ArrayList<>();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
String o=userSnapshot.getKey();
userModels.add(userSnapshot.getValue(Post.class));
//Here I want to retrieve no of "postimg"child and its value and pass in adapter//
}
mAdapter.addAll(userModels);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});