从Firebase实时数据库中获取值并将它们放入ArrayList中

时间:2018-05-21 15:13:19

标签: java android firebase firebase-realtime-database

在我的应用程序中,我正在尝试创建一个实时订阅源(例如Instagram订阅源或Facebook订阅源),其中包含包含图片,标题,用户用户名等的帖子,以及图片。我创建了一个片段,它拍摄照片,添加标题,并将其转换为Bitmap中的字符串。我可以成功将这些帖子(对象)发布到firebase数据库,但是从数据库中获取每个帖子的值并将它们添加到arraylist是不行的 CameraFragment(为每个帖子的数据库添加帖子值)

 package com.example.a10012032.dreamapplicationv2.Main;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.a10012032.dreamapplicationv2.R;
import com.example.a10012032.dreamapplicationv2.UserAuth.Login;
import com.example.a10012032.dreamapplicationv2.UserAuth.Profile;
import com.example.a10012032.dreamapplicationv2.UserAuth.signUp;
import com.google.firebase.auth.FirebaseAuth;
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.io.ByteArrayOutputStream;

import static android.app.Activity.RESULT_OK;


public class cameraFragment extends Fragment {
    private static final String Tab = "cameraFragment";
    private static final int CAMERA_REQUEST_CODE = 102;

    private Button take;
    private ImageView holder;
    private EditText editText;
    private TextView caption;
    private Button post;
    Bitmap bitmap;
    FirebaseAuth mAuth;
    DatabaseReference mDatabaseRef;
    DatabaseReference mUserData;
    String keyUser;
    String UsernameStr;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.camera_fragment, container, false);
        keyUser = signUp.USER_KEY;
        UsernameStr= Login.usernameValue;
        bitmap = null;
        mAuth = FirebaseAuth.getInstance();
        mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("Posts");
        mUserData = FirebaseDatabase.getInstance().getReference().child("Users").child(keyUser);
        take = view.findViewById(R.id.btnCapture);
        post = view.findViewById(R.id.post);
        holder = view.findViewById(R.id.imageView2);
        editText = view.findViewById(R.id.editText2);
        editText.setVisibility(View.INVISIBLE);
        caption = view.findViewById(R.id.cap);
        caption.setVisibility(View.INVISIBLE);
        post.setVisibility(View.INVISIBLE);


        take.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                takePictureFromCamera();
            }
        });
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String caption = editText.getText().toString();
                DatabaseReference mChildDatabase = mDatabaseRef.child("Posts").push();
                mChildDatabase.child("imageString").setValue(bitmapToString(bitmap)); //converts bitmap to string
                mChildDatabase.child("likeCount").setValue(0);
                Log.d("TAGUSERNAME", UsernameStr+" is null");
                mChildDatabase.child("Username").setValue(UsernameStr);
                mChildDatabase.child("Message").setValue(caption);
                holder.setImageResource(0);
                editText.setVisibility(View.INVISIBLE);
                post.setVisibility(View.INVISIBLE);
            }
        });


        return view;
    }
    public void takePictureFromCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, CAMERA_REQUEST_CODE);
    }
    public String bitmapToString(Bitmap bm){
        ByteArrayOutputStream bYtE = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, bYtE);
        bm.recycle();
        byte[] byteArray = bYtE.toByteArray();
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
            bitmap = (Bitmap) data.getExtras().get("data");
            holder.setImageBitmap(bitmap);
            editText.setVisibility(View.VISIBLE);
            caption.setVisibility(View.VISIBLE);
            post.setVisibility(View.VISIBLE);
            editText.setText("");
        }
    }
}

FeedFragment(尝试获取每个帖子并将其添加到ListView CustomAdapter)

