无法从嵌套的实时数据库中将图像显示在recyclerview中

时间:2018-11-08 15:20:52

标签: android firebase firebase-realtime-database

这是我的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的链接测试代码时,它可以工作。但是为什么我不能从数据库中获取图像?

我似乎找不到问题。我以为它可能是arraylist,photo_id url或我上载到Firebase存储/实时数据库的方式,也许是因为无法获取文件名.png或.jpeg并将其存储为photo_id吗?

更新:我更改了URL链接以从Firebase Storage下载URL,但是我无法从DatabaseReference中检索该链接,因此没有任何内容添加到列表中

我正在关注本教程。Coding-In-Flow Tutorial

UPDATE2::嵌套数据有问题。我只想从实时数据库中获取photo_id值(即url),但我将其作为空值获取。更改recyclerview后,占位符图像为null。除非有办法,我应该如何仅从字符子项到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();
    }

}

1 个答案:

答案 0 :(得分:0)

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

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

        });
    }