How to compare value from radio button with specific value in firebase - android

I'm trying to assign my radio button value with a specific value in Firebase. But when I run it, I did not get the output. The problem of the coding is here (snapshot.child("Allergy").child("None").getValue().equals(selectedRadioValue2)))) when I'm trying to assign the "None" value. Can anyone help?
dr.addValueEventListener(new ValueEventListener() {
Intent intent = getIntent();
String selectedRadioValue1 = intent.getExtras().getString("SelectedValue1");
String selectedRadioValue2 = intent.getExtras().getString("SelectedValue2");
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if ((snapshot.child("Age").getValue().equals(selectedRadioValue1))&&((!snapshot.child("Allergy").getValue().equals(selectedRadioValue2))
|| (snapshot.child("Allergy").child("None").getValue().equals(selectedRadioValue2))))
{
String ingredient = snapshot.child("Ingredient").getValue().toString();
HashSet<String> hashSet = new HashSet<String>();
al.add(ingredient);
hashSet.addAll(al);
al.clear();
al.addAll(hashSet);
Collections.sort(al);
ad.notifyDataSetChanged();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(result.this, "Category Selected", Toast.LENGTH_SHORT).show();
String TempListViewClickedValue = al.get(position).toString();
Intent intent = new Intent (result.this,RecommendedFood.class);
intent.putExtra("1",selectedRadioValue1);
intent.putExtra("2",selectedRadioValue2);
intent.putExtra("RecommendedFood",TempListViewClickedValue);
startActivity(intent);
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
This is my firebase

Related

How can we store dropdown selected option string to firestore in android studio

I have String list as shown I want the selected item to be store in Firestore
Can you please tell me how it should be possible?
I have String list as shown I want the selected item to be store in Firestore
Can you please tell me how it should be possible?
public class Student_Register_Activity extends AppCompatActivity {
EditText etRegEmail,etname,etfathername,etRollno,etdepartment,etadress,etphonenmbr,semester,;
EditText etRegPassword;
String[] items={"Shinkiari","Mansehra","Abbottabad","Qalandarabad","Attersheesha","Khaki"};
AutoCompleteTextView autoCompleteText;
Button btnRegister;
ArrayAdapter<String> adapteritems;
FirebaseAuth mAuth;
FirebaseFirestore firestore=FirebaseFirestore.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_register);
autoCompleteText=findViewById(R.id.auto_complete_txt);
adapteritems=new ArrayAdapter<String>(this,R.layout.list_item,items);
autoCompleteText.setAdapter(adapteritems);
autoCompleteText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String item =adapterView.getItemAtPosition(position).toString();
}
});
etRegEmail = findViewById(R.id.etRegEmail);
etRegPassword = findViewById(R.id.etRegPass);
btnRegister = findViewById(R.id.btnRegister);
etname = findViewById(R.id.etname);
etfathername = findViewById(R.id.etfname);
etRollno = findViewById(R.id.etRollno);
etdepartment = findViewById(R.id.etdepartment);
etadress = findViewById(R.id.etadress);
etphonenmbr = findViewById(R.id.etphonenmbr);
mAuth = FirebaseAuth.getInstance();
btnRegister.setOnClickListener(view -> createUser());
}
private void createUser(){
String email = etRegEmail.getText().toString();
String password = etRegPassword.getText().toString();
if (TextUtils.isEmpty(email)){
etRegEmail.setError("Email cannot be empty");
etRegEmail.requestFocus();
}else if (TextUtils.isEmpty(password)){
etRegPassword.setError("Password cannot be empty");
etRegPassword.requestFocus();
}else{
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(Student_Register_Activity.this, "Student registered successfully", Toast.LENGTH_SHORT).show();
FirebaseUser user = mAuth.getCurrentUser();
DocumentReference df = firestore.collection("Student").document(user.getUid());
//Map is used to store the data
Map<String,Object> userinfo = new HashMap<>();
userinfo.put("Name",etname.getText().toString());
userinfo.put("FName",etfathername.getText().toString());
userinfo.put("Email",etRegEmail.getText().toString());
userinfo.put("Password",etRegPassword.getText().toString());
userinfo.put("semester",etRegPassword.getText().toString());
userinfo.put("Transport", adapteritems.toString();
userinfo.put("Rollno",etRollno.getText().toString());
userinfo.put("Department",etdepartment.getText().toString());
userinfo.put("address",etadress.getText().toString());
userinfo.put("phone",etphonenmbr.getText().toString());
startActivity(new Intent(Student_Register_Activity.this, AdminDashboard.class));
//specify if user is student
userinfo.put("isStudent","1");
df.set(userinfo);
}else{
Toast.makeText(Student_Register_Activity.this, "Registration Error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
I think you want to add selected items from list in user object, If that so you can follow below steps:
first declare global variable for selected
String selectedOption;
Then save value in on click of list
autoCompleteText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
selectedOption =adapterView.getItemAtPosition(position).toString();
}
});
then use that value to save in user object
userinfo.put("city",selectedOption);

how can get spinner values when I used if else then pass value to setonClick?

how can get spinner values when I used if else then pass value to setonClick?
in my code, I used this methods to set spinner values
DatabaseReference chk_sub = FirebaseDatabase.getInstance()......
chk_sub.addValueEventListener(new ValueEventListener() {
if(xxxxxx){
List<String> sub = new ArrayList<>();
sub.add(0, getApplicationContext().getResources().getString(R.string.choose_sub));
sub.add("USA");
sub.add("CA");
ArrayAdapter<String> dataSpinnerAdapter;
dataSpinnerAdapter = new ArrayAdapter(getApplication(), android.R.layout.simple_spinner_item, sub);
dataSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataSpinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getItemAtPosition(position).equals(getApplicationContext().getResources().getString(R.string.choose_sub))){
//do nothing
} else {
spinner_item = parent.getItemAtPosition(position).toString();
//Toast.makeText(parent.getContext(),"Selected : "+item, Toast.LENGTH_SHORT).show();
}
}
}
and I hope I can get spinner sub value because I need to judge
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( -- how can get spinner value in here? --){
//
}else {
Toast.makeText(getApplication(), getApplicationContext().getResources().getString(R.string.must_upload), Toast.LENGTH_SHORT).show();
}
}
});
If you just want selected spinner item to be used in if(condition=spinner value) on click event of post i.e., post.onClick(), just get the spinner selected item
your code will look like this
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(spinner.getSelectedItem().equals("your compare value")){
// do whatever you want
}else {
Toast.makeText(getApplication(), getApplicationContext().getResources().getString(R.string.must_upload), Toast.LENGTH_SHORT).show();
}
}
});

