如何将多个图像上传到firebase数据库并进行检索

时间:2018-06-18 10:59:53

标签: java android firebase firebase-realtime-database

如何以索引值存储Firebase数据库中的所有图像。

This is sample screenshot of my firebase database structure

这是我的照片上传课程,但图片仅使用单个ID和单个图片网址存储。如何将多个图像上传到firebase数据库并进行检索。请帮助我和新的firebase数据库上传多个图片。

public class PhotoUploadActivity extends AppCompatActivity implements View.OnClickListener {

private String mListID,mInspectionID;
private FirebaseStorage firebaseStorage;
private StorageReference storageReference;


private Button openCustomGallery;
private Button mUploadPhoto;
private GridView selectedImageGridView;

private static final int CustomGallerySelectId = 1;//Set Intent Id
public static final String CustomGalleryIntentKey = "ImageArray";//Set Intent Key Value
private List<String> selectedImages;
private GalleryAdapter adapter;
private String imagesArray;
private String timestampString;
private String formattedTimestamp;
private Long timestamp;
private int failUplaod;
private int successUpload;
private ProgressDialog uploadProgress;
private String pathPhoto;
private String remarkPhoto;
private int currentprogress;
private ImageView currentImage;
private String mTestID;
 private ArrayList<String > blogimages;
private String mKeyID, mAddress, mLocationKey, mRegion;
private HashMap<String,Object> photos = new HashMap<>();
private HashMap<String, String> metadata = new HashMap<>();
public static boolean loaded = false;
StorageReference mstorageReference;
DatabaseReference mdatabaseReference;
FirebaseAuth firebaseAuth;
DatabaseReference userdatabaseReference;
EditText desc;
Button upload;
private ProgressDialog mProgressbar;

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

    setTitle("Write Post");
    mProgressbar = new ProgressDialog(this);

    initViews();
    setListeners();
    mstorageReference = FirebaseStorage.getInstance().getReference();
    mdatabaseReference = FirebaseDatabase.getInstance().getReference().child("Blog");
    firebaseAuth = FirebaseAuth.getInstance();
    userdatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(firebaseAuth.getCurrentUser().getUid());
   upload = (Button)findViewById(R.id.new_post_submit);
   desc = (EditText)findViewById(R.id.new_post_text);
    upload.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            UploadTask uploadTask;
            if( selectedImageGridView.getChildCount()!= 0)
            {
                blogimages   =  new ArrayList<>();
                mProgressbar.setMessage("Post Uploading_Please Wait.....");
                mProgressbar.show();

                for ( int i = 0; i < selectedImages.size(); i++) {


                   Uri  uri = Uri.parse("file://"+selectedImages.get(i));

                    Log.v("URIIII", String.valueOf(uri));
                    final String CurrentUser = firebaseAuth.getCurrentUser().getUid();
                    StorageReference reference = mstorageReference.child("Blog_pics/users").child(uri.getLastPathSegment());

                    uploadTask = reference.putFile(uri);

                   uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            //todo: if want to make this the full progress bar, just need to make this as the sum of all progress and add to the main progress dialog
                            double progress = (100.0 * (taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());

                            mProgressbar.setMessage("Uploading Images.....");
                            mProgressbar.show();


                        }
                    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                            final Uri downloaduri = taskSnapshot.getDownloadUrl();
                            Log.v("DOWNLOAD URI", String.valueOf(downloaduri));
                            blogimages.add(downloaduri.toString());
                            Log.v("BLOGGIMAGES", String.valueOf(blogimages));
                           // final String path=  uri.getLastPathSegment();
                            final String key = mdatabaseReference.push().getKey();
                            final String posttitle = desc.getText().toString();
                            final String CurrentUser = firebaseAuth.getCurrentUser().getUid();
                            userdatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(DataSnapshot dataSnapshot) {

                                    DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                                    Date today = Calendar.getInstance().getTime();
                                    final   String current_time = df.format(today);
                                    Blog blog = new Blog();
                                    long millis = System.currentTimeMillis();
                                    int timestamp = ((int) (millis/1000))* -1;
                                    blog.setTimestamp(current_time);
                                   blog.setTime(timestamp);
                                    blog.setTitle(posttitle);
                                    blog.setUrl(blogimages);
                                   blog.setUid(firebaseAuth.getCurrentUser().getUid());
                                 blog.setUsername(dataSnapshot.child("name").getValue().toString());
                                   blog.setImage(dataSnapshot.child("image").getValue().toString());
                                   mdatabaseReference.child(key).setValue(blog) .addOnSuccessListener(new OnSuccessListener<Void>()
                                    {
                                        @Override
                                        public void onSuccess(Void aVoid)
                                        {
                                            Intent mm = new Intent(PhotoUploadActivity.this, MainActivity.class);
                                            startActivity(mm);
                                        }
                                    }).addOnFailureListener(new OnFailureListener()
                                    {
                                        @Override
                                        public void onFailure(@NonNull Exception e)
                                        {
                                            Toast.makeText(PhotoUploadActivity.this,"Failed to post the blog.. Try again later",Toast.LENGTH_LONG).show();
                                        }
                                    });

                                }

                                @Override
                                public void onCancelled(DatabaseError error) {
                                }
                            });
                            }

                    }) .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {

                            Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }

            }else
            {
                Toast.makeText(PhotoUploadActivity.this,"Please enter all fields and Select images.",Toast.LENGTH_LONG).show();

            }

        }
    });

    selectedImageGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
            AlertDialog.Builder deleteDialog = new AlertDialog.Builder(PhotoUploadActivity.this)
                    .setTitle("Delete Item?")
                    .setMessage("Do you want to remove this item?")
                    .setNegativeButton("No", null)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            adapter.removeitem(position);
                            adapter.notifyDataSetChanged();

                            /*Or you can do it this way if the top one doesnt work:

                            selectedImageGridView.setAdapter(null);*/
                        }
                    });

            deleteDialog.create().show();


            return true;
        }
    });


}



