-2

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?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

0

yes initialize List artists; inside onCreate(){}

Something like this artists = new ArrayList<>();

0

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.

KyleAure
  • 465
  • 4
  • 15
  • Please please can you edit my block of code so that I can implement your sincere suggestions – Javed Abrar Sep 30 '19 at 22:37
  • While my **Sustainable Solution** could be implemented in an small project. The **Golden Solution** would be to use Java Persistence API (JPA) in your project (OpenJPA is a good lightweight implementation of JPA). You should read more about JPA and how to use it to persist objects in a database here: https://www.javaworld.com/article/3379043/what-is-jpa-introduction-to-the-java-persistence-api.html – KyleAure Sep 30 '19 at 22:47