Adding Items in ListView From Firebase in Android Studio - android

In android I am simply add some values in listview from firebase now I data pair like:
I am using array list for adding this items on my adapter by the help of ChildEventListener, Here is my class :
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView listView;
ArrayList<String> arr = new ArrayList<>(10);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
final Firebase myFirebaseRef = new Firebase("https://f.......firebaseio.com/");
myFirebaseRef.child("Donors").child("Baldia Town").child("Ittehad Town").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
System.out.println(dataSnapshot.getKey() + " was " + dataSnapshot.getValue());
Log.d("obj", dataSnapshot.getKey() + " , " + dataSnapshot.getValue());
arr.add(dataSnapshot.getKey());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
listView = (ListView) findViewById(R.id.lvDonnors);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,arr);
arrayAdapter.notifyDataSetChanged();
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView text = (TextView) view;
Toast.makeText(this, text.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
Note: by this I simply get the Log :
Faizan: 2341
Hussain: 1345
Khezar: 2233
Zeeshan: 1122
but I want to add the name only in "arr" (list) . and when user press "zeeshan" I simply get its id (datasnapshot.getValue)like 1122 in any variable.
Can anyone help me to do this??

Related

Retrieve other values of child

So, I have this Firebase Structure.
I made an autocompletetext to get all child named "alimento".
That's OK!
But now, based on this "alimento" selection, I want to get all other childs in TextViews referent to this selection.
Is It possible? I don't know If I was clear enough.
This is my code: (I tried a lot of stuff, but all always return 0.00, so I won't put anything)
public class MainActivity extends AppCompatActivity {
private Button btnList, buttonAdicionar;
private AutoCompleteTextView autoCompleteTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnList = (Button) findViewById(R.id.btnList);
buttonAdicionar = (Button) findViewById(R.id.buttonAdicionar);
//Nothing special, create database reference.
final DatabaseReference database = FirebaseDatabase.getInstance().getReference();
//Create a new ArrayAdapter with your context and the simple layout for the dropdown menu provided by Android
final HRArrayAdapter<String> adapter = new HRArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line);
//Child the root before all the push() keys are found and add a ValueEventListener()
database.child("alimentos").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
adapter.clear();
//Basically, this says "For each DataSnapshot *Data* in dataSnapshot, do what's inside the method.
for (DataSnapshot suggestionSnapshot : dataSnapshot.getChildren()){
//Get the suggestion by childing the key of the string you want to get.
String autocomplete = suggestionSnapshot.child("alimento").getValue(String.class);
adapter.add(autocomplete);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.acTV);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setThreshold(1);
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String alimento = (String) parent.getItemAtPosition(position);
Log.d("TAG", alimento);
Toast.makeText(getApplicationContext(), alimento, Toast.LENGTH_SHORT).show();
}
});
btnList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), FoodActivity.class));
}
});
buttonAdicionar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), NewAlimentoActivity.class));
}
});
}
}
This is an example that what I want (using SQL):
If you're asking how to get all child nodes with a specific value in their alimento property, that'd be something like:
database.child("alimentos")
.orderByChild("alimento")
.equalTo("Arroz, integral, cozido")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String base = snapshot.child("base").getValue(String.class);
double baseValue = Double.parseDouble(base);
...
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});

Retrieved Data from Firebasedatabase and set into recyclierview Adapter