private void initViews() {
    openCustomGallery = (Button) findViewById(R.id.openCustomGallery);
    selectedImageGridView = (GridView) findViewById(R.id.selectedImagesGridView);
   // mUploadPhoto = (Button) findViewById(R.id.UploadPhotos);

}

//set Listeners
private void setListeners() {
    openCustomGallery.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.openCustomGallery:
            //Start Custom Gallery Activity by passing intent id
            Intent intent = new Intent(PhotoUploadActivity.this, CustomGalleryActivity.class);
            startActivityForResult(intent, CustomGallerySelectId);
            break;
    }

}

@Override
protected void onActivityResult(int requestcode, int resultcode, Intent imagereturnintent) {
    super.onActivityResult(requestcode, resultcode, imagereturnintent);
    switch (requestcode) {
        case CustomGallerySelectId:
            if (resultcode == RESULT_OK) {
                imagesArray = imagereturnintent.getStringExtra(CustomGalleryIntentKey);//get Intent data
                //Convert string array into List by splitting by ',' and substring after '[' and before ']'
                selectedImages =  Arrays.asList(imagesArray.substring(1, imagesArray.length() - 1).split(", "));
                //loadGridView(new ArrayList<String>(selectedImages));//call load gridview method by passing converted list into arrayList
                adapter = new GalleryAdapter(PhotoUploadActivity.this,new ArrayList<>(selectedImages),false);
                selectedImageGridView.setAdapter(adapter);

            }
            break;

    }
}

@Override
public void onBackPressed() {
    super.onBackPressed();
}

//I'm saving the instance state of photos.. let's see how

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable("Photos",photos);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    savedInstanceState.getSerializable("Photos");
}
}

1 个答案:

答案 0 :(得分:0)

要解决此问题,请将图片网址存储在applyFilter中。您的数据库结构应如下所示:

Map

要显示所有这些图片,只需获取Firebase-root | --- Blog | --- blogId | --- urls | | | --- "https://firebasestorage...": true | | | --- "https://firebasestorage...": true | --- //the other blog details 对象,这是一张地图并进行迭代以获取实际照片网址的键。

修改

还有另一种结构,如下所示:

urls