How to display new data at the top position of an adapter? Here are the coding:-
Sorry just now, I wrongly copy the coding, now I just noticed. Sorry my bad. The issues now is I want to display the latest advertisement at the top of the adapter....
mDatabase.child("Advertisement").child(mAuth.getUid()).addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
//iterating through all the values in database
mChildrenList = new ArrayList<>();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
Advertisement advertisement = postSnapshot.getValue(Advertisement.class);
mChildrenList.add(advertisement);
}
//Creating adapter
mAdapter = new AdvertisementAdapter(getApplicationContext(), mChildrenList, "AddAds");
//Adding adapter to recyclerview
mRecyclerView.setAdapter(mAdapter);
//mAdapter.notifyItemChanged(0);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
This line:
tuitionPackageList.add(0, new TuitionPackage(tuitionPackageList));
you get an error because you are instantiating a TuitionPackage object with tuitionPackageList as a parameter and I believe this is not correct.
Earlier in the code you made the same instantiation with just:
TuitionPackage tuitionPackage = new TuitionPackage();
and you added the item to the end of the list.
Is it this item that you wanted to add at position 0?
Edit change to this:
else {
TuitionPackage tuitionPackage = new TuitionPackage();
tuitionPackage.setPrice(mPriceView.getText().toString());
tuitionPackageList.add(0, tuitionPackage);
mPackageAdapter.notifyItemInserted(0);
}
replace last else block with this
TuitionPackage tuitionPackage = new TuitionPackage();
tuitionPackage.setPrice(mPriceView.getText().toString());
tuitionPackageList.add(tuitionPackage);
mPackageAdapter.notifyDataSetChanged();
Here are my answer with the help from the above coding to sort the first ads at the top position:-
//Iterating through all the values in database
mChildrenList = new ArrayList<>();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
Advertisement advertisement = postSnapshot.getValue(Advertisement.class);
mChildrenList.add(0, advertisement);
}
//Creating adapter
mAdapter = new AdvertisementAdapter(getApplicationContext(), mChildrenList, "AddAds");
//Adding adapter to recyclerview
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyItemInserted(0);
Related
I can only retrieve first data "9780071792745" from my database. The app crashed when I tried to retrieve data from b. Here is my code
public class wish_list extends AppCompatActivity {
TextView display;
//private String wishlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wish_list);
display=(TextView)findViewById(R.id.tvDisplay);
//start here
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Wishlist");
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
List<String> wishlist_item = new ArrayList<String>();
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
wishlist_item.add(postSnapshot.getValue().toString());//got all wish list item from database
String a = wishlist_item.get(0);
String b = wishlist_item.get(1);
display.setText("Hi" + a);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
I can only retrieve from String a = wishlist_item.get(0) and cannot retrieve from String b = wishlist_item.get(1);
How can I retrieve?
Here is my data structure from my firebase database:
I can also tried to retrieve like this display.setText("Hi" + wishlist_item); and it worked but cannot retrieve from display.setText("Hi" + b);
error is :
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 at java.util.ArrayList.get(ArrayList.java:437)
You are trying to retrive data from index 1 while that index is not created yet. When you enter the for loop, the for loop is getting the first item from the snapshot and adding it to the wishlist_item arraylist. What you need to do is this:
List<String> wishlist_item = new ArrayList<String>();
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
wishlist_item.add(postSnapshot.getValue().toString());//got all wish list item from database
}
String a = wishlist_item.get(0);
String b = wishlist_item.get(1);
display.setText("Hi" + a);
This will work. Because you let your foreach loop to finish. This line:
wishlist_item.add(postSnapshot.getValue().toString());//got all wish list item from database
won't put all items from a snapshot, it will add one item at the time, the one that foreach loop is using right now. You first need to understand how for and foreach loops work: https://www.geeksforgeeks.org/for-each-loop-in-java/
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am using firebase database and want to show data in a listview.When I call onDataChange() of firebase database it shows nullpointer excetion. I find my best on google and many other sites but nothing helps me to get rid of this error, so please help me, I,m stuck on this error from last three hours...
Here is Mainactiviy named as Articles_from_firebase.java:
public class Articles_from_fireabse extends AppCompatActivity {
EditText editTextName;
Spinner spinnerGenre;
Button buttonAddArtist;
ListView listViewArtists;
DatabaseReference databaseArtists;
//a list to store all the artist from firebase database
List<Artist> artists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_articles_from_fireabse);
databaseArtists = FirebaseDatabase.getInstance().getReference("artists");
editTextName = (EditText) findViewById(R.id.editTextName);
spinnerGenre = (Spinner) findViewById(R.id.spinnerGenres);
listViewArtists = (ListView) findViewById(R.id.listViewArtists);
buttonAddArtist = (Button) findViewById(R.id.buttonAddArtist);
buttonAddArtist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//calling the method addArtist()
//the method is defined below
//this method is actually performing the write operation
addArtist();
}
});
}
private void addArtist() {
//getting the values to save
String name = editTextName.getText().toString().trim();
String genre = spinnerGenre.getSelectedItem().toString();
//checking if the value is provided
if (!TextUtils.isEmpty(name)) {
//getting a unique id using push().getKey() method
//it will create a unique id and we will use it as the Primary Key for our Artist
String id = databaseArtists.push().getKey();
//creating an Artist Object
Artist artist = new Artist(id, name, genre);
//Saving the Artist
databaseArtists.child(id).setValue(artist);
//setting edittext to blank again
editTextName.setText("");
//displaying a success toast
Toast.makeText(this, "Artist added", Toast.LENGTH_LONG).show();
} else {
//if the value is not given displaying a toast
Toast.makeText(this, "Please enter a name", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onStart() {
super.onStart();
//attaching value event listener
databaseArtists.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//clearing the previous artist list
artists.clear();
//iterating through all the nodes
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//getting artist
Artist artist = postSnapshot.getValue(Artist.class);
//adding artist to the list
artists.add(artist);
}
//creating adapter
ArtistList artistAdapter = new ArtistList(Articles_from_fireabse.this, artists);
//attaching adapter to the listview
listViewArtists.setAdapter(artistAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Here is my 2nd class ArtistList.java :
public class ArtistList extends ArrayAdapter<Artist> {
private Activity context;
List<Artist> artists;
public ArtistList(Activity context, List<Artist> artists) {
super(context, R.layout.list_layout, artists);
this.context = context;
this.artists = artists;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_layout, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
TextView textViewGenre = (TextView) listViewItem.findViewById(R.id.textViewGenre);
Artist artist = artists.get(position);
textViewName.setText(artist.getArtistName());
textViewGenre.setText(artist.getArtistGenre());
return listViewItem;
}
This is my Stacktrace:
java.lang.NullPointerException
at com.example.e_agriculture10.Articles_from_fireabse$2.onDataChange(Articles_from_fireabse.java:92)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.1.0:75)
This is the critical block of my code where error exists.
public void onDataChange(DataSnapshot dataSnapshot) {
//clearing the previous artist list
artists.clear();
//iterating through all the nodes
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//getting artist
Artist artist = postSnapshot.getValue(Artist.class);
//adding artist to the list
artists.add(artist);
}
//creating adapter
ArtistList artistAdapter = new ArtistList(Articles_from_fireabse.this, artists);
//attaching adapter to the listview
listViewArtists.setAdapter(artistAdapter);
}
According to my opinion in this line [artists.clear()], artists getting the null value. Why artists getting null value?
Easy Solution
Whenever you call artists.clear(); check to make sure it is not null.
if(artists != null)
artists.clear();
else
artists = new ArrayList<>();
Sustainable Solution
You should consider what the role of the artists object arry is. In this case, you have both a database and an array that both store information about artists. The database should store persistent data, that is data that lives after program execution. Whereas, your artists object is just around during runtime.
Therefore, you should have code at the start of your program that loads in data from the database into the artists object. Reference / edit / add to the artist object during runtime. Finally, have cleanup code at the end of runtime that updates the artist table in the database.
yes initialize List artists; inside onCreate(){}
Something like this
artists = new ArrayList<>();
I have been having some trouble for quite some time stuck on this. I am wanting to make a spinner in android studio and use a firebase database. But I can't seem to get the spinner to display any of the database's data in the spinner. I have tried to follow some similar questions but I just run into the same problems. Since I am new to Firebase I am unsure how to actually create the indexes to pull from it.
Here is my current code:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference fDatabaseRoot = database.getReference("locations");
fDatabaseRoot.child("buildings").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<String> buildings = new ArrayList<>();
for (DataSnapshot buildingSnapshot: dataSnapshot.getChildren()) {
String buildingName = buildingSnapshot.child("buildingName").getValue(String.class);
buildings.add(buildingName);
}
Spinner buildingSpinner = findViewById(R.id.spinner);
ArrayAdapter<String> buildingAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, buildings);
buildingAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
buildingSpinner.setAdapter(buildingAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});`
Here is how my database is setup: Firebase Spinner Database
Here is the FirebaseFirestore implementation for SnapshotListener.
You can check the type of change in data (ADDED, MODIFIED, REMOVED) by DocumentChange class. You can check out the example here: https://firebase.google.com/docs/firestore/query-data/listen#view_changes_between_snapshots
FirebaseFirestore db= FirebaseFirestore.getInstance();
db.collection("locations").document("buildings").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot snapshots,
#Nullable FirebaseFirestoreException e){
//your action here
}
);
Ok so using the Realtime Database I had to switch the Read and Write rules to true, completely forgot to do that.
Remember kids always do your homework. :)
Hi I am new to Android and Firebase. I am trying to loop through the TextViews and updating the values from the database.
I got a simple database and would like to display all the keys (eg 71001) on multiple textviews.
I got my views instantiated as below:
// Instantiate Views for Rolls:
mRoll1 = findViewById(R.id.rollno1);
mRoll2 = findViewById(R.id.rollno2);
mRoll3 = findViewById(R.id.rollno3);
mRoll4 = findViewById(R.id.rollno4);
mRoll5 = findViewById(R.id.rollno5);
mRoll6 = findViewById(R.id.rollno6);
mRoll7 = findViewById(R.id.rollno7);
mRoll8 = findViewById(R.id.rollno8);
This will only put the last number in the text view
// Read from the database
mRootReference.addListenerForSingleValueEvent (new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mRolll.setText(snapshot.getKey());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
//Failed to read value
}
});
Please help.
What it looks like right now is that you end up with just having 71008 in your first TextView because you loop through the keys but only ever access the first TextView.
If you know that you'll always have eight keys, in your case you can try adding them to your TextViews without the loop, something along the lines of:
// Read from the database
mRootReference.addListenerForSingleValueEvent (new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
Iterator<DataSnapshot> children = dataSnapshot.getChildren().iterator();
mRolll.setText(children.next().getKey());
mRoll2.setText(children.next().getKey());
mRoll3.setText(children.next().getKey());
mRoll4.setText(children.next().getKey());
mRoll5.setText(children.next().getKey());
mRoll6.setText(children.next().getKey());
mRoll7.setText(children.next().getKey());
mRoll8.setText(children.next().getKey());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
//Failed to read value
}
});
If you want to use a loop, I would recommend placing your TextViews in an Array or List and then looping through those with the children:
// Read from the database
mRootReference.addListenerForSingleValueEvent (new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
Iterator<DataSnapshot> children = dataSnapshot.getChildren().iterator();
TextView[] views = new TextView[] {
mRolll,
mRoll2,
mRoll3,
mRoll4,
mRoll5,
mRoll6,
mRoll7,
mRoll8,
}
for (int i = 0; i < views.length && children.hasNext(); i++) {
views[i].setText(children.next().getKey());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
//Failed to read value
}
});
(The Array could be created elsewhere, probably in the same place you instantiate your Views)
I am trying to retrieve a list of items from Firebase and after all the data is retrieved, I want to inflate the data in listView using an adaptor. Here is the code I am using:
vehicleReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
for (DataSnapshot data : dataSnapshot.getChildren()){
ServiceHistoryDataModel serviceHistoryData = data.getValue(ServiceHistoryDataModel.class);
serviceHistoryDataList.add(serviceHistoryData);
}
ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter (this,serviceHistoryDataList,getLayoutInflater());
listView.setAdapter(adapter);
}else
Toast.makeText(ServiceHistoryActivity.this, "No service history available !", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
(please refer the screenshot)
I am getting an error :-
"ServiceHistoryListAdpter() in ServiceHistoryListAdapter cannot be
applied:..."
For the line:
ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter (this,serviceHistoryDataList,getLayoutInflater());
Could you please let me know how can I solve this?
You want to access the instance of enclosing class from the anonymous class. The syntax for which is EnclosingClassName.this.
So change the line to:
ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter(YourActivityName.this,serviceHistoryDataList,getLayoutInflater());
i.e. add YourActivityName. before this.
Just pass parameter like "YourActivityName.this" your problem will be resolved.
Check out code below for the same.
ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter(YourActivityName.this,serviceHistoryDataList,getLayoutInflater());
Please replace
ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter(this,serviceHistoryDataList,getLayoutInflater());
with
ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter(YourActivityName.this,serviceHistoryDataList,getLayoutInflater());
Replace your code with this.
ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter(ActivityName.this,serviceHistoryDataList,getLayoutInflater());
ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter(YourActivityName.this,serviceHistoryDataList,getLayoutInflater());