База данных Firebase не отображает данные в ListView, но записывает в Firebase - PullRequest
0 голосов
/ 16 февраля 2019

Я получаю сообщение об ошибке:

12378-12378 / info.androidhive.firebase W / ClassMapper: не найдено установщика / поля для artistName в классе info.androidhive.firebase.Artist2

Данные записываются в базу данных Firebase, но не отображаются в ListView.

Пожалуйста, смотрите мой код ниже:

import android.widget.TextView;

import java.util.List;

public class ArtistList2 extends ArrayAdapter<Artist2> {

private Activity context; //context activity
private List<Artist2> artistList2; //list will store all the artists


//constructor parsing context and artist list
public ArtistList2(Activity context, List<Artist2> artistList2) {
    super(context, R.layout.list_layout2, artistList2); //passing context, layout file and the artist list
    this.context = context; //initialising variables
    this.artistList2 = artistList2;

}

@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) { //over ride get view method
    LayoutInflater inflater = context.getLayoutInflater(); //layout inflator object

    View listViewItem = inflater.inflate(R.layout.list_layout2,null,true); //creating list view object to inflate the xml list layout

    TextView textViewName2 = (TextView) listViewItem.findViewById(R.id.textViewName2); //create text view for the name
    TextView textViewGenre2 = (TextView) listViewItem.findViewById(R.id.textViewGenre2); //create text view for the genres

    Artist2 artist2 = artistList2.get(position);
    //Artist artist2 = artistList2.get(position); //gets the artists particular position

    textViewName2.setText(artist2.getArtistName2()); //set name value to the corresponding text view
    textViewGenre2.setText(artist2.getArtistGenre2()); //set genre value to the corresponding text view

    return listViewItem;

}

}

пакет info.androidhive.firebase;

открытый класс Artist2 {

String artistId2;
String artistName2;
String artistGenre2;


public Artist2(){}

public Artist2(String artistId2, String artistName2, String artistGenre2) {
    this.artistId2 = artistId2;
    this.artistName2 = artistName2;
    this.artistGenre2 = artistGenre2;
}

public String getArtistId2() {
    return artistId2;
}

public String getArtistName2() {
    return artistName2;
}

public String getArtistGenre2() {
    return artistGenre2;
}

}

открытый класс WishListActivity расширяет AppCompatActivity {

//Declarations of variables
EditText editTextName2;
Button buttonAdd2;
Spinner spinnerGenres2;

//Database reference object
DatabaseReference databaseArtists2;

//Declaration of list view for the adapter
ListView listViewArtists2; //retrieves this from the xml
List<Artist2> artistList2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wish_list2);


    //gets the database reference object and passes artists - the parameter
    databaseArtists2 = FirebaseDatabase.getInstance().getReference("artists2");
    //Declarations of textviews, buttons and spinners
    editTextName2 = (EditText) findViewById(R.id.editTextName2);
    buttonAdd2 = (Button) findViewById(R.id.buttonAddArtist2);
    spinnerGenres2 = (Spinner) findViewById(R.id.spinnerGenres2);

    listViewArtists2 = (ListView) findViewById(R.id.listViewArtists2);

    artistList2 = new ArrayList<>();
    //onclick listener to the button - calls the method add artist
    buttonAdd2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view){
            addArtist2();

        }});

}


@Override
protected void onStart() { //overriding on start method
    super.onStart();


    databaseArtists2.addValueEventListener(new ValueEventListener() { //database  reference object attached to the value event listener, passing a new value event listener
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) { //when anything changed in the db
            artistList2.clear(); //clears artist list
            for(DataSnapshot artistSnapshot : dataSnapshot.getChildren()) { //everything that is contained within db reference object will be displayed in the snapshot
               // Artist artist2 = artistSnapshot.getValue(Artist2.class); //gets all values of the artist class for the snapshot
                Artist2 artist2 = artistSnapshot.getValue(Artist2.class);
                //artistList2.add(artist2);
                artistList2.add(artist2);


            }

           // ArtistList2 adapter2 = new ArtistList(WishListActivity.this, artistList2);
            ArtistList2 adapter2 = new ArtistList2(WishListActivity.this, artistList2);
            listViewArtists2.setAdapter(adapter2); //this method is executed when new information is added to the database
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) { //when anything removed in the db

        }
    });

}
//Add artist method
private void addArtist2() {
    String name = editTextName2.getText().toString().trim();
    String genre = spinnerGenres2.getSelectedItem().toString();
    //checks to see if the name field is left empty
    if(!TextUtils.isEmpty(name)) { //if name field isnt empty, the information will be stored in firebase

        //using the post method to store values within
        String id = databaseArtists2.push().getKey();

        //Create new artist
        Artist artist2 = new Artist(id,name,genre);

        //Use set value method to store the artist within the unique generated id value
        databaseArtists2.child(id).setValue(artist2);

        //Prompts the user that the information has been added
        Toast.makeText(this, "Book added to Wishlist", Toast.LENGTH_LONG).show();

    }else{ //if the name field is empty, the user will be prompted to enter in a name
        Toast.makeText(this, "Enter Book Info",Toast.LENGTH_LONG).show();
    }


}}

1 Ответ

0 голосов
/ 17 февраля 2019

Вы получаете следующую ошибку:

W / ClassMapper: не найден установщик / поле для artistName в классе info.androidhive.firebase.Artist2

, посколькуFirebase SDK при десериализации просматривает вашу базу данных после поля с именем artistName, которое действительно не существует, поскольку в вашем классе модели все ваши поля заканчиваются на 2 (см. Последний символ?).Чтобы решить эту проблему, либо измените имя полей в классе модели, чтобы оно совпадало с именем в базе данных, либо удалите фактические данные с сервера и добавьте новые в соответствии с полями, существующими в вашем классе.Вы также можете использовать аннотацию перед вашим геттером так:

@PropertyName("artistName")
public String getArtistName2() { return artistName2; }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...