I want to read the data from firebasedatabase and show that into recyclerview retrieve data form FirebaseDatabase by orderbychild method. I want to read data of that child who's email match with my useremail who is currently login from app .
This is my Firebase:
I have successfully completed the first part, but I am facing problems with second part how can I pass the retrieved data to recyclerview adapter.
For example whenever user login from mobeen#gmail.com I read his location and ticket_no and show that data into recyclerview. I am facing problem with this line
programinglist.setAdapter(new myadapter(this, modl1));
where should I pass my modl1 (ArrayList<model> modl1) to recyclerview.setadapter
public class recyclierview extends AppCompatActivity {
public RecyclerView programinglist;
DatabaseReference b1, b2;
public ArrayList<model> modl1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recyclierview);
programinglist = findViewById(R.id.my_recycler_view);
programinglist.setLayoutManager(new LinearLayoutManager(this));
modl1 =new ArrayList<model>();
readdata(new firebasecallback() {
#Override
public void oncallback(ArrayList<model> list) {
Log.v("aliraza" , "value oncalback" + list.get(0).getTicket_no());
}
});
}
private void readdata(final firebasecallback firebasecallback)
{
b1= FirebaseDatabase.getInstance().getReference();
b2=b1.child("tasks");
b2.orderByChild("email").equalTo(MainActivity.email).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
model m = new model();
String location = dataSnapshot.child("location").getValue().toString();
String tickeno = dataSnapshot.child("ticket_no").getValue().toString();
Log.v("ALI", "family value " +location);
Log.v("ALI", "family value " + tickeno);
m.setLocation(location);
Log.v("ALI", "location " +m.getLocation());
m.setTicket_no(tickeno);
modl1.add(m);
Log.v("ALI", "family value " +modl1.get(0).getTicket_no());
firebasecallback.oncallback(modl1);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
programinglist.setAdapter(new myadapter(this, modl1));// where should i call this setadapter function of recyclierview.enter code here
}
private interface firebasecallback
{
void oncallback( ArrayList<model> list);
}
}
Initialise your arraylist and adapter;
public ArrayList<model> modl1=new ArrayList();
private myadapter adapter;
In onCreate() method initialize your adapter with blank list and set adapter to recyclerview.
adapter=new myadapter(this, modl1);
programinglist.setAdapter(adapter);
then create a method addItem() in your adapter.
public void addItem(model item){
list.add(item); // add item to your adapter list
notifyItemInserted(list.size());
}
changes in onChildAdded() method
modl1.add(m); //remove this line
firebasecallback.oncallback(m);
readdata(new firebasecallback() {
#Override
public void oncallback(model m) {
modl1.add(m);
adapter.add(m);
Log.v("aliraza" , "value oncalback" + list.get(0).getTicket_no());
}
});
You can remove firebasecallback method,as there is no need of it, and directly add item to adapter in onChildAdded() method. Simply call readdata() method from onCreate()
private void readdata()
{
b1= FirebaseDatabase.getInstance().getReference();
b2=b1.child("tasks");
b2.orderByChild("email").equalTo(MainActivity.email).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
model m = new model();
String location = dataSnapshot.child("location").getValue().toString();
String tickeno = dataSnapshot.child("ticket_no").getValue().toString();
Log.v("ALI", "family value " +location);
Log.v("ALI", "family value " + tickeno);
m.setLocation(location);
Log.v("ALI", "location " +m.getLocation());
m.setTicket_no(tickeno);
modl1.add(m);
Log.v("ALI", "family value " +modl1.get(0).getTicket_no());
adapter.add(m);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Hope this will help!!

Can't populate listview from firebase database but toast works

I am trying to update a listview realtime from my firebase database. The data uploads to database without any issues and a toast which displays the newly added data also works. But I could not get the listview to work. Here is my code:
public class MainActivity extends AppCompatActivity {
private ListView list;
private Button btnadd;
private EditText ettext;
private DatabaseReference mDatabase;
private ArrayList<String> arrayList= new ArrayList<>();
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=findViewById(R.id.liston);
list.setAdapter(adapter);
btnadd=findViewById(R.id.button);
ettext=findViewById(R.id.ed);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabase.push().setValue(ettext.getText().toString());
}
});
mDatabase= FirebaseDatabase.getInstance().getReference();
adapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
mDatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String string =dataSnapshot.getValue(String.class);
arrayList.add(string);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(),
"Name: " + dataSnapshot.getValue(), Toast.LENGTH_LONG)
.show();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String string =dataSnapshot.getValue(String.class);
arrayList.remove(string);
adapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
The updation of the database also happens from within the app using an "edittext" and a button.

In Firebase calss Adapter is fill with nothing

