【问题标题】:Unable to get the image to display in recyclerview from nested realtime database无法从嵌套的实时数据库中获取要在 recyclerview 中显示的图像
【发布时间】:2019-04-12 03:23:26
【问题描述】:

这是我的 firebase 实时数据库表。我确实有一个图像存储在 Firebase 存储中。我打算在此表中的字符列下使用多个字符。

Realtime Database

我不明白为什么我无法从实时数据库中获取 photo_id。链接 (photo_id) 是 "https://firebasestorage.googleapis.com/v0/b/occreations-b6c14.appspot.com/o?name=characterimage%2FWk80hB04oZRMQxK9Ig0DDgoL5n52%20be58f895-8fda-4dd1-9e15-32e4186eae8a&uploadType=resumable&upload_id=AEnB2UrkBecZTlE4kpNypl-1ACjekw1CIM3UsUxXgRGXHLB4DCmyLDI-i70OxqjwKchf7sf3YURhgCFq3KxV7JUPDy55GyZWSg&upload_protocol=resumable" 当我单击此链接时,它显示 “无效请求。缺少 X-Goog-Upload-Command 标头。”

但是当我使用从 URL 到数组列表的链接测试我的代码时,它可以工作。但是为什么我无法从我的数据库中获取图像呢?

我似乎找不到问题所在。我在想它可能是 arraylist、photo_id url 或我上传到 firebase 存储/实时数据库的方式,可能是因为我无法将文件名作为 .png 或 .jpeg 并将其存储为 photo_id?

更新:我将 url 链接更改为从 Firebase Storage 下载 url,但我无法从 DatabaseReference 中检索链接,这导致列表中没有添加任何内容

我一直在学习这个教程。Coding-In-Flow Tutorial

UPDATE2:我遇到了嵌套数据问题。我只想从实时数据库中获取 photo_id 值(即 url),但我将它作为空值获取。更改回收站视图后,占位符图像为空。除非有办法,否则我应该如何仅将我的数据从角色子项检索到 character_id(已经无法检索)。我一直在搜索 stackoverflow 上的其他答案,但没有一个与我正在寻找的答案相匹配。

我的原木猫说

W/ClassMapper: No setter/field for -LQq7dIvsJX7GgNfXeIf found on class com.example.linda.originalcharacterapp.model.CharacterInformation
           No setter/field for -LQq7SB5qvcNXdJEzwBh found on class 
           com.example.linda.originalcharacterapp.model.CharacterInformation
           D/TAG: null / null
           W/ClassMapper: No setter/field for username found on class 
           com.example.linda.originalcharacterapp.model.CharacterInformation
           No setter/field for email found on class 
           com.example.linda.originalcharacterapp.model.CharacterInformation
           No setter/field for password found on class 
           com.example.linda.originalcharacterapp.model.CharacterInformation
           D/TAG: null / null

Updated Android Screenshot

Android Screenshot

Current Image sitting in Firebase Storage

HomeFragment.class

    mRecyclerView.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager (this.getActivity());
    mRecyclerView.setLayoutManager(new GridLayoutManager (this.getActivity(),2));
    userOCs = new ArrayList<> ();

    //DatabaseReference characterReference = FirebaseDatabase.getInstance().getReference();

     reference.child(userid).orderByChild("characters").getRef().addValueEventListener (new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Display images of ocs
            for(DataSnapshot characterSnapshot : dataSnapshot.getChildren()){
                if (dataSnapshot.exists()) {
                    String photoid = dataSnapshot.child ("photo_id").getValue (String.class);
                    String cName = dataSnapshot.child ("characterName").getValue (String.class);
                    CharacterInformation oc = characterSnapshot.getValue (CharacterInformation.class);
                    Log.d ("TAG", photoid + " / " + cName);
                    userOCs.add (oc);
                    Toast.makeText (getActivity (), "Adding images " + oc.getCharacterName (), Toast.LENGTH_SHORT).show ();
                }
           }
           String file = "https://firebasestorage.googleapis.com/v0/b/occreations-b6c14.appspot.com/o/characterimage%2FWk80hB04oZRMQxK9Ig0DDgoL5n52%2F3aa5daa6-86b7-41e5-b6aa-2dae58a991ef.png?alt=media&token=5a4e9c2a-e1f8-4d05-904a-a1d934524a09";
           userOCs.add(new CharacterInformation("12", "23",file, " Linda", "12", "Time ANGEL", "Quirk","Justin", "Flight", "lIVES IN MAIN"));

            mAdapter = new RecycleViewAdapter (userOCs, getActivity()); //where the image is inserted
            mRecyclerView.setAdapter(mAdapter);
        }

