Avant la mise à jour de Gradle, tout fonctionnait bien, mais plus tard, cette erreur est apparue. J'ai référé aux documents officiels et il fournit le même code . N'accepte pas la méthode getDownloadUrl ()
J'ai ajouté la dépendance correcte, la dernière en date, et la synchronisation est effectuée avec succès . app/build.gradle
Il s'agit de l'exemple de code fourni dans les documents firebase qui est identique au mien . Firebase Assistant
Je suis incapable de comprendre ce qui pourrait éventuellement mal tourner même si toutes les choses requises sont présentes. Coincé sur cela depuis 2 jours, aidez s'il vous plaît!
Comme Doug l'a fait remarquer, UploadTask.getDownloadUrl()
étant obsolète, utilisez StorageReference.getDownloadUrl () .
Mais StorageReference.getDownloadUrl () renvoie Task, qui doit être traité de manière asynchrone, vous ne pouvez pas do Uri downloadUrl = photoRef.getDownloadUrl().getResult();
sinon vous obtiendrez Java.lang.IllegalStateException: Task is not yet complete
Par conséquent, gérez-le de manière asynchrone comme ceci
photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
Toast.makeText(getBaseContext(), "Upload success! URL - " + downloadUrl.toString() , Toast.LENGTH_SHORT).show();
}
});
UploadTask.getDownloadUrl()
est obsolète. Utilisez StorageReference.getDownloadUrl () à la place.
getDownloadUrl
n'existe plus.
La nouvelle méthode est donc:
final StorageReference ref = storageRef.child("images/mountains.jpg");
uploadTask = ref.putFile(file);
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
@Override
public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
} else {
// Handle failures
// ...
}
}
});
Si vous avez un 'image_uri' et le mettez dans la base de feu, ce code vous aidera.
private StorageReference storageReference= FirebaseStorage.getInstance().getReference();
final StorageReference ref = storageReference.child("picture.jpg");
ref.putFile(image_uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
final Uri downloadUrl = uri;
}
});
Pour kotlin
val uploadTask = fileReference.putFile(Uri.fromFile(primaryFile), metadata)
et
uploadTask
.addOnProgressListener { taskSnapshot ->
}
.addOnPausedListener {
}
.addOnSuccessListener { taskSnapshot ->
}
.continueWithTask { task ->
if (!task.isSuccessful) {
throw task.exception!!
}
fileReference.downloadUrl
}
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val downloadUrl: Uri = task.result
} else {
// Handle failures
}
}
.addOnFailureListener { e ->
}
val downloadUrl
est votre URL qui est téléchargée.
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Map newImage = new HashMap();
newImage.put("profileImageUrl", uri.toString());
mDriverDatabase.updateChildren(newImage);
finish();
return;
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
finish();
return;
}
});
}
}); ** Nous pouvons utiliser get url de téléchargement de cette manière, car firebase apporte quelques modifications **
Essayez ce code ..
public class MainActivity extends AppCompatActivity {
String LOG_TAG = MainActivity.class.getSimpleName();
Button buttonUpload, buttonDownload;
RadioGroup radioGroup;
ImageView imageviewResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonUpload = findViewById(R.id.upload_button);
buttonDownload = findViewById(R.id.download_button);
radioGroup = findViewById(R.id.radio_group);
imageviewResult = findViewById(R.id.resultant_imageview);
buttonUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
uploadImage();
}
});
buttonDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
downloadImage();
}
});
}
private void uploadImage() {
// Start by getting our StorageReference
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference rootRef = storage.getReference();
StorageReference bearRef = rootRef.child("images/bear.jpg");
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();
// Get the data from the image as bytes
ImageView bearImage = getSelectedBearImage();
bearImage.setDrawingCacheEnabled(true);
bearImage.buildDrawingCache();
Bitmap bitmap = bearImage.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
// Upload it to our reference
UploadTask uploadTask = bearRef.putBytes(data);
buttonDownload.setEnabled(false);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Log.w(LOG_TAG, "Upload failed: " + exception.getMessage());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
progressDialog.dismiss();
Log.d(LOG_TAG, "Download Url: " + downloadUrl);
buttonDownload.setEnabled(true);
}
});
}
private void downloadImage() {
// Start by getting a reference to the same location we uploaded to
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference rootRef = storage.getReference();
StorageReference bearRef = rootRef.child("images/bear.jpg");
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();
// Download our data with a max allocation of 1MB
final long ONE_MEGABYTE = 1024 * 1024;
bearRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
@Override
public void onSuccess(byte[] bytes) {
// Convert bytes to bitmap and call setImageBitmap
progressDialog.dismiss();
Log.d(LOG_TAG, "Download successful");
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
imageviewResult.setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle any errors
progressDialog.dismiss();
Log.w(LOG_TAG, "Download failed: " + exception.getMessage());
}
});
}
private ImageView getSelectedBearImage() {
switch (radioGroup.getCheckedRadioButtonId()) {
case R.id.radio1:
return findViewById(R.id.image_bear1);
case R.id.radio2:
return findViewById(R.id.image_bear2);
case R.id.radio3:
return findViewById(R.id.image_bear3);
case R.id.radio4:
return findViewById(R.id.image_bear4);
default:
return findViewById(R.id.image_bear1);
}
}
}
activité.xml ..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
xmlns:app="http://schemas.Android.com/apk/res-auto"
xmlns:tools="http://schemas.Android.com/tools"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:orientation="vertical"
tools:context="com.example.adruser.firebasestorageapp.MainActivity">
<LinearLayout
Android:layout_width="match_parent"
Android:layout_height="96dp"
Android:orientation="horizontal">
<ImageView
Android:id="@+id/image_bear1"
Android:layout_width="0dp"
Android:layout_height="wrap_content"
Android:layout_weight="1"
Android:scaleType="centerInside"
Android:src="@drawable/a"/>
<ImageView
Android:id="@+id/image_bear2"
Android:layout_width="0dp"
Android:layout_height="wrap_content"
Android:layout_weight="1"
Android:scaleType="centerInside"
Android:src="@drawable/tiger"/>
<ImageView
Android:layout_width="0dp"
Android:id="@+id/image_bear3"
Android:layout_height="wrap_content"
Android:layout_weight="1"
Android:scaleType="centerInside"
Android:src="@drawable/download"/>
<ImageView
Android:layout_width="0dp"
Android:id="@+id/image_bear4"
Android:layout_height="wrap_content"
Android:layout_weight="1"
Android:scaleType="centerInside"
Android:src="@drawable/add"/>
</LinearLayout>
<RadioGroup
Android:id="@+id/radio_group"
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:orientation="horizontal">
<RadioButton
Android:id="@+id/radio1"
Android:layout_width="0dp"
Android:layout_weight="1"
Android:checked="true"
Android:layout_height="wrap_content" />
<RadioButton
Android:id="@+id/radio2"
Android:layout_width="0dp"
Android:layout_weight="1"
Android:layout_height="wrap_content" />
<RadioButton
Android:id="@+id/radio3"
Android:layout_width="0dp"
Android:layout_weight="1"
Android:layout_height="wrap_content" />
<RadioButton
Android:id="@+id/radio4"
Android:layout_width="0dp"
Android:layout_weight="1"
Android:layout_height="wrap_content" />
</RadioGroup>
<TextView
Android:layout_marginTop="16dp"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:text="Downloaded Image"/>
<ImageView
Android:id="@+id/resultant_imageview"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:layout_marginTop="16dp"/>
<Button
Android:id="@+id/upload_button"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:layout_marginTop="24dp"
Android:text="Upload"/>
<Button
Android:id="@+id/download_button"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:enabled="false"
Android:layout_marginTop="8dp"
Android:text="Download"/>
</LinearLayout>
et j'espère que vous avez connecté avec le stockage firebase et donné la permission à internet ..
<uses-permission Android:name="Android.permission.INTERNET"/>
plus d'informations, consultez ce lien .. https://code.tutsplus.com/tutorials/image-upload-to-firebase-in-Android-application--cms-29934