Android Java ListView从Firebase数据库检索列表,但显示空的TextViews和图像

时间:2018-09-30 16:24:04

标签: java android json firebase firebase-realtime-database

我遇到一个问题,可以从Firebase实时数据库创建列表视图项,但是其内容为空视图,所有文本视图和图像都没有数据,我开始在Firebase中学习,所有这些我都遵循了本教程: https://www.youtube.com/watch?v=jEmq1B1gveM&list=PLk7v1Z2rk4hj6SDHf_YybDeVhUT9MXaj1&index=2

我确实很喜欢,但是视频教程显示了一个工作列表,而我的列表是空视图,这是我的代码:

相册。

{this.initialize(data.saturday)}

AlbumsListAdapter.Java

package com.emadzedan.michealjacksonnoads.michealjacksonnoads;

public class Album{
private String thumbAndID;
private String albumName;
private String numberOfSongs;
private String albumYear;

public Album() {
}

public Album(String thumbAndID, String albumName, String numberOfSongs, String albumYear) {
    this.thumbAndID = thumbAndID;
    this.albumName = albumName;
    this.numberOfSongs = numberOfSongs;
    this.albumYear = albumYear;
}

public String getThumbAndID() {
    return thumbAndID;
}

public void setThumbAndID(String thumbAndID) {
    this.thumbAndID = thumbAndID;
}

public String getAlbumName() {
    return albumName;
}

public void setAlbumName(String albumName) {
    this.albumName = albumName;
}

public String getNumberOfSongs() {
    return numberOfSongs;
}

public void setNumberOfSongs(String numberOfSongs) {
    this.numberOfSongs = numberOfSongs;
}

public String getAlbumYear() {
    return albumYear;
}

public void setAlbumYear(String albumYear) {
    this.albumYear = albumYear;
}
}

AlbumsContainerFragment.Java

package com.emadzedan.michealjacksonnoads.michealjacksonnoads;

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.List;

public class AlbumsListAdapter extends ArrayAdapter<Album> {
    private Context context;
    private List<Album> albums;

ImageView albumThumb;
TextView albumName;
TextView numberOfSongsText;
TextView numberOfSongs;
TextView albumYear;
TextView hiddenThumbORID;

public AlbumsListAdapter(Context context, List<Album> albums) {
    super(context, R.layout.albums_list_row, albums);
    this.context = context;
    this.albums = albums;
}

@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater =  LayoutInflater.from(context);
    View view = inflater.inflate(R.layout.albums_list_row, null, true);

    Album album = albums.get(position);

    //the new code it is not nessacery to cast fields
    albumThumb = view.findViewById(R.id.albumThumb);
    albumName = view.findViewById(R.id.albumName);
    numberOfSongsText = view.findViewById(R.id.numberOfSongsText);
    numberOfSongs = view.findViewById(R.id.numberOfSongs);
    albumYear = view.findViewById(R.id.albumYear);
    hiddenThumbORID = view.findViewById(R.id.hiddenThumbORID);

    Picasso.with(context).load("http://emadzedan.com/musiclibraryandroid_karaokebeta7/bandsimages/" + album.getThumbAndID() + ".png").into(albumThumb);
    albumName.setText(album.getAlbumName());
    numberOfSongs.setText(album.getNumberOfSongs());
    albumYear.setText(album.getAlbumYear());
    hiddenThumbORID.setText(album.getThumbAndID());


    if (position % 2 == 1) {
        //Second
        view.setBackgroundResource(R.color.colorPrimaryDark2);
        albumThumb.setBackgroundResource(R.color.colorPrimaryDark);
        albumYear.setTextColor(context.getResources().getColor(R.color.colorAccent));
        albumName.setTextColor(context.getResources().getColor(R.color.colorAccent));
        numberOfSongsText.setTextColor(context.getResources().getColor(R.color.colorPrimary));
        numberOfSongs.setTextColor(context.getResources().getColor(R.color.colorPrimary));

    } else {
        //First
        view.setBackgroundResource(R.color.colorPrimaryDark);
        albumThumb.setBackgroundResource(R.color.colorPrimaryDark2);
        albumYear.setTextColor(context.getResources().getColor(R.color.colorAccent));
        albumName.setTextColor(context.getResources().getColor(R.color.colorAccent));
        numberOfSongsText.setTextColor(context.getResources().getColor(R.color.colorPrimary));
        numberOfSongs.setTextColor(context.getResources().getColor(R.color.colorPrimary));
    }

    return view;
}


}