CreateCharacter.class

  private void uploadOC() {
    //String values
    nameValue = cName.getText ().toString ().trim ();
    ageValue = cAge.getText ().toString ().trim ();
    speciesValue = cSpecies.getText ().toString ().trim();
    personalityValue = cPersonality.getText ().toString ().trim();
    familyValue = cFamily.getText ().toString ().trim();
    powerValue = cPowers.getText ().toString ().trim();
    bioValue = cBiography.getText ().toString ().trim();
    currentUserID = firebaseAuth.getCurrentUser().getUid();


    if (!TextUtils.isEmpty (nameValue) && selectedImage != null) {
      //  StorageReference fileReference = storageReference.child(System.currentTimeMillis()+ "." + getFileExtension(downloadImage));

        storageReference = storageReference.child("characterimage").child (currentUserID + "/" + UUID.randomUUID ().toString ());

            storageReference.putFile (selectedImage)

                     .addOnSuccessListener (new OnSuccessListener<UploadTask.TaskSnapshot> () {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                           downloadImage = taskSnapshot.getUploadSessionUri ();
                            String characterId = databaseReference.child("characters").push ().getKey(); //creates unique random id
                      //      String photoName = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
                            CharacterInformation newCharacter =  new CharacterInformation (currentUserID, characterId, downloadImage.toString(),nameValue, ageValue, speciesValue,
                                    personalityValue, familyValue, powerValue, bioValue);

                            Map<String, Object> postValue = newCharacter.toMap();
                            Map<String, Object> childUpdates = new HashMap<> ();
                            databaseReference.child("User Account").child(currentUserID).child("character").child(characterId).setValue(newCharacter);

                            childUpdates.put(nameValue, newCharacter);
                            databaseReference.updateChildren (childUpdates);
                            Toast.makeText (getActivity (), "Uploaded", Toast.LENGTH_SHORT).show ();

                        }
                    })
                    .addOnFailureListener (new OnFailureListener () {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText (getActivity (), "Failed " + e.getMessage (), Toast.LENGTH_SHORT).show ();
                        }
                    })
                    .addOnProgressListener (new OnProgressListener<UploadTask.TaskSnapshot> () {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            double progress = (100.0 * taskSnapshot.getBytesTransferred () / taskSnapshot
                                    .getTotalByteCount ());
                        }
                    });

    }
    else {
        Toast.makeText (getActivity (), "Character needs name", Toast.LENGTH_SHORT).show ();
    }
}

RecyclerViewAdapter.class

public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.ViewHolder> {
    private List<CharacterInformation> mDataset;
    private Context context;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView image;
        private Context context;

        private ViewHolder(View view) {
            super(view);
           image = (ImageView) view.findViewById(R.id.recycleImage);
        }

    }

    public RecycleViewAdapter(List<CharacterInformation> myDataset, Context context) {
        mDataset = myDataset;
        this.context = context;
    }

    @Override
    public RecycleViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                     int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_row, parent, false);
        ViewHolder vh = new ViewHolder(view);
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.image.setScaleType (ImageView.ScaleType.CENTER_CROP);
        CharacterInformation oc = mDataset.get(position);
        Picasso.get().load(oc.getPhoto_id ())
                .into(holder.image);
        System.out.println("Binding images...");
        Toast.makeText (context,"Binding images" + oc.getCharacterName(), Toast.LENGTH_SHORT).show();
       holder.image.setOnClickListener (new View.OnClickListener () {

            @Override
            public void onClick(View v) {
                AppCompatActivity activity = (AppCompatActivity) v.getContext();
                DisplayCharacter ocFragment = new DisplayCharacter ();
                activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, ocFragment).addToBackStack(null).commit();
            }
        });
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

}

【问题讨论】:

  • 您的图片是否存储在 Firebase 存储中?如果是这样,请尝试从 Firebase 存储中读取。如果你保存的图片的名字是用户名,你可以从路径中读取用户名并从那里接收图片。
  • 它们已存储,我设法将 photo_id url 更改为来自 Firebase 存储的 downlow url 下的正确地址。现在,我正在尝试让 DatabaseReference 使角色出现在 photo_id 下。当我运行它时,主页片段中没有发生任何事情,而只有测试代码。我需要从 StorageReference 中获取它吗?
  • 在 onBindViewHolder 下检查 oc.getPhoto_id() 是否返回 null 值是否返回您的图片链接
  • 我认为通过从 Firebase Storage 读取来获取图像会很简单。我无法获得确切的链接,但我知道一个名为 Code In Flow 的 YouTube 频道提供了有关如何从 Firebase Storgae 检索图像的精彩教程。您可以查看它们以学习从 Firebase 存储中读取数据。这可能会有所帮助。
  • 我确实有一个嵌套表。当我将其更改为 characterReference.child(userid).orderByChild(user.getUid()).addValueEventListener(new ValueEventListener ()....我得到 W/ClassMapper: No setter/field for -LQo0mbXKgYa2HIgkBSn found on class etc.

标签: android firebase firebase-realtime-database


【解决方案1】:

我已经找到了这个问题的答案 这就是我解决问题的方法,但更像是我遇到了无设置器字段问题和从数据库引用调用的问题。

W/ClassMapper: No setter/field for class

我必须调用数据库引用来获取我的嵌套数据。

public void retrieveUserOCs() {
        System.out.println("Revoke the character reference ");
        reference = FirebaseDatabase.getInstance().getReference("User Account");
        DatabaseReference characterReference = reference.child(user.getUid()).child("character");
        // final Query query = characterReference;
        reference.child(user.getUid()).child("character").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                ////Loop 1 to go through all the child nodes of characters
                for(DataSnapshot characterSnapshot : dataSnapshot.getChildren()){
                        if (dataSnapshot.getValue() != null ) {
                            CharacterInformation oc = characterSnapshot.getValue (CharacterInformation.class);
                            String ocKey = characterSnapshot.getKey ();
                            System.out.println ("Adding ocs: " + ocKey + " Name: " + oc.getCharacterName ());
                            Log.d ("TAGGING OCS", ocKey + " / " + oc.getCharacterName ());
                            userOCs.add (oc);
                            Toast.makeText (getContext(), "Adding images " + oc.getCharacterName (), Toast.LENGTH_SHORT).show ();
                        } else { //if user haven't added any characters
                            break;
                        }
                }
                String file2 ="http://ghostfinder101.weebly.com/uploads/1/9/7/3/19737887/published/gear-of-diamond_1.png?1541826567";
                userOCs.add(new CharacterInformation("34", "124",file2, "Diamond", "2002", "Diamond Angel", "Narcissistic","Jahara(friend)", "Flight, shard attacks", "lIVES IN MAIN"));
                mAdapter = new RecycleViewAdapter (userOCs, getActivity()); //where the image is inserted
                mRecyclerView.setAdapter(mAdapter);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                System.out.println("Database error");
            }

        });
    }

【讨论】:

    猜你喜欢
    • 2021-05-05
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多