当前位置: 首页 > 知识库问答 >
问题:

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

巫马庆
2023-03-14

在我的应用程序中,我试图创建一个实时提要(如Instagram提要或Facebook提要),其中包含包含图像、标题、用户用户名等图像计数的帖子。我创建了一个片段,用于拍摄图片、添加标题并将其从位图转换为字符串。我可以成功地将这些帖子(对象)发布到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("");
        }
    }
}

(尝试获取每个帖子并将其添加到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);
    }

}

所有被注释掉的部分都是试图修正我的错误

共有1个答案

汪晨
2023-03-14

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

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()方法内部。

有关更多信息,请参阅我在这篇文章中的回答。

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

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);

它将打印所有消息。

 类似资料:
  • 我真的很难从数据库中收集数据。我正在使用实时数据库,我正在将这些值添加到一个可以单击的列表中。 当我单击列表上的用户时,我需要获取用户名值来创建聊天ID。这是我的问题,以获得键内的值。我现在的做法似乎行不通。 这是我的数据库 我需要取给“name”的值。 这是我的密码

  • 我试过这个: 首先,我获得了数据库中所有数据的引用,我正在尝试获取它,但我不知道如何实现这一点。 此外,当我这样做时,它会抛出以下错误: java.lang.NullPoInterException:尝试在.laramira.atellez.moroninfo.models.newsviewholder$1$1.ondatachange(newsviewholder.java:48)在com.go

  • 问题内容: 作为标题,如何从Firebase获取数据并在android studio中显示?当前,由于我不知道如何使用微调器,因此我将id首先放在XML文件中作为EditText。有人知道如何从Firebase获取数据并修改Java文件吗?例如,我想显示微调器中所有(1111,2222,3333 ....)的所有registerEventName(Google)。我在下面添加了附件。感谢您的推进,

  • 我是编程新手,我开始使用Ionic框架构建应用程序作为体验。我目前正在学习构建一个基本的社交媒体应用程序,匿名用户可以在该平台上发帖。 我现在处于用户可以评论帖子的阶段。但是,我很难在视图上显示每个帖子的实时评论数。 我计算评论的方法是从Firebase获取帖子数据,计算评论数量,然后显示给视图。 我尝试过使用间隔来每隔x秒获取post数据,以刷新post数据。这有点可行,但问题是离子内容(视图)

  • 有人能帮我做这个吗?

  • 我想从Firebase实时数据库中获取整个JSON数组。从实时数据库中提取数组并将其存储在自定义类的ArrayList中。