i am uploading video to firebase storage. i want to show the thumbnail of selected video on app screen
i have tried uploading image with the same code and it gives me the image preview of selected image, but it doesnot show any preview or thumbnail of selected video
moreover i want to know hoe to give the path of selected video as well..
main activity
public class MainActivity extends AppCompatActivity {
private static final int PICK_VIDEO_REQUEST = 3;
Button chooseImg, uploadImg;
ImageView imgView;
int PICK_IMAGE_REQUEST = 111;
Uri filePath;
ProgressDialog pd;
//creating reference to firebase storage
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://<<ur app url>>"); //change the url according to your firebase app
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseImg = (Button)findViewById(R.id.chooseImg);
uploadImg = (Button)findViewById(R.id.uploadImg);
imgView = (ImageView)findViewById(R.id.imgView);
pd = new ProgressDialog(this);
pd.setMessage("Uploading....");
chooseImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Video"), PICK_VIDEO_REQUEST);
}
});
uploadImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(filePath != null) {
pd.show();
StorageReference childRef = storageRef.child("vide.mp4");
//uploading the image
UploadTask uploadTask = childRef.putFile(filePath);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(MainActivity.this, "Select a video", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
//getting image from gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting image to ImageView
imgView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Related
I'm trying to upload some pictures and videos from the gallery to the Firebase Storage. I tried For the images I had no problems, but for the videos yes. I tried with several tutorial found on google but none worked.
How could I do? This is the code I have written so far:
public class GalleryActivity extends AppCompatActivity {
private Button chooseImage;
private Button chooseVideo;
private Button sendToCloud;
private ImageView selectedImage;
private VideoView selectedVideo;
private TextView txtDescription;
private static final int PICK_IMAGE = 100;
private static final int PICK_VIDEO = 200;
private Uri mImageUri;
//Firebase stuff
private FirebaseStorage storage;
private StorageReference storageReference;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
txtDescription = findViewById(R.id.diplay);
selectedImage = findViewById(R.id.image_taken);
selectedVideo = findViewById(R.id.video_taken);
chooseImage = findViewById(R.id.imageBtn);
chooseVideo = findViewById(R.id.videoBtn);
sendToCloud = findViewById(R.id.send_to_cloud);
// get the Firebase storage reference
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
chooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseImageFromGallery();
}
});
chooseVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseVideoFromGallery();
}
});
sendToCloud.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(selectedImage.getDrawable() != null) {
uploadImage();
}
//check if videoview is empty and call uploadVideo()
}
});
}
private void chooseVideoFromGallery() {
Intent i = new Intent();
i.setType("video/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i, "choose App"), PICK_VIDEO);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
if (requestCode == PICK_IMAGE) {// img from gallery
previewImage(data);
} else if (requestCode == PICK_VIDEO) {
previewVideo(data);
}
}
}
private void previewVideo() {
try {
txtDescription.setVisibility(View.GONE);
selectedImage.setVisibility(View.GONE);
selectedVideo.setVisibility(View.VISIBLE);
selectedVideo.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private void previewImage(Intent data) {
try {
txtDescription.setVisibility(View.GONE);
selectedVideo.setVisibility(View.GONE);
selectedImage.setVisibility(View.VISIBLE);
Uri imgUri = data.getData();
InputStream imageStream = GalleryActivity.this.getContentResolver().openInputStream(imgUri);//2
Bitmap selectedImageBitmap = BitmapFactory.decodeStream(imageStream);//3}
mImageUri = imgUri;
selectedImage.setImageBitmap(selectedImageBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Thanks in advance to everyone
This is the working code:
if (resultCode == RESULT_OK) {
if (requestCode == PICK_VIDEO) {
Uri videoUri= data.getData();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
String filename = "give a unique filename for each";
videoRef = storageRef.child("/videos/" + uid+ "/" + filename);
uploadVideo(videoUri);
}
}
Upload Video here:
private void uploadVideo(Uri videoUri) {
if(videoUri != null){
UploadTask uploadTask = videoRef.putFile(videoUri);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>({
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful())
Toast.makeText(getContext(), "Video Upload Completed", Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
updateProgress(taskSnapshot);
}
});
}else {
Toast.makeText(getContext(), "upload failed!", Toast.LENGTH_SHORT).show();
}
}
// StorageReference videoRef;
I have this code to upload an image from the gallery or user can use their camera to take the picture, but the result code for the camera returns -1 and crashes, I honestly don't know why. Here is the code:
private Button mSelectImage;
private Button upload;
private ImageView mImage;
private StorageReference mStorage;
private static final int GALLERY_INTENT = 2;
private static final int CAMERA_REQUEST_CODE = 7;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mSelectImage = (Button) findViewById(R.id.selectImage);
upload = (Button) findViewById(R.id.captureUpload);
progressDialog = new ProgressDialog(this);
mImage = (ImageView) findViewById(R.id.image);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i, GALLERY_INTENT);
}
});
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK)
{
progressDialog.setMessage("uploading...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filePath =
mStorage.child("Photos").child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
Toast.makeText(MainActivity.this, "Image upload
successful",Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
else if(requestCode == CAMERA_REQUEST_CODE && resultCode ==
RESULT_OK)
{
progressDialog.setMessage("uploading...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filePath =
mStorage.child("Photos").child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
Toast.makeText(MainActivity.this, "Image upload
successful",Toast.LENGTH_LONG).show();
progressDialog.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this)
.load(downloadUri).fit().centerCrop().into(mImage);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
}
It works when I upload from the gallery but returns a -1 request result on the camera, just after I take the camera. It doesn't even go to the download part, (with Picasso)
Your help would be appreciated very much!!!!
Best regards
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=7, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.user.uploadingimages/com.example.user.uploadingimages.MainActivity}: java.lang.IllegalArgumentException: uri cannot be null
Without a logcat i'd say it could be a permission issue:
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
If you post the logcat i can be more precise
EDIT:
The logcat clearly states the problem
java.lang.IllegalArgumentException: uri cannot be null
Did you properly check that this statements returns a not null value?
Uri uri = data.getData();
As per logs, data.getData() is returning null.
Supply EXTRA_OUTPUT in your ACTION_IMAGE_CAPTURE Intent, in which case you know where the image should be stored, and do not need to rely upon getData()
On click of camera button, use this code:
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(f));
startActivityForResult(intent,
CAMERA_REQUEST_CODE);
Refer: Android data.getData() returns null from CameraActivity for some phones
I am trying to upload Image to firebase storage but I am neither seeing the progress dialog nor the toast message.
The debug breakpoint is not even stopping at those lines.
Please help.
ib_profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent_modifyImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent_modifyImage);
}
});
}
//Image Capture Activity Result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = storageReference_image.child("profile_photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(UserProfileActivity.this,"Upload Complete",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
try this
public class MainActivity extends AppCompatActivity {
Button chooseImg, uploadImg;
ImageView imgView;
int PICK_IMAGE_REQUEST = 111;
Uri filePath;
ProgressDialog pd;
//creating reference to firebase storage
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://fir-example-c4312.appspot.com"); //change the url according to your firebase app
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseImg = (Button)findViewById(R.id.chooseImg);
uploadImg = (Button)findViewById(R.id.uploadImg);
imgView = (ImageView)findViewById(R.id.imgView);
pd = new ProgressDialog(this);
pd.setMessage("Uploading....");
chooseImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
}
});
uploadImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(filePath != null) {
pd.show();
StorageReference childRef = storageRef.child("image.jpg");
//uploading the image
UploadTask uploadTask = childRef.putFile(filePath);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(MainActivity.this, "Select an image", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
//getting image from gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting image to ImageView
imgView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
don't forget to Change Rules in firebase console
By default we are not allowed to access firebase storage without authentication. To change it go to firebase console using any web browser. Open the firebase project that you have used in above steps and go to Storage and then Rules tab. Now change read and write rules to true as shown in below image.
try this method,its worked for me
Inside onActivityResult,
StorageReference storageRef = storage.getReferenceFromUrl(---STORAGE_BUCKET---);
StorageReference imagePathReference = storageRef.child("image");
final Uri uri = data.getData();
Bitmap bmp = null;
try {
bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
// convert bitmap to byte array to save image in firebase storage
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (bmp != null) {
bmp.compress(Bitmap.CompressFormat.JPEG, 60, bos);
}
byte[] dataNew = bos.toByteArray();
uploadTask = imagePathReference.putBytes(dataNew);
try {
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// success
}
});
}catch (Exception e){
}
I have a code for upload an image to Firebase Storage. The code was running well but when I updated Android Studio there is a problem with code. Can you please suggest how should I change the code?
private StorageReference mStorage;
private static final int GALLERY_INTENT = 2;
private ProgressDialog mProgressDialog;
private ImageView imageViewProfilePicturePreview;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mProgressDialog = new ProgressDialog(this);
mDatabase = FirebaseDatabase.getInstance().getReference();
mStorage = FirebaseStorage.getInstance().getReference();
imageViewProfilePicturePreview = (ImageView) findViewById(R.id.imageViewProfilePicturePreview);
}
...
#Override
public void onClick(View view) {
...
if (view == textViewUploadPhoto) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
}
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
mProgressDialog.setMessage("Uploading...");
mProgressDialog.show();
StorageReference imageRef = mStorage.child(email);
StorageReference imageImagesRef = mStorage.child("photos/" + email);
imageRef.getName().equals(imageImagesRef.getName()); // true
imageRef.getPath().equals(imageImagesRef.getPath()); // false
Uri uri = data.getData();
imageViewProfilePicturePreview.setImageURI(uri);
imageViewProfilePicturePreview.setDrawingCacheEnabled(true);
imageViewProfilePicturePreview.buildDrawingCache();
Bitmap bitmap = imageViewProfilePicturePreview.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data2 = baos.toByteArray();
UploadTask uploadTask = imageImagesRef.putBytes(data2);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getApplicationContext(), "Sorry, your image wasn't set, please try again",
Toast.LENGTH_LONG).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(intent);
Uri downloadUrl = taskSnapshot.getDownloadUrl();
mProgressDialog.dismiss();
Picasso.with(getApplicationContext()).load(downloadUrl).fit().centerCrop().into(imageViewProfilePicturePreview);
Toast.makeText(getApplicationContext(), "Upload done",
Toast.LENGTH_SHORT).show();
}
});
}
}
Thanks for all help.
I've been trying to create an app which uses Firebase authentication, Firebase storage and Firebase database. Im trying to get the downloadURI from the successListener but it never reaches, and the toast never displays. However, in Firebase Storage it has successfully created a folder with profilepictures and uploaded the image. I dont see what im doing wrong, so any help is appreciated!
public class RegisterLastActivity extends AppCompatActivity {
private EditText displayName;
private Button cheersButton;
private ImageView profilePicture;
private Uri imageFile;
private boolean imageFileChosen = false;
private StorageReference mStorageRef;
private DatabaseReference mDatabase;
private static final int PICK_IMAGE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_last);
displayName = (EditText) findViewById(R.id.displayname);
cheersButton = (Button) findViewById(R.id.cheers_button);
profilePicture = (ImageView) findViewById(R.id.profile_picture);
mStorageRef = FirebaseStorage.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance().getReference();
cheersButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendToStorage(imageFile);
startActivity(new Intent(RegisterLastActivity.this, MainActivity.class));
finish();
}
});
}
public void imagePressed(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
setImageFile(uri);
imageFileChosen = true;
Log.d("OnActivityResult", "imageFileChosen " + String.valueOf(imageFileChosen));
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
//Log.d(TAG, String.valueOf(bitmap));
profilePicture.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
protected void sendToStorage(Uri uri){
if(imageFileChosen){
StorageReference storageReference = mStorageRef.child("Profilepictures").child(getCurrentToken());
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
#SuppressWarnings("VisibleForTests") Uri downloadUri = taskSnapshot.getDownloadUrl();
Toast.makeText(RegisterLastActivity.this, "Kom inn til success!", Toast.LENGTH_SHORT).show();
}
});
}else{
Toast.makeText(this, "Choose an image!", Toast.LENGTH_SHORT).show();
}
}
protected String getCurrentToken(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
return user.getUid();
}
return null;
}
public void setImageFile(Uri imageFile) {
this.imageFile = imageFile;
}
}
This doesnt produce any error messages in Android Monitor. Look for sendToStorage(Uri uri) method, that's where i have the error. I had to include the #SuppressWarnings("VisibleForTests") because it gives me an annoying error without.