如何在Firebase的ValueEventListener()中的onDataChange()方法中添加ArrayList?

时间:2016-12-18 16:13:04

标签: android firebase firebase-realtime-database

对于Android + Firebase,我是新手,我不太了解异步侦听器。有没有办法在onDataChange()方法中添加到ArrayList?

我正在使用它来填充我的ListView。我知道并且我已经尝试过FirebaseUI的ListViewAdapter和RecyclerViewAdapter,但我希望有一个customAdapter,因为我可以控制它比FirebaseUI的适配器更好。

以下是我的MainActivity代码:

package com.example.chiz.list_view_adapter;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
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 java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference mRecipeRef = mRootRef.child("recipes");

    ArrayList<String> titles = new ArrayList<String>();
    ArrayList<String> urls = new ArrayList<String>();
    ArrayList<String> images = new ArrayList<String>();

    ListView listView;
    List<Recipes> rowItems;

    private static final String TAG = "Chiz";

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

        listView = (ListView) findViewById(R.id.recipe_list);

        this.getData();

        rowItems = new ArrayList<Recipes>();
        for (int i = 0; i < titles.size(); i++) {
            Recipes item = new Recipes(titles.get(i), urls.get(i), images.get(i));
            rowItems.add(item);
        }

        RecipeListAdapter adapter = new RecipeListAdapter(this, rowItems);
        listView.setAdapter(adapter);
    }

    public void getData(){
        mRecipeRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                    String recipeKey = postSnapshot.getKey();
                    String title = postSnapshot.child("title").getValue(String.class);
                    String url = postSnapshot.child("url").getValue(String.class);
                    String image_url = postSnapshot.child("image_url").getValue(String.class);

                    //I want something like this:
                    //titles.add(title);
                    //urls.add(url);
                    //images.add(image_url); 

                    Log.d(TAG, "recipeKey: "+recipeKey);
                    Log.d(TAG, "title: "+title);
                    Log.d(TAG, "url: "+url);
                    Log.d(TAG, "image_url: "+image_url);
                    Log.d(TAG, "-----");
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Post failed, log a message
                Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
                // ...
            }
        });
    }
}

食谱:

package com.example.chiz.list_view_adapter;

public class Recipes {
    private String title;
    private String url;
    private String image_url;

    public Recipes() {
    }

    public Recipes(String title, String url, String image_url){
        super();
        this.title = title;
        this.url = url;
        this.image_url = image_url;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        title = title;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        url = url;
    }

    public String getImage_url() {
        return image_url;
    }

    public void setImage(String image_url) {
        image_url = image_url;
    }
}

RecipeListAdapter:

package com.example.chiz.list_view_adapter;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.List;

public class RecipeListAdapter extends BaseAdapter {
    Context context;
    List<Recipes> rowItems;

    public RecipeListAdapter ( Context context, List<Recipes> items ) {
        this.context = context;
        this.rowItems = items;
    }

    private class ViewHolder {
        ImageView imageView;
        TextView txtTitle;
        TextView txtUrl;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;

        LayoutInflater mInflater = (LayoutInflater)
                context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.custom_list, null);
            holder = new ViewHolder();
            holder.txtUrl = (TextView) convertView.findViewById(R.id.Text2);
            holder.txtTitle = (TextView) convertView.findViewById(R.id.Text1);
            holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }

        Recipes rowItem = (Recipes) getItem(position);

        holder.txtUrl.setText(rowItem.getUrl());
        holder.txtTitle.setText(rowItem.getTitle());
        Picasso.with(context).load(rowItem.getImage_url()).error(R.drawable.placeholder_error).into(holder.imageView);

        return convertView;
    }

    @Override
    public int getCount() {
        return rowItems.size();
    }

    @Override
    public Object getItem(int position) {
        return rowItems.get(position);
    }

    @Override
    public long getItemId(int position) {
        return rowItems.indexOf(getItem(position));
    }

}

1 个答案:

答案 0 :(得分:0)

试试这个。我使用了ListenerForSingleValueEvent来避免冗余。

    mRecipeRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                 Recipes recipe = postSnapshot.getValue(Recipes.class); 
                 titles.add(recipe.getTitle());
                 urls.add(recipe.getUrl());
                 images.add(recipe.getImage_url); 
             }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });