ListView会填充,但每个视图最初都是空白的?

时间:2018-05-25 20:34:52

标签: android firebase firebase-realtime-database android-arrayadapter

我在片段中使用ListView,从Firebase存储中下载备注然后显示它们。但是,我遇到的问题是当它显示笔记时它只是一个空的笔记布局,但当我切换活动并返回时它们不再是空白,它们会被重新加载。我不知道到底哪里出错了,我已经尝试过调用onDataSetChange到Adapter Everywhere,也尝试了ListView上的invalidate()和invalidateViews(),希望它只是简单地刷新视图,但不幸的是,这也没有工作:/代码在下面,谢谢你提前任何帮助! :)

这是我在Notes片段中设置适配器的地方

mNoteStorage = FirebaseStorage.getInstance().getReference().child("Notes").child(currentUser.getUid());
    mNotesDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            my_notes.setAdapter(null);
            Iterable<DataSnapshot> all_keys = dataSnapshot.getChildren();
            filename_arrayList = new ArrayList<>();
            na = null;
            for (DataSnapshot each_key : all_keys) {
                String each = each_key.getKey();
                filename_arrayList.add(each);
            }
            for (String each_filename : filename_arrayList) {
                downloadFile(each_filename);
                Note each_note = Utilities.getNoteByName(getContext(), each_filename + Utilities.FileExtention);
                each_note_array.add(each_note);
            }

            if (each_note_array == null || each_note_array.size() == 0) {
                Toast.makeText(getActivity().getApplicationContext(), "No Notes!", Toast.LENGTH_LONG).show();
            } else {
                na = new MyNotesAdapter(getContext(), R.layout.item_note, each_note_array);
                my_notes.setAdapter(na);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

以及我的适配器

class MyNotesAdapter extends ArrayAdapter<Note> {

Context ctx;

public MyNotesAdapter(@NonNull Context context, int resource, ArrayList<Note> note) {
    super(context, resource, note);

    this.ctx = context;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    //return super.getView(position, convertView, parent);

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_note, null);
    }

    Note note = getItem(position);

    if(note != null) {
        TextView title = (TextView) convertView.findViewById(R.id.list_note_title);
        TextView content = (TextView) convertView.findViewById(R.id.list_note_content);
        TextView date = (TextView) convertView.findViewById(R.id.list_note_date);

        Typeface music_font = Typeface.createFromAsset(getContext().getAssets(), "fonts/melodymakernotesonly.ttf");
        Typeface scribble_card = Typeface.createFromAsset(getContext().getAssets(), "fonts/the unseen.ttf");

        if (getThemeCountInt() == 0) {
            title.setTypeface(music_font);
        } else if (getThemeCountInt() == 1) {
            title.setTypeface(scribble_card);
        }

        content.setTypeface(scribble_card);

        title.setText(note.getTitle());
        date.setText(note.getDateTimeFormatted(getContext()));

        if(note.getContent().length() > 25) {
            content.setText(note.getContent().substring(0,25) + "...");
        } else {
            content.setText(note.getContent());
        }

        if(note.getContent().length() <= 0) {
            content.setText("(Empty Note..)");
        } else {
            content.setText(note.getContent());
        }

        if (note.getTitle().length() <= 0) {
            title.setText("(Untitled)");
        } else {
            title.setText(note.getTitle());
        }
    }

    return convertView;
}

private int getThemeCountInt() {
    SharedPreferences mSharedPreferences = this.getContext().getSharedPreferences("theme", MODE_PRIVATE);
    int selectedTheme = mSharedPreferences.getInt("theme", 0);
    return selectedTheme;

}

}

downloadFile

private void downloadFile(final String filenames) {


    final String each_filename = filenames + Utilities.FileExtention;
    final long file_size = 1024 * 1024;
        mNoteStorage.child(each_filename).getBytes(file_size).addOnSuccessListener(new OnSuccessListener<byte[]>() {
            @Override
            public void onSuccess(byte[] bytes) {
                FileOutputStream stream;
                FileInputStream streamIn;
                    try {
                        File dir = getActivity().getApplication().getFilesDir();
                        File file = new File(dir, each_filename);

                        stream = new FileOutputStream(file);
                        stream.write(bytes);

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        });
}

Utilities.getNoteByName

public static Note getNoteByName(Context context, String filename) {
    File file = new File(context.getFilesDir(), filename);
    Note note;

    if (file.exists()) {
        FileInputStream fis;
        ObjectInputStream ois;

        try {
            fis = context.openFileInput(filename);
            ois = new ObjectInputStream(fis);

            note = (Note) ois.readObject();

            fis.close();
            ois.close();

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }

        return note;
    }

    return null;
}

1 个答案:

答案 0 :(得分:1)

创建MyNotesAdapter调用notifyDataSetChanged()方法后,让ListView实例知道基础数据已更改。

my_notes.setAdapter(na);
na.notifyDataSetChanged();

我个人更喜欢创建和设置适配器实例一次,然后使用其add()方法来操作其基础数据。完成后,我调用适配器notifyDataSetChanged()

每次数据库更改时重新创建新的适配器实例都可能会触发垃圾收集器更频繁地运行。