gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:22:48 25 4
gpt4 key购买 nike

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

This is sample screenshot of my firebase database structure

这是我的照片上传类,但图像仅使用单个 id 和单个图像 url 进行存储。如何将多个图像上传到 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");
}
}

最佳答案

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

Firebase-root
|
--- Blog
|
--- blogId
|
--- urls
| |
| --- "https://firebasestorage...": true
| |
| --- "https://firebasestorage...": true
|
--- //the other blog details

要显示所有这些图像,只需获取 urls 对象(这是一个 map )并迭代以获取实际照片 URL 的键。

编辑:

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

Firebase-root
|
--- Blog
|
--- blogId
|
--- urls
| |
| --- pushedKeyOne: "https://firebasestorage..."
| |
| --- pushedKeyTwo: "https://firebasestorage..."
|
--- //the other blog details

关于java - 如何将多个图像上传到firebase数据库并检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50907966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com