Полное решение:
CloudStorageDatabaseUtils.java
public class CloudStorageDatabaseUtils {
public void uploadImage(String storageChildAndPath, File file) {
Uri uriFile = Uri.fromFile(file);
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
final StorageReference ref = storageRef.child(storageChildAndPath);
ref.putFile(uriFile);
}
public void getDownloadURL(String path, UrlReceiver receiver) {
StorageReference reference = FirebaseStorage.getInstance().getReference().child(path);
reference.getDownloadUrl().addOnSuccessListener(uri -> receiver.onUrlReceived(uri.toString()));
}
}
activity_upload_image.xml
просто кнопка
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button_upload"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="@string/action_upload_an_image"/>
</LinearLayout>
UrlReceiver.java
public interface UrlReceiver {
/**
* @param url URL which will be received
*/
void onUrlReceived(String url);
}
UploadImageActivity.java
public class UploadImageActivity extends AppCompatActivity implements View.OnClickListener, UrlReceiver {
CloudStorageDatabaseUtils databaseUtils = new CloudStorageDatabaseUtils();
String downloadUrl;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_image);
Button upload = findViewById(R.id.button_upload);
upload.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_upload:
File rootStorage = Environment.getExternalStorageDirectory();
File exactlyFile = new File(rootStorage.toString() + "/download/q1.jpeg");//or whatever
databaseUtils.uploadImage("/example1/" + exactlyFile.getName(), exactlyFile);
databaseUtils.getDownloadURL("/example1/" + exactlyFile.getName(), this);
}
}
@Override
public void onUrlReceived(String url) {
if (url != null) {
downloadUrl = url;
Log.d("MyS", "url: " + url);
}
}
}