package com.example.a10012032.dreamapplicationv2.Main;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.a10012032.dreamapplicationv2.UserAuth.Login;
import com.example.a10012032.dreamapplicationv2.UserAuth.Profile;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.example.a10012032.dreamapplicationv2.R;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class feedFragment extends Fragment {
    private static final String Tab = "feedFragment";
    ListView list;
    DatabaseReference mDatabaseRef, mUserCheckData, mGodPlease;
    ArrayList<Post> array;
    CustomAdapter customAdapter;



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.feed_fragment,container,false);
        mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("Posts").child("Posts");
        array=new ArrayList<>();
        Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.prof);
        array.add(new Post(bitmapToString(bm),"Caption","Username"));
        mDatabaseRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()){
                    mUserCheckData=mDatabaseRef.child(ds.getKey());
                    array.add(new Post(mUserCheckData.child("imageString").toString(),mUserCheckData.child("Message").toString(),mUserCheckData.child("Username").toString()));
                    Log.d("TAGPLS",mUserCheckData.child("Username").toString());
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        customAdapter=new CustomAdapter(getActivity(),R.layout.item,array);
        list = view.findViewById(R.id.id_listView);
        list.setAdapter(customAdapter);
        customAdapter.notifyDataSetChanged();
        return view;
    }
   /* public ArrayList<Post> retrieve(){
        mDatabaseRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                fetchData(dataSnapshot);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                fetchData(dataSnapshot);
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        return array;
    }
    private void fetchData(DataSnapshot dataSnapshot)
    {
        array.clear();
        for (DataSnapshot ds : dataSnapshot.getChildren())
        {
            Post newPost=ds.getValue(Post.class);
            array.add(newPost);
        }
    }
*/
    public class CustomAdapter extends ArrayAdapter<Post> {
        Context context;
        List<Post> list;

        public CustomAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<Post> objects) {
            super(context, resource, objects);
            this.context=context;
            list=objects;
        }

        @NonNull
        @Override
        public View getView(int i, @Nullable View convertView, @NonNull ViewGroup parent) {
            LayoutInflater layoutInflater=(LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            View adapterView = layoutInflater.inflate(R.layout.item,null);

            TextView userN = adapterView.findViewById(R.id.profMainTxt);
            ImageView postI = adapterView.findViewById(R.id.imagePost);
            TextView capt = adapterView.findViewById(R.id.captionTxt);
            Log.d("TAGHI",array.get(i).getUsername()+" is null");
            userN.setText(array.get(i).getUsername());
            postI.setImageBitmap(stringToBitMap(array.get(i).getBitmapString()));
            capt.setText(array.get(i).getCaption());
            notifyDataSetChanged();
            return adapterView;

        }
    }
    public Bitmap stringToBitMap(String encodedString){
        try {
            byte [] encodeByte= Base64.decode(encodedString,Base64.DEFAULT);
            return BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        } catch(Exception e) {
            e.getMessage();
            return null;
        }
    }
    public String bitmapToString(Bitmap bm){
        ByteArrayOutputStream bYtE = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, bYtE);
        bm.recycle();
        byte[] byteArray = bYtE.toByteArray();
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }

}

所有已注释的部分都是尝试修复我的错误

最后,我的firebase目录  enter image description here

1 个答案:

答案 0 :(得分:0)

要解决此问题,只需移动以下代码行:

public void onDataChange(DataSnapshot dataSnapshot) {
    for(DataSnapshot ds : dataSnapshot.getChildren()){
        mUserCheckData=mDatabaseRef.child(ds.getKey());
        array.add(new Post(mUserCheckData.child("imageString").toString(),mUserCheckData.child("Message").toString(),mUserCheckData.child("Username").toString()));
        Log.d("TAGPLS",mUserCheckData.child("imageString").toString());
    }
    customAdapter=new CustomAdapter(getActivity(),R.layout.item,array);
    list = view.findViewById(R.id.id_listView);
    list.setAdapter(customAdapter);
    customAdapter.notifyDataSetChanged();
}
在for循环结束后,

onDataChange()方法内。

有关详细信息,请参阅 this post

中的回答

修改:根据您编辑的帖子,请使用以下代码:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postsRef = rootRef.child("Posts").child("Posts");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String message = ds.child("Message").getValue(String.class);
            Log.d("TAG", message);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
postsRef.addListenerForSingleValueEvent(valueEventListener);

它将打印所有消息。