How to write Shared preference Code that uses firebase for User authentication?

How do I write Shared-preference Code that is using Firebase for User authentication and the data that is saved by a user is only accessible for them?
My current application Saves a note and displays it which is the main thing needed in my project but when a user logs out and new user logs in he/she can also view the data so the data is not private. My sir suggested to make nodes for users using shared preference but i couldn't find any solutions
HomeActivity:
public class HomeActivity extends AppCompatActivity {
EditText Descriptionholder;
Button Savebtn;
DatabaseReference DatabaseNote;
ListView listViewNotes;
List<PrivateNote> privateNoteList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
DatabaseNote = FirebaseDatabase.getInstance().getReference("privatenote");
Descriptionholder = findViewById(R.id.description2);
Savebtn = findViewById(R.id.buttonsave);
listViewNotes= findViewById(R.id.listViewPrivate);
privateNoteList = new ArrayList<>();
Savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addnote();
}
});
listViewNotes.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
PrivateNote privateNote = privateNoteList.get(i); //confusion
showUpdateDialog(privateNote.getNoteId(),privateNote.getNoteDescription());
return false;
}
});
}
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.side, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()) {
case R.id.item1:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(new Intent(this, MainActivity.class)));
Toast.makeText(this, "Logged out ", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onStart() {
super.onStart();
DatabaseNote.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
privateNoteList.clear();
for (DataSnapshot privateSnapshot: dataSnapshot.getChildren() ){
PrivateNote privateNote = privateSnapshot.getValue(PrivateNote.class);
privateNoteList.add(privateNote);
}
PrivateList adapter = new PrivateList(HomeActivity.this,privateNoteList);
listViewNotes.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showUpdateDialog(final String noteId, String noteDescription){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogview = inflater.inflate(R.layout.update_dialouge,null);
dialogBuilder.setView(dialogview);
final EditText editDescription = dialogview.findViewById(R.id.editDescription);
final Button buttonUpdate = dialogview.findViewById(R.id.buttonUpdate);
final Button buttonDelete = dialogview.findViewById(R.id.buttonDelete);
dialogBuilder.setTitle("Updating Note: " +noteDescription);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String description = editDescription.getText().toString().trim();
if (TextUtils.isEmpty(description)){
editDescription.setError(" New information required");
return;
}
updatePrivateNote(noteId,description);
alertDialog.dismiss();
}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePrivateNote(noteId);
}
});
}
private void deletePrivateNote(String noteId) {
DatabaseReference drPrivateNote = FirebaseDatabase.getInstance().getReference("privatenote").child(noteId);
drPrivateNote.removeValue();
Toast.makeText(this, " Note Deleted", Toast.LENGTH_SHORT).show();
}
private boolean updatePrivateNote(String id,String description){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("privatenote").child(id);
PrivateNote privateNote = new PrivateNote(id,description);
databaseReference.setValue(privateNote);
Toast.makeText(this, " Note Updated", Toast.LENGTH_SHORT).show();
return true;
}
private void addnote () {
String description = Descriptionholder.getText().toString().trim();
if (!TextUtils.isEmpty(description)){
//generated unique number for id
String id = DatabaseNote.push().getKey();
PrivateNote pNote = new PrivateNote(id, description);
DatabaseNote.child(id).setValue(pNote); //pNote value added in id
Toast.makeText(this, "Note added", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, " Please Enter a note ", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
FirebaseAuth.getInstance().signOut();
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Adapter:
public class PrivateList extends ArrayAdapter<PrivateNote> {
private Activity context;
private List<PrivateNote> privateNoteList;
public PrivateList(Activity context, List<PrivateNote> privateNoteList){
super(context, R.layout.list_layout,privateNoteList);
this.context =context;
this.privateNoteList=privateNoteList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_layout,null,true);
TextView textViewDescription = listViewItem.findViewById(R.id.TextViewDescription);
PrivateNote privateNote = privateNoteList.get(position);
textViewDescription.setText(privateNote.getNoteDescription());
return listViewItem;
}
}
PrivateNote:
public class PrivateNote {
public String noteId;
public String noteDescription;
public PrivateNote(){
}
PrivateNote(String noteId, String noteDescription){
this.noteId = noteId;
this.noteDescription=noteDescription;
}
String getNoteId()
{
return noteId;
}
String getNoteDescription()
{
return noteDescription;
}
}
In Firebase, there are two things,
FirebaseDatabase
FirebaseAuth
Usually, in almost all the apps, user data is stored in the FirebaseDatabase under the key, that is generated while creating a new user in your Firebase app.
So, for example, your database structure will look like this.
-Your_main_database
|____UserId_Of_FirebaseUser
|____stuff_related_to_user
|____More stuff related to user
So, you create a new user in FirebaseAuth, you can find more about it below:
Firebase Custom Auth.
Then, after creating a new user, you create child nodes under your database with the key=userId of your current logged in user.
eg. In your addNote function, the id variable will be equal to
String id = FirebaseAuth.getInstance().getCurrentUser().getUid();
Currently, you're using Push keys which are generated based on Timestamp, which you won't be able to associate with user unless you add a key inside your note object which stored current username, and then find all the child nodes that contain that username, but in that case, your data won't be organized at all.
Then, after you create a node with userId under your main database, you can then push new notes created by your user inside the userId with the push() function. So your database structure will look like below.
___
|
|__users
|__uniqueUserId
| |__note1
| |__note2
|__uniqueUserId2
|__note1
|__note2
|__note3
Next time whenever you want to fetch user created notes, you log in the user, get his ID, and then find the notes corresponding to that ID.
I don't see how you can fit SharedPreferences in there, before there is also function to cache data offline in Firebase once it is loaded.
Securing the notes:
If you implement the database like I said above, you'll be very easily able to secure your database.
Common Database Rules.
If you implement everything correctly like I told, you'll be able to secure your database with the fourth set of rules from above rules.
Since you are using firebase authentication, then you can retrieve the userId, and create the following database:
notes
userId
note : "todo"
description : "study"
Then you can do:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("notes");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId = user.getUid();
ref.orderByKey().equalTo(userId).addValueEventListener(new ValueEventListener() {...}
This way you would retrieve the data of the currently logged in user only.

Get Can't pass null for argument 'pathString' in child() error

I having some trouble with how to use a Button to access another activity with data from firebase. I'm just getting an error "Can't pass null for argument 'pathString' in child()". But when I try in another activity with OnItemClick on a listview item it works. Why is that?
What I'm trying to do is: I have a activity with a listview that stores and get data from firebase. What I want is, if I click on one of the items in that listview I want a new activity with buttons, and these buttons will get me to another activity with a listview that are related to the first activity (related data). So the activity with the buttons are the same activity for every listview items i click on, like just a "dummy" activity. Is this possible?
Here is the code:
lvjobbinfo works fine, but add doesn't. I want lvjobbinfo and add to do the same.
public class MainActivity extends AppCompatActivity {
EditText etinfonavn;
ListView lvjobbinfo;
TextView tvjobbnavn;
Button add;
DatabaseReference databaseJOBBINFO;
List<Main> jobbinfo;
public static final String infonavn = "infonavn";
public static final String infoid = "infoid";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseJOBBINFO = FirebaseDatabase.getInstance().getReference().child("Jobbinfo");
lvjobbinfo = (ListView)findViewById(R.id.lvjobbinfo);
lvjobbinfo.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
Main main = jobbinfo.get(i);
Intent intent = new Intent(getApplicationContext(), Notater.class);
intent.putExtra(infoid, main.getInfoId());
intent.putExtra(infonavn, main.getInfonavn());
startActivity(intent);
return true;
}
});
tvjobbnavn = (TextView)findViewById(R.id.tvjobbnavn);
etinfonavn = (EditText) findViewById(R.id.etinfonavn) ;
add = (Button)findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent add = new Intent(MainActivity.this, Notater.class);
startActivity(add);
}
});
Intent intent = getIntent();
jobbinfo = new ArrayList<>();
String id = intent.getStringExtra(Jobbliste.jobbId);
String navn = intent.getStringExtra(Jobbliste.jobbnavn);
tvjobbnavn.setText(navn);
databaseJOBBINFO = FirebaseDatabase.getInstance().getReference("Jobbinfo").child(id);
}
#Override
protected void onStart() {
super.onStart();
databaseJOBBINFO.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
jobbinfo.clear();
for (DataSnapshot infosnapshot : dataSnapshot.getChildren()) {
final Main main = infosnapshot.getValue(Main.class);
jobbinfo.add(main);
final listMain infolistadapter = new listMain(MainActivity.this, jobbinfo);
lvjobbinfo.setAdapter(infolistadapter);
infolistadapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Data fetched from FirebaseDatabase is getting shown in 3 separate AlertDialogs instead of one

I'm fetching some data from FirebaseDatabase and then putting them into an array and then trying to show them in a List which is in a custom AlertDialog.
Here's the code:
query = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
uProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
query.orderByChild("someChild").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null) {
Map<String, String> newD = (Map<String, String>) dataSnapshot.getValue();
ArrayList<String> l = new ArrayList<String>();
l.add(newD.get("lol").substring(30));
String names[] = l.toArray(new String[0]);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Activity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.dialog_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("title");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, names);
lv.setAdapter(adapter);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alertDialog.show();
} else {
Toast.makeText(getBaseContext(), "NULLLLL", Toast.LENGTH_SHORT).show();
}
}
...
...
});
}
});
Here's the database structure:
app
-child
-anotherChild
-yetAnotherChild
-inaccessibleChild
-someChild: "value"
-lol: "value"
I can't use valueEventListener() here as I have no access to inaccessibleChild. The inaccessibleChild here is the uid of the other users who followed a particular user. How can I access there uid?
The problem is that data is getting fetched but instead of getting shown in a list in one AlertDialog, it is getting shown one-by-one in 3 separate AlertDialog.
What is going wrong here?
Please let me know.
Firebase transactions are asynchronous so your initial line to add the 3 children happens after you set your listener, therefore your callback is called 3 times. (making 3 dialogs).
Move this line outside of the on click:
query = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
Then when you add the below listener (inside the on click) it should be ok
query.orderByChild("someChild").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Put limit when you are using valueEventListener or addChildEventListener. like this,
int limit = 100;
databaseRef.child("chats").limitToLast(limit).addValueEventListener(listener);
And always remove listener when you've done with your work related to firebase. like this,
databaseRef.child("chats").limitToLast(limit).removeEventListener(listener);
Thanks.
Create and show the AlertDialog before you call .addChildEventListener()
Then use inside addChildEventListener call notifyDatasetChanged() after you downloaded the appropriate data. Do not create the AlertDialog inside the addChildEventListener
You can use Firebase Queries to limit the data that is downloaded by a listener.
query.orderByChild("someChild").limitToLast(1).addChildEventListener(...
#Blundell has the insight of solving your problem. I just want to suggest you a similar approach with addValueEventListener.
The value event listener will fire once for the initial state of the
data, and then again every time the value of that data changes.
You need to move out the firebase query from onClick function. So your query might look like this..
// Declare the variable names as public
private String names[];
private void addFirebaseListener() {
ref = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
ref. userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Map<String, String> newD = (Map<String, String>) dataSnapshot.getValue();
ArrayList<String> l = new ArrayList<String>();
l.add(newD.get("lol").substring(30));
names[] = l.toArray(new String[0]);
// Call notifyDataSetChanged each time your array gets updated
adapter.notifyDataSetChanged();
}
#Override public void onCancelled(FirebaseError error) { }
});
}
Now write a function to show the ListView in the AlertDialog
// Declare the adapter as public and initialize it with null
private ArrayAdapter<String> adapter = null;
private void showListInDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Activity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.dialog_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("title");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
if(adapter == null)
adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, names);
// Now set the adapter
lv.setAdapter(adapter);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
Now inside your onCreate function you need to set the Firebase listener first and then set the onClick function like this.
uProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showListInDialog();
}
});
#Hammad Try this modified code basing on your requirement.
query = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
AlertDialog alertDialog;
ArrayList<String> l;
uProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
query.orderByChild("someChild").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null) {
Map<String, String> newD = (Map<String, String>) dataSnapshot.getValue();
if(l == null) {
l = new ArrayList<String>();
}
l.add(newD.get("lol").substring(30));
String names[] = new String[l.size()];
for(int length=0; length < l.size(); l++) {
names[length] = l.get(length);
}
if(alertDialog == null) {
alertDialog = new AlertDialog.Builder(Activity.this).create();
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.dialog_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("title");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
} ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, names);
lv.setAdapter(adapter);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
if(!alertDialog.isShowing()) {
alertDialog.show();
}
} else {
Toast.makeText(getBaseContext(), "NULLLLL", Toast.LENGTH_SHORT).show();
}
}
...
...
});
}
});
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
/**
Retrieve lists of items or listen for additions to a list of items. This callback is triggered once for each existing child and then again every time a new child is added to the specified path. The DataSnapshot passed to the listener contains the new child's data.
**/
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
ref.addChildEventListener(childEventListener);
Usining ChildEventListener onChildAdded are call per child you have in that node. Means your code runs 3 time so dialog appers 3 time.
This is the problem
So the solution is:
While using a ChildEventListener is the recommended way to read lists of data, there are situations where attaching a ValueEventListener to a list reference is useful.
Attaching a ValueEventListener to a list of data will return the entire list of data as a single DataSnapshot, which you can then loop over to access individual children.
Even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result:
inaccessibleChild.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
//here you can access the each child of that node.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
});
Well, none of the above answers really helped, though Linxy's answer is correct, I saw it after solving the probelm.
Moving all the code out and writing just this line: alertDialog.show(); inside setOnClickListener() improving my code to this:
query = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
query.orderByChild("someChild").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null) {
Map<String, String> newD = (Map<String, String>) dataSnapshot.getValue();
ArrayList<String> l = new ArrayList<String>();
l.add(newD.get("lol").substring(30));
String names[] = l.toArray(new String[0]);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Activity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.dialog_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("title");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, names);
lv.setAdapter(adapter);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
} else {
Toast.makeText(getBaseContext(), "NULLLLL", Toast.LENGTH_SHORT).show();
}
}
...
...
});
uProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert11.show();
}
});
Anyway, I would like to thank all those who answered this question.
Peace.

Categories

Resources