示例JSON:         {         “专辑”:{

package com.emadzedan.michealjacksonnoads.michealjacksonnoads;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.NonNull;

import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;

import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;

import java.util.List;
import java.util.Random;

import static android.content.Context.MODE_PRIVATE;

public class AlbumsContainerFragment extends Fragment {
SharedPreferences prefs;

ImageView bandImageImageView;

SongsListFragment songsListFragment;

FirebaseDatabase firebaseDatabase;
DatabaseReference rootReference;

List<Album> albums;
ListView albumsListView;
AlbumsListAdapter adapter;

public AlbumsContainerFragment() {

}


@Override
public View onCreateView(@NonNull LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {

    final View view = inflater.inflate(R.layout.fragment_albums_container, container, false);


    final float scale = getContext().getResources().getDisplayMetrics().density;
    int pixels = (int) (200 * scale + 0.5f);


    prefs = getContext().getSharedPreferences("SelectedItemsPref", MODE_PRIVATE);

    SharedPreferences.Editor editor = getContext().getSharedPreferences("SelectedItemsPref", MODE_PRIVATE).edit();

    int minNumberOfCovers = 1;
    int maxNumberOfCovers = 10;

    Random r = new Random();
    int coverNumberSelected = r.nextInt(maxNumberOfCovers - minNumberOfCovers + 1) + minNumberOfCovers;

    editor.putString("image", prefs.getString("bandname" + coverNumberSelected, "michaeljackson" + coverNumberSelected) + ".jpg");
    editor.putString("id", prefs.getString("bandname", "michaeljackson"));
    editor.apply();

    assert ((AppCompatActivity) getActivity()) != null;
    ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    bandImageImageView = (ImageView) view.findViewById(R.id.bandImageImageView);
    Picasso.with(getContext()).load("http://emadzedan.com/musiclibraryandroid_karaokebeta7/bandsimages/" + prefs.getString("image", "michaeljackson1.jpg")).into(bandImageImageView);

    firebaseDatabase = FirebaseDatabase.getInstance("");
    rootReference = firebaseDatabase.getReference("album");
    albumsListView = view.findViewById(R.id.albumsListView);
    albums = new ArrayList<Album>();

    songsListFragment = new SongsListFragment();

    //This is only because listview is inside scrollview
    int NumberOfAlbums = 29;
    int RowHeight = 106;
    albumsListView.getLayoutParams().height = Math.round(NumberOfAlbums * convertDpToPixel(RowHeight, getContext()));
    albumsListView.setFocusable(false);
    //===================================================

    return view;
}

public static float convertDpToPixel(float dp, Context context) {
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    return px;
}

public static float convertPixelsToDp(float px, Context context) {
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = px / ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    return dp;
}

@Override
public void onStart() {
    super.onStart();

    //Fire base List===================================================
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot albumSnapshot : dataSnapshot.getChildren()) {
                Album album = albumSnapshot.getValue(Album.class);
                albums.add(album);
            }

            adapter = new AlbumsListAdapter(getContext(), albums);
            albumsListView.setAdapter(adapter);

            albumsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    SharedPreferences.Editor editor = getContext().getSharedPreferences("SelectedItemsPref", MODE_PRIVATE).edit();
                    //editor.putString("albumThumb", rootReference.child("album").child("" + position ).toString());
                    //editor.putString("albumName",rootReference.child("album").child("" + position ).orderByChild("name").toString());
                    editor.apply();

                    DrawerBaseActivity.backButtonTextView.setVisibility(View.VISIBLE);
                    DrawerBaseActivity.CurrentFragment = "SongsList";
                    //DrawerBaseActivity.titleTextView.setText(rootReference.child("album").child("" + position ).orderByChild("name").toString());
                    getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.FragmentContainer, songsListFragment).addToBackStack("SongsList").commit();
                }
            });
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    };

    rootReference.addValueEventListener(valueEventListener);
    //Query query = rootReference.orderByChild("id").equalTo("1");
    //query.addValueEventListener(valueEventListener);
    //End Of Fire base 
List===================================================
}
}

我检查了ID,通常不会复制和粘贴,因此不会出现拼写错误,并且应用程序不会崩溃或仅在列表视图中显示空视图时显示错误,请帮助我,我已经工作2天了,没有结果正常!!!

2 个答案:

答案 0 :(得分:0)

代码中的问题在于Album类中字段的名称与数据库中属性的名称不同。您在Album类中有一个名为thumbAndID的字段,但是在数据库中我将​​其视为id,这是不正确的。名称必须匹配。有两种方法可以解决此问题。

第一个是删除当前数据,然后使用正确的名称再次添加。因此,您的字段ID也应该在数据库中具有相同的名称thumbAndID。仅当您处于测试阶段时,此解决方案才有效。

第二种方法(在我看来是一种更优雅的方法)是使用annotations。因为我看到您正在使用私有字段和公共获取程序,所以应该仅在获取程序之前使用PropertyName批注。因此,您的Album类应如下所示:

public class Album{
    private String thumbAndID;
    private String albumName;
    private String numberOfSongs;
    private String albumYear;

    public Album() {}

    public Album(String thumbAndID, String albumName, String numberOfSongs, String albumYear) {
        this.thumbAndID = thumbAndID;
        this.albumName = albumName;
        this.numberOfSongs = numberOfSongs;
        this.albumYear = albumYear;
    }

    @PropertyName("id")
    public String getThumbAndID() {
        return thumbAndID;
    }

    public void setThumbAndID(String thumbAndID) {
        this.thumbAndID = thumbAndID;
    }

    @PropertyName("name")
    public String getAlbumName() {
        return albumName;
    }

    public void setAlbumName(String albumName) {
        this.albumName = albumName;
    }

    @PropertyName("numberofsongs")
    public String getNumberOfSongs() {
        return numberOfSongs;
    }

    public void setNumberOfSongs(String numberOfSongs) {
        this.numberOfSongs = numberOfSongs;
    }

    @PropertyName("year")
    public String getAlbumYear() {
        return albumYear;
    }

    public void setAlbumYear(String albumYear) {
        this.albumYear = albumYear;
    }
}

如果您打算使用此解决方案,则无需在数据库中进行其他任何更改。

答案 1 :(得分:-1)

您的构造函数参数名称应与Firebase数据库密钥匹配。像这样修改Album类的构造函数。

public Album(String id, String name, String numberofsongs, String year) {
    this.thumbAndID = id;
    this.albumName = name;
    this.numberOfSongs = numberofsongs;
    this.albumYear = year;
}