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



我有一个问题,我可以从Firebase实时数据库创建列表视图项目,但它的内容是空视图,所有文本视图和图像都没有数据,我正在Firebase中开始我的方式,并且对所有这些我都这样做了,我确实遵循了本教程: https://www.youtube.com/watch?v=jEmq1B1gveM&list=PLk7v1Z2rk4hj6SDHf_YybDeVhUT9MXaj1&index=2

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

专辑.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;
}
}

AlbumsListAdapter.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;
}

}

AlbumsContainerFragment.Java

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===================================================
}
}

示例 JSON:{ "专辑":{

"1": {
"id":"1",
"year": "1969 (The Jackson 5)",
"name": "Diana Ross Presents The Jackson 5",
"numberofsongs": "12"
},
"2": {
"id":"2",
"year": "1970 (The Jackson 5)",
"name": "ABC",
"numberofsongs": "12"
}
}
}

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

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

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

第二种方法,在我看来是更优雅的方法,是使用annotations.因为我看到您正在使用私有字段和公共 getter,所以您应该仅在 getter 前面使用 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;
}
}

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

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

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

最新更新