In FirebaseHelper Class I declare retrieve ArrayList method witch return spacecrafts ArrayList and it call fetchData method to add new Item in spacecrafts , In MainActivity I fill my adapter with helper.retrieve on the onCreate method , and make Dialog to add user Items when click saveBtn witch fill my adapter with helper.retrieve also , but adapter is fill with nothing , I make Toast to detect the problem and found that spacecrafts.size is fill every time with new Item but helper.retrieve().size every time =0 , Can anyone Shows me my mistake ?
here is FirebaseHelper Class :
class FirebaseHelper {
private DatabaseReference db;
private ArrayList<Spacecraft> spacecrafts=new ArrayList<>();
int x;
public FirebaseHelper(DatabaseReference db) {
this.db = db;
}
public Boolean save(Spacecraft spacecraft)
{
Boolean saved ;
if(spacecraft==null)
{
saved =false;
}else
{
try
{
db.child("Spacecraft").push().setValue(spacecraft);
saved =true;
}catch (DatabaseException e)
{
e.printStackTrace();
saved =false;
}
}
return saved;
}
private void fetchData(DataSnapshot dataSnapshot)
{
spacecrafts.clear();
for (DataSnapshot ds : dataSnapshot.getChildren())
{
Spacecraft spacecraft=ds.getValue(Spacecraft.class);
spacecrafts.add(spacecraft);
x=spacecrafts.size();
}
}
ArrayList<Spacecraft> retrieve()
{
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return spacecrafts;
}
}
and here is Main Activity class :
public class MainActivity extends AppCompatActivity {
DatabaseReference db;
FirebaseHelper helper;
MyAdapter adapter;
private RecyclerView rv;
EditText nameEditTxt,propTxt,descTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
rv= (RecyclerView) findViewById(R.id.rv);
rv.setLayoutManager(new LinearLayoutManager(this));
db= FirebaseDatabase.getInstance().getReference();
helper=new FirebaseHelper(db);
adapter=new MyAdapter(this,helper.retrieve());
rv.setAdapter(adapter);
Toast.makeText(MainActivity.this, "helper.retrieve().size() = " + helper.retrieve().size(), Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "spacecrafts.size() = " + helper.x, Toast.LENGTH_SHORT).show();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
displayInputDialog();
Toast.makeText(MainActivity.this, "spacecrafts.size() = " + helper.x, Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "helper.retrieve().size() = " + helper.retrieve().size(), Toast.LENGTH_SHORT).show();
}
});
}
private void displayInputDialog()
{
final Dialog d=new Dialog(this);
d.setTitle("Save To Firebase");
d.setContentView(R.layout.input_dialog);
nameEditTxt= (EditText) d.findViewById(R.id.nameEditText);
propTxt= (EditText) d.findViewById(R.id.propellantEditText);
descTxt= (EditText) d.findViewById(R.id.descEditText);
Button saveBtn= (Button) d.findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//GET DATA
String name=nameEditTxt.getText().toString();
String propellant=propTxt.getText().toString();
String desc=descTxt.getText().toString();
//SET DATA
Spacecraft s=new Spacecraft();
s.setName(name);
s.setPropellant(propellant);
s.setDescription(desc);
if(name.length() > 0)
{
if(helper.save(s))
{
nameEditTxt.setText("");
propTxt.setText("");
descTxt.setText("");
adapter=new MyAdapter(MainActivity.this,helper.retrieve());
Toast.makeText(MainActivity.this, "spacecrafts.size() = " + helper.x, Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "helper.retrieve().size() = " + helper.retrieve().size(), Toast.LENGTH_SHORT).show();
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
d.hide();
}
}else
{
Toast.makeText(MainActivity.this, "Name Must Not Be Empty", Toast.LENGTH_SHORT).show();
}
}
});
d.show();
}
}
Firebase operations are run asynchronously that means they are run on a separate thread, So your method ArrayList<Spacecraft> retrieve() returns the list before it is populated.
I try this and its work
private void fetchData(DataSnapshot dataSnapshot)
{
// spacecrafts.clear();
for (DataSnapshot ds : dataSnapshot.getChildren())
{
Spacecraft spacecraft=ds.getValue(Spacecraft.class);
spacecrafts.add(spacecraft);
x=spacecrafts.size();
}
}
ArrayList<Spacecraft> retrieve()
{
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// try to clear spacecrafts here
spacecrafts.clear();
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// and here
spacecrafts.clear();
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return spacecrafts;
}
}

the result of pressing button is displayed after two presses

I have an activity for searching in firebase, it contains edittext for typing the text and button when I press the button The results supposed to appear in the recyclerview but when I press the button the first time nothing appears unless I press the button for the second time
the code of findDataActivity
public class FindDataActivity extends AppCompatActivity {
DatabaseReference db;
FirebaseHelper helper;
MyAdapter adapter;
RecyclerView rv;
EditText findETxt;
Button findBtn;
ArrayList<Paints> p;
String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_data);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if(actionBar != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//SETUP RECYCLER
rv = (RecyclerView) findViewById(R.id.rvsearch);
rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
//INITIALIZE FIREBASE DB
db = FirebaseDatabase.getInstance().getReference("Database");
adapter = new MyAdapter(FindDataActivity.this, p);
rv.setAdapter(adapter);
findBtn = (Button) findViewById(R.id.find_btn);
helper = new FirebaseHelper(db);
}
public void search(View view) {
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
findETxt = (EditText) findViewById(R.id.findETxt);
s = findETxt.getText().toString();
p=helper.retrieveSearch(s);
adapter = new MyAdapter(FindDataActivity.this, p);
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id == android.R.id.home){
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
the code of firebase
public class FirebaseHelper {
DatabaseReference db;
Boolean saved=null;
Boolean saved1=null;
ArrayList<Paints> paints=new ArrayList<>();
ArrayList<String> keys=new ArrayList<>();
public FirebaseHelper(DatabaseReference db) {
this.db = db;
}
//READ THEN RETURN ARRAYLIST FOR SEARCH ITEMS IN CASE OF SEARCHING ABOUT ITEM
public ArrayList<Paints> retrieveSearch(final String item) {
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchDataSearch(dataSnapshot,item);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchDataSearch(dataSnapshot,item);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return paints;
}
//IMPLEMENT FETCH DATA AND FILL ARRAYLIST FOR SEARCH
private void fetchDataSearch( DataSnapshot dataSnapshot,String item)
{
paints.clear();
//sorting and searching
final DatabaseReference myRef = db.child("items");
Query query = myRef.orderByChild("type").startAt(item)
.endAt(item + "\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
Paints paint=messageSnapshot.getValue(Paints.class);
paints.add(paint);
//Toast.makeText(FindDataActivity.this, "found " + type + " unit: " + unit + " price " + price, Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
In your MyAdapter class you must create a method like this:
public void updateAdapter(ArrayList<Paints> paint){
this.paint= paint;
notifyDataSetChanged();
}
In your search method replace adapter.notifyDataSetChanged(); for adapter.updateAdapter(p);

Categories

Resources