Изображение загружается в Firebase, но каталог не создается по какой -то причине. Однако происходит только в 1 из 2 фрагAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Изображение загружается в Firebase, но каталог не создается по какой -то причине. Однако происходит только в 1 из 2 фраг

Сообщение Anonymous »

private void uploadImageToFirebase(Bitmap bitmap)
{
if(bitmap == null)
{
Log.e(TAG, "Cannot upload null bit map");
return;
}

if(!isAdded() || getActivity() == null || getActivity().isFinishing())
{
return; // Fragment is no longer attached
}

// Show a loading indicator
Toast.makeText(requireContext(), "Uploading image...", Toast.LENGTH_SHORT).show();

// Get the current user ID
FirebaseUser currentUser = auth.getCurrentUser();
if(currentUser == null)
{
Log.e(TAG, "No user is currently logged in");
Toast.makeText(requireContext(),
"You must be logged in to upload an image", Toast.LENGTH_SHORT).show();
return;
}

// Create a unique filename for the image
String filename = "restaurant_images/" + restaurantID + "/" + UUID.randomUUID().toString() + ".jpg";

StorageReference imageRef = storageRef.child(filename);

// Compress the image before uploading
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
byte[] imageData = baos.toByteArray();

// Start the upload
isUploading = true;
currentUploadTask = imageRef.putBytes(imageData);
currentUploadTask.addOnSuccessListener(taskSnapshot ->
{
isUploading = false;
currentUploadTask = null;

// Only proceed if fragment is still attached
if(isAdded() && getActivity() != null && !getActivity().isFinishing())
{
// Image uploaded successfully, now get the download URL
imageRef.getDownloadUrl().addOnSuccessListener(downloadUri ->
{
if(isAdded() && getActivity() != null && !getActivity().isFinishing())
{
// Got the download URL, now update the user's Firestore document
Log.d(TAG, "Called updateImageWithImageUrl with URL: " + downloadUri.toString());
updateImageWithImageUrl(downloadUri.toString(), new ManageMenuFragment.OnImageURLUpdateCompleteListener()
{
@Override
public void onImageURLImageUpdate(String imageURL)
{
saveRestaurantChanges(imageURL);
}
});
Log.d(TAG, "Upload successful, URL: " + downloadUri.toString());
}
}).addOnFailureListener(e ->
{
if(isAdded() && getActivity() != null && !getActivity().isFinishing())
{
Log.e(TAG, "Failed to get download URL", e);
Toast.makeText(requireContext(),
"Failed to get image URL: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}).addOnFailureListener(e ->
{
isUploading = false;
currentUploadTask = null;

if(isAdded() && getActivity() != null && !getActivity().isFinishing())
{
Log.e(TAG, "Image upload failed", e);
Toast.makeText(requireContext(),
"Upload failed: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(taskSnapshot ->
{
// Calculate and show upload progress if needed
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
Log.d(TAG, "Upload progress: " + progress + "%");
});
}
< /code>
Эта функция загружает изображение, но каталог в хранилище фактически не создается по какой -то причине. Я понятия не имею, почему, и у меня даже есть очень похожий, где он также не создается. Другие функции из того, что я проверил, на самом деле не актуальны, потому что они не делают ничего, что связано с хранением. < /P>
private void uploadImageToFirebase(Bitmap bitmap)
{
if(bitmap == null)
{
Log.e(TAG, "Cannot upload null bit map");
return;
}

if(!isAdded() || getActivity() == null || getActivity().isFinishing())
{
return; // Fragment is no longer attached
}

// Show a loading indicator
Toast.makeText(requireContext(), "Uploading image...", Toast.LENGTH_SHORT).show();

// Get the current user ID
FirebaseUser currentUser = auth.getCurrentUser();
if(currentUser == null)
{
Log.e(TAG, "No user is currently logged in");
Toast.makeText(requireContext(),
"You must be logged in to upload a profile picture", Toast.LENGTH_SHORT).show();
return;
}

String userId = currentUser.getUid();
// Create a unique filename for the image
String filename = "profile_images/" + userId + "/" + UUID.randomUUID().toString() + ".jpg";
StorageReference imageRef = storageRef.child(filename);

// Compress the image before uploading
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
byte[] imageData = baos.toByteArray();

// Start the upload
isUploading = true;
currentUploadTask = imageRef.putBytes(imageData);
currentUploadTask.addOnSuccessListener(taskSnapshot ->
{
isUploading = false;
currentUploadTask = null;

// Only proceed if fragment is still attached
if(isAdded() && getActivity() != null && !getActivity().isFinishing())
{
// Image uploaded successfully, now get the download URL
imageRef.getDownloadUrl().addOnSuccessListener(downloadUri ->
{
if(isAdded() && getActivity() != null && !getActivity().isFinishing())
{
// Got the download URL, now update the user's Firestore document
updateUserProfileWithImageUrl(downloadUri.toString());
Log.d(TAG, "Upload successful, URL: " + downloadUri.toString());
}
}).addOnFailureListener(e ->
{
if(isAdded() && getActivity() != null && !getActivity().isFinishing())
{
Log.e(TAG, "Failed to get download URL", e);
Toast.makeText(requireContext(),
"Failed to get image URL: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}).addOnFailureListener(e ->
{
isUploading = false;
currentUploadTask = null;

if(isAdded() && getActivity() != null && !getActivity().isFinishing())
{
Log.e(TAG, "Image upload failed", e);
Toast.makeText(requireContext(),
"Upload failed: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(taskSnapshot ->
{
// Calculate and show upload progress if needed
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
Log.d(TAG, "Upload progress: " + progress + "%");
});
}
< /code>
Здесь действительно создает каталог. Еще раз, никакой заметной разницы, когда я тестировал вещи с журналами, все сработало правильно, только что каталог в другом фрагменте не создавался, и из -за того, что все URL -адреса изображения приведут к 404S. Любая помощь ценится, я могу публиковать журналы, если это необходимо. До сих пор все было хорошо, и мне нужно исправить это как можно скорее, как и до субботы, чтобы на самом деле закончить в основном все мое приложение, и осталось много работы.

Подробнее здесь: https://stackoverflow.com/questions/795 ... -some-reas
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»