I have a Spinner in which I want value from Firebase Database. I try what I Know since I am new to Android but the value in Spinner is not coming as i want it is coming like this.
When i am passing String Array directly it is coming Properly but it is doing problem when the String Array fill with the Firebase data.Here is also my Database.
final String[] batcht = {"1903f","343","33323"};
XML
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/stubatch"
/>
JAVA
public class Student extends AppCompatActivity {
DatabaseReference ref;
Spinner spinner;
List<String> store;
String[] batchlist;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student);
spinner = findViewById(R.id.stubatch);
store =new ArrayList<>();
Student_ID =getIntent().getStringExtra("Student_Id");
ref = FirebaseDatabase.getInstance().getReference("Batch");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot batches : dataSnapshot.getChildren()){
String a= batches.getValue().toString();
store.add(a);
}
batchlist = new String[store.size()];
for(int i=0;i<batchlist.length;i++){
batchlist[i]=store.get(i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(getApplicationContext(),android.R.layout.simple_spinner_item,batchlist);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}}
I don't know what I am doing wrong.
When you are fetching data you are doing some mistake. You are not fetching according to ur insertion technique try this
In for loop of datasnapshot use this code:
String a = batches.child("1710f").getValue().toString()
By doing this only data with the 1710f key will be picked for other values you have listed out all the keys.
Hopefully, this will workout
Actually the problem was that I was Storing the Data in the Firebase the wrong way.
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String batchdata = edit.getText().toString();
ref = FirebaseDatabase.getInstance().getReference("Batch").child(User_Id);
ref.child(batchdata).setValue(batchdata);
Toast.makeText(getApplicationContext(), "Successful", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(),Faculty.class);
i.putExtra("User_Id",User_Id);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
I Just have to remove the .child(User_Id);.
Now it is working Fine.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am new to android i have made a project to store members information in one activity and in another activity i display members in listView and on onlong clicking listview i open another activity to update members information but when i click on update button it adds that record instead of Updating.
My Firebase Structure :
My activity for storing :
public class MainActivity extends AppCompatActivity {
EditText txtname,txtage,txtheight,txtphone;
Button btnsave,btnRead;
Member member;
DatabaseReference reff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtname = findViewById(R.id.txtname);
txtage =findViewById(R.id.txtage);
txtphone =findViewById(R.id.txtphone);
txtheight =findViewById(R.id.txtheight);
btnsave = (Button)findViewById(R.id.btnsave);
btnRead =(Button)findViewById(R.id.btnRead);
btnRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivity();
}
private void openActivity() {
Intent intent = new Intent(MainActivity.this, Retreivedata.class);
startActivity(intent);
}
});
member = new Member();
reff = FirebaseDatabase.getInstance().getReference().child("Member");
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddUsers();
}
});
}
private void AddUsers(){
String name = txtname.getText().toString().trim();
String age = txtage.getText().toString().trim();
String phone = txtphone.getText().toString().trim();
String ht = txtheight.getText().toString().trim();
if(!TextUtils.isEmpty(name)) {
String id = reff.push().getKey();
Member member = new Member(id, name, age, phone, ht);
reff.child(id).setValue(member);
Toast.makeText(this,"User Inserted Successfully",Toast.LENGTH_LONG).show();
txtheight.setText("");
txtphone.setText("");
txtage.setText("");
txtname.setText("");
}else {
txtname.setError("Enter Name");
}
}
}
My activity for displaying records in listview:
public class Retreivedata extends AppCompatActivity {
ListView listView;
FirebaseDatabase database;
DatabaseReference ref;
ArrayList<Member> list;
ArrayAdapter<Member> adapter;
Member member;
Button btnDlt;
Boolean a=false;
String val="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retreivedata);
member = new Member();
listView =(ListView)findViewById(R.id.listView);
btnDlt = (Button) findViewById(R.id.btnDlt);
database = FirebaseDatabase.getInstance();
ref = database.getReference("Member");
list = new ArrayList<>();
adapter = new ArrayAdapter<Member>(this,R.layout.list_white_text,R.id.userInfo, list);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dts: dataSnapshot.getChildren())
{
member = dts.getValue(Member.class);
list.add(member);
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
btnDlt.setEnabled(false);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Boolean a=true;
Member member=adapter.getItem(position);
Toast.makeText(Retreivedata.this,"Do u want to delete this record!!",Toast.LENGTH_LONG).show();
if (a==true)
{
btnDlt.setEnabled(true);
}else{
btnDlt.setEnabled(false);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Member member= adapter.getItem(position);
Intent intent = new Intent(Retreivedata.this, Update.class);
intent.putExtra("tem", member);
startActivity(intent);
return false;
}
});
btnDlt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ref.child(member.getMemberId()).removeValue();
Toast.makeText(Retreivedata.this, "Record deleted Successfully",
Toast.LENGTH_LONG).show();
adapter.remove(member);
adapter.clear();
}
});
}
}
My activity for updating record:
public class Update extends AppCompatActivity {
EditText EditTxtName,EditTxtAge,txtPhone,txtHeight;
Member member;
FirebaseDatabase db;
DatabaseReference reff;
Button btnUpdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
EditTxtName = (EditText)findViewById(R.id.EditTxtName);
EditTxtAge = (EditText)findViewById(R.id.EditTxtAge);
txtPhone = (EditText)findViewById(R.id.txtPhone);
txtHeight = (EditText)findViewById(R.id.txtHeight);
btnUpdate = (Button)findViewById(R.id.btnUpdate);
final Member member= (Member) getIntent().getSerializableExtra("tem");
EditTxtName.setText(member.getName());
EditTxtAge.setText(member.getAge());
txtPhone.setText(member.getPhone());
txtHeight.setText(member.getHeight());
reff = db.getInstance().getReference().child("Member");
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Update();
}
});
}
private void Update(){
final String mnam = EditTxtName.getText().toString().trim();
final String mage = EditTxtAge.getText().toString().trim();
final String mph = txtPhone.getText().toString().trim();
final String mhei = txtHeight.getText().toString().trim();
final String ID = reff.getKey();
if(TextUtils.isEmpty(mnam)) {
EditTxtName.setText("Plz enter name");}
if(TextUtils.isEmpty(mage)) {
EditTxtName.setText("Plz enter age");}
else{
final Member member = new Member(ID,mnam,mage,mph,mhei);
reff.child("Member").child(ID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
reff = FirebaseDatabase.getInstance().getReference();
reff.child("Member").child(ID).child("name").setValue(mnam);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Toast.makeText(Update.this,"Updated",Toast.LENGTH_LONG).show();
txtHeight.setText("");
txtPhone.setText("");
EditTxtName.setText("");
}
}
}
But after updating record it creates another record.Suggest me what changes has to be done on update button click.
Thnaks!!
First I assume that you implement Serializable for your Member class:
class Member implements Serializable{
.............
.............
.............
}
Since you are passing the member object to the update activity, why not use the ID in it to update the data:
//the update activity
public class Update extends AppCompatActivity {
//this is the member that you pass
Member member;
......
......
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.........
.........
//this is how you retrieve it
member= (Member) getIntent().getSerializableExtra("tem");
//this is your ref
reff = db.getInstance().getReference().child("Member");
........
........
}
//when you update
private void Update(){
final String mnam = EditTxtName.getText().toString().trim();
final String mage = EditTxtAge.getText().toString().trim();
final String mph = txtPhone.getText().toString().trim();
final String mhei = txtHeight.getText().toString().trim();
//update the name field
reff.child(member.getMemberId()).child("name").setValue(mnam);
}
Your problem is this line of code final String ID = reff.getKey()
That call generates a new ID which you then use in your update of the db. You need to replace the call to getKey with the ID of the member you want to update.
I want to retrieve data from firebase to show in a ListView but when i run the app, the ListView does not show any data. I see the ListView but there is no data. Can you tell me why and what can i do? I had the same problem when i tried with spinner.
public class CitiesList extends AppCompatActivity {
DatabaseReference databasePaths;
private ListView ListViewCities;
private ArrayList<String> ArrayListCities;
private ArrayAdapter<String> adapterCities;
Paths info;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cities_list);
ListViewCities = (ListView) findViewById(R.id.ListViewCities);
ArrayListCities = new ArrayList<>();
databasePaths = FirebaseDatabase.getInstance().getReference("Paths");
databasePaths.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot items: dataSnapshot.getChildren())
{
info = items.getValue(Paths.class);
ArrayListCities.add(info.city);
}
adapterCities = new ArrayAdapter<>(CitiesList.this, android.R.layout.simple_list_item_1);
ListViewCities.setAdapter(adapterCities);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}}
You need to set new list to adapter, which you are not doing into your current code. Modify below line
adapterCities = new ArrayAdapter<>(CitiesList.this, android.R.layout.simple_list_item_1);
ListViewCities.setAdapter(adapterCities);
as
adapterCities = new ArrayAdapter<>(CitiesList.this, android.R.layout.simple_list_item_1, ArrayListCities);
ListViewCities.setAdapter(adapterCities);
As a side note, try to follow coding style guidelines.
You need to pass in Adapter the TextView from where the adapter will set the data.
So after R.layout.XXXX, you need to pass:
android.R.id.text1
Hello so I've been strugging for awhile now. I want to consult someone about my code. I want to apply
a coloring function to my app.
When the person presses the button when it's at its:
GREEN state it updates the value on the database to BEING HOUSEKEPT
YELLOW state when pressed sends READY FOR INSPECTION RoomStatus
RED state when pressed sends READY FOR HOUSEKEEPING RoomStatus
It was working earlier but when I tried to restrict the users that users who are Housekeepers can't access the RED STATE which are for House Keepers, I inserted somewhere in my code where I want to implement it.
I'm going over loops here can somebody tell me where I did wrong?
Here's my code:
Button room1;
private DatabaseReference mFirebaseDatabase, mFirebaseDatabase1, mFirebaseDatabase1room;
private FirebaseDatabase mFirebaseInstance;
private DatabaseReference referenceroom1;
private String roomStat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navi_to_scan2);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase1 = mFirebaseInstance.getReference("Rooms");
mFirebaseDatabase = mFirebaseInstance.getReference("Users");
mFirebaseDatabase1room = mFirebaseInstance.getReference("Rooms").child("Room1");
referenceroom1 = mFirebaseDatabase1.child("Room1").child("RoomStatus");
room1 = (Button) findViewById(R.id.rm1Btn);
mFirebaseDatabase1.child("Room1").addValueEventListener(new ValueEventListener() { //attach listener
#Override
public void onDataChange(DataSnapshot dataSnapshot) { //something changed!
for (DataSnapshot locationSnapshot : dataSnapshot.getChildren()) {
String location = locationSnapshot.getValue().toString();
if (location.equals("READY FOR HOUSEKEEPING")) {
room1.setBackgroundColor(Color.GREEN);
roomStat = "Green";
} else if (location.equals("BEING HOUSEKEPT")) {
room1.setBackgroundColor(Color.YELLOW);
roomStat = "Yellow";
} else {
room1.setBackgroundColor(Color.RED);
roomStat = "Red";
}
if (roomStat.equals("Green")) {
room1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "BEING HOUSEKEPT";
DatabaseReference reference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
reference.setValue(message);
Intent next1 = new Intent(getApplicationContext(), ReaderActivity3.class);
startActivity(next1);
}
});
} else if (roomStat.equals("Yellow")) {
room1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "READY FOR INSPECTION";
DatabaseReference reference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
reference.setValue(message);
Intent next1 = new Intent(getApplicationContext(), ReaderActivity2.class);
startActivity(next1);
}
});
} else {
room1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "READY FOR HOUSEKEEPING";
DatabaseReference reference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
reference.setValue(message);
Intent next1 = new Intent(getApplicationContext(), ReaderActivity.class);
startActivity(next1);
//I ALSO WANT TO PUT A CONDITION HERE FETCHING userType from Structure
// mFirebaseDatabase = mFirebaseInstance.getReference("Users").child("userKey");
//but doing this would mean that I would have to put a listener inside, would that be okay? I tried when this
//was working at first but it didin't and now the whole thing is not working
}
});
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) { //update UI here if error occurred.
}
});
}
Here's my structure:
Can you help me identify what's the problem with how i implemented this?
I see nothing wrong, try debugging. Android is buggy nowadays, especially when you're connecting to a cloud database. In the left side of the run button the bug shaped one. Debug.
Or maybe you could try to show your location which is your string, to check if you pulled the right info from your database. You can use logs. A guide can be found here
https://developer.android.com/studio/debug/am-logcat.html
i am trying to read a specific child in Firebase which i named Tags. the problem is, i just can't put the object from tags (dados.getValue) into a ArrayList to later populate in my ListView.
I know is simple, sorry about that, ut i am new here in android
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_taglist);
tags = new ArrayList<>();
tagList = (ListView) findViewById(R.id.tagsList);
tagsRefs = FirebaseConfig.getFireBase();
tagsRefs.child("tags").child("categorias");
tagsRefs.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dados : dataSnapshot.child("tags").getChildren()) {
System.out.println("tag EXTRAIDA NO taglist " + dados.getValue());
dados.getValue(); //HOW CAN I PUT THIS INTO AN ARRAY TO LATER ADD IN MY ArrayList tags??
String tagS = dados.getValue(String.class);
tags.addAll(tagS);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
tagAdapter = new ArrayAdapter(getBaseContext(), android.R.layout.simple_list_item_2,
android.R.id.text1,
tags);
tagList.setAdapter(tagAdapter);
tagList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedTag = (String) tagList.getItemAtPosition(position);
setSelectedTag(selectedTag);
}
});
}
here is my database:
h
This is happening because onDataChange() method is called asynchronously. This means that the statement that adds tags to your list is executed before onDataChange() method has been called. That's why your list is empty outside that method. So in order to use that lists, you need to use it inside the onDataChange().
For other approach, please visit this post and this post.
Hope it helps.
I need to give a custom login. I don't want to use login providers like google, facebook,etc. I need old school single data retrieval of users info(name and phone in my case) and if user data is found in the database then redirect to home page.I have tried something and it's not working.
java snippet
................................................
public class LoginActivity extends AppCompatActivity {
EditText editTextname;
EditText editTextphone;
Button buttonlogin;
Spinner spinnerdesignation;
DatabaseReference rootRef= FirebaseDatabase.getInstance().getReference();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextname=(EditText)findViewById(R.id.name);
editTextphone=(EditText)findViewById(R.id.phonenumber);
spinnerdesignation=(Spinner)findViewById(R.id.designation);
buttonlogin=(Button)findViewById(R.id.login);
buttonlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findUser();
}
});
}
public void findUser(){
String designation=spinnerdesignation.getSelectedItem().toString();
if(designation=="Faculty"){
rootRef.child("Faculty").orderByChild("facultyName").equalTo(editTextname.toString()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String,String> map=dataSnapshot.getValue(Map.class);
String phoneNumber=map.get("facultyPhone");
if(phoneNumber==editTextphone.toString()){
Intent intent=new Intent(getApplicationContext(),FacultyActivity.class);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
database
-Root
-Faculty
-Kg5Qe482G7xEn9rYLXn
facultyDept:"computer science"
facultyDesignation: "HOD"
facultyEmail: "ajaskjfjaj#gmail.com"
facultyID: "-Kg5Qe482G7xEn9rYLXn"
facultyName: "john"
facultyPhone: "1234567891"
-Kg5QjXQIZeuwvHi22WH
-Student
-Kg-Jg1f68RXb4N47sbA
You should use String#equals method when comparing strings. Do not use ==.