How to Retrieve videos from Firebase in app? - java

I want to add videos in firebase storage and retrieve all upload videos in-app through recycler view with card view.
Please give some reference or source code for this.
I am trying this for uploading video in firebase it is successfully uploaded but I am unable to retrieve it.
Thanks in advance.
public class VideoUplod extends AppCompatActivity
{
private static final int RC_PDF_PICKER = 2;
private FirebaseStorage mFirebaseStorage;
private StorageReference mChatPDFStorageReference;
public static final int RC_SIGN_IN = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_uplod);
VideoView videoView =(VideoView)findViewById(R.id.image);
//Creating MediaController
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
//specify the location of media file
Uri uri=Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/media/1.mp4");
//Setting MediaController and URI, then starting the videoView
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
mFirebaseStorage =FirebaseStorage.getInstance();
mChatPDFStorageReference = mFirebaseStorage.getReference().child("Video");
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("video/*");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PDF_PICKER);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
// Sign-in succeeded, set up the UI
Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
finish();
}
//for photo storage check
} else if (requestCode == RC_PDF_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// Get a reference to store file at chat_photos/<FILENAME>
StorageReference photoRef = mChatPDFStorageReference.child(selectedImageUri.getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
#SuppressWarnings("VisibleForTests") Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box so that the user can send it to the database
}
});
}
}
}

I'd take a look at:
Zero to App (video, source)
How to get an array with all pictures?
Firebase SDK for Cloud Storage docs
From the docs, it's pretty simple to download a file:
StorageReference videoRef = storageRef.child("videos/myvideo.mp4");
final long ONE_MEGABYTE = 1024 * 1024;
videoRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
// Transform bytes to a video, play
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});

Related

How to read a file from internal storage or external storage and store the file in a arrayList in android

My requirement is the end-user must be able to upload files into the application from internal or external storage and finally display the name of the file in the page.
Actual result: Now I've fetched the file name from the storage and displayed the name in my page.
Expected Result: The end user must be able to load image or video files from external or internal storage to the application and finally display their name in the page.
But don't have any idea about how to load read the file from storage and store it in a arrayList.
Code for fetching the file name
public class ServiceDetails extends AppCompatActivity {
private Button next, attachment_one;
private ImageButton attach_file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter_details);
next = findViewById(R.id.submit);
attachment_one = findViewById(R.id.attachmentOne);
attach_file = findViewById(R.id.attachFile);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ServiceDetails.this, ServiceAddress.class);
startActivity(intent);
}
});
attach_file.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M &&
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10001);
}
new MaterialFilePicker()
.withActivity(ServiceDetails.this)
.withRequestCode(1)
.withFilter(Pattern.compile(".*\\.(mkv|wmv|avi|mpeg|swf|mov|mp4|jpg|jpeg)$"))
.withHiddenFiles(true) // Show hidden files and folders
.start();
}
});
attachment_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
attachment_one.setVisibility(View.INVISIBLE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
String file_path = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
String file_array[] = file_path.split("/");
String file_name = file_array[file_array.length - 1];
// Do anything with file
if(attachment_one.getText().toString().isEmpty()) {
attachment_one.setVisibility(View.VISIBLE);
attachment_one.setText(file_name);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 10001: {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(ServiceDetails.this, "Permission granted", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(ServiceDetails.this, "Permission not granted", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
}
I'm new to android and kindly help me providing solution for this answer. Million thanks in advance!
Image showing file attachment option
As you are willing to load the title of video/images, and other file related information from the External Storage. You have to use this code and also make sure don't forget to create a Arraylist with model(required to extract information and find to the listview).
//ContentResolver and contentProvider as well as cursor
String[] projection = new String[]{
MediaStore.Video.Media._ID,
MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media.DATE_MODIFIED
};
String selection = null;
String[] selectionargs = null;
String orderBy = MediaStore.Video.Media.DISPLAY_NAME + " Desc";
Uri content_uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = getContentResolver().query(content_uri, projection, selection, selectionargs, orderBy);
if (cursor != null) {
cursor.moveToPosition(0);
}
while (true) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
Uri VideoUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id);
Log.d("uri", "onCreate: video path " + VideoUri);
String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
float size = cursor.getFloat(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
// loading a thumbnail from the content resolver
// Load thumbnail of a specific media item.
Bitmap thumbnail = null;
try {
thumbnail = getApplicationContext().getContentResolver().loadThumbnail(VideoUri, new Size(200, 200), null);
Log.d("thumbnail", "onCreate: Lodaing a thumbnail");
} catch (IOException e) {
Log.d("thumbnail", "onCreate: Showing Error on thumbnail");
e.printStackTrace();
}
videolist.add(new Video(thumbnail, VideoUri, title, size));
if (!cursor.isLast()) {
cursor.moveToNext();
} else {
Log.d("lastItem", "onCreate: last uri is encountered");
break;
}
}
cursor.close();

Passing Image Captured to FilePathUri

I have problem to pass the Captured Image to the FilePathUri where the image will be stored and then uploaded to Firebase. I need to integrate them together cause the FilePathUri is always returning null.
Hope somebody can show me an Example with Code. Thanks
On-Create Method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_takephoto);
// Assign FirebaseStorage instance to storageReference.
storageReference = FirebaseStorage.getInstance().getReference();
// Assign FirebaseDatabase instance with root database name.
databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
//Assign ID'S to button.
ChooseButton = (Button)findViewById(R.id.ButtonChooseImage);
UploadButton = (Button)findViewById(R.id.ButtonUploadImage);
// Assign ID's to EditText.
ImageName = (EditText)findViewById(R.id.ImageNameEditText);
// Assign ID'S to image view.
SelectImage = (ImageView)findViewById(R.id.ShowImageView);
// Assigning Id to ProgressDialog.
progressDialog = new ProgressDialog(PhotoActivity.this);
// Adding click listener to Choose image button.
ChooseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, FilePathUri);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
});
OnActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
// Line 1:
FilePathUri = data.getData();
// Line 2:
Bitmap photo = (Bitmap) data.getExtras().get("data");
SelectImage.setImageBitmap(photo);
ChooseButton.setText("Image Selected");
}
}
Uploading Image Part
// Creating UploadImageFileToFirebaseStorage method to upload image on storage.
public void UploadImageFileToFirebaseStorage() {
// Checking whether FilePathUri Is empty or not.
if (FilePathUri != null) {
// Setting progressDialog Title.
progressDialog.setTitle("Image is Uploading...");
// Showing progressDialog.
progressDialog.show();
// Creating second StorageReference.
StorageReference storageReference2nd = storageReference.child(Storage_Path + System.currentTimeMillis() + "." + FilePathUri);
// Adding addOnSuccessListener to second StorageReference.
storageReference2nd.putFile(FilePathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Getting image name from EditText and store into string variable.
String TempImageName = ImageName.getText().toString().trim();
// Hiding the progressDialog after done uploading.
progressDialog.dismiss();
// Showing toast message after done uploading.
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
#SuppressWarnings("VisibleForTests")
ImageUploadInfo imageUploadInfo = new ImageUploadInfo(TempImageName, taskSnapshot.getDownloadUrl().toString());
// Getting image upload ID.
String ImageUploadId = databaseReference.push().getKey();
// Adding image upload id s child element into databaseReference.
databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
}
})
// If something goes wrong .
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Hiding the progressDialog.
progressDialog.dismiss();
// Showing exception erro message.
Toast.makeText(PhotoActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
// On progress change upload time.
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
// Setting progressDialog Title.
progressDialog.setTitle("Image is Uploading...");
}
});
}
else {
Toast.makeText(PhotoActivity.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();
}

shared preference to save profile image

In my app I want to make a profile page with default image profile and allow to user to change it by take a picture from camera or choose image from gallery, I did that successfully and here's my code:
public class MainActivity extends AppCompatActivity {
private static final int pick = 1, capture = 2;
Uri imgeUri, touri;
ImageView imp;
SharedPreferences sh;
SharedPreferences.Editor editor;
String S;
boolean d=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("eee","in resume");
setContentView(R.layout.activity_main);
sh = getSharedPreferences("my" ,Context.MODE_PRIVATE);
editor=sh.edit();
imp = (ImageView) findViewById(R.id.profile_image);
if(d==false) {
imp.setImageResource(R.drawable.photo);
}
else{
imp.setImageURI(Uri.parse(sh.getString("link", null)));
}
}
public void changepic(View V) {
final String[] items = {"Take picture", "Choose Picture",
"cancle"};
AlertDialog.Builder build = new AlertDialog.Builder(this);
build.setTitle("Add Photo");
build.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (items[which].equals("Choose Picture")) {
Log.d("test","bh");
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i, pick);
} else if (items[which].equals("Take picture")) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, capture);
}
}
}).create().show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == pick && resultCode == RESULT_OK) {
imgeUri = data.getData();
Log.d("test","pick");
imp.setImageURI(imgeUri);
editor.putString("link",String.valueOf(imgeUri));
//Log.d("test",f);
editor.commit();
d=true;
} else if (requestCode == capture && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imp.setImageBitmap(imageBitmap);
}
}
But the problem is when selecting an image I save it in shared preference the image appears just fine when I'am in activity when go to another and return back this disappear and the activity show the default image, i know the reason it because every time i return to profile activity this was created again and the boolean variable d was false again.
How can i fix that when i must call the get preference.?
In the "onActivityResult()" method, save the imageUri (or imagePath) obtained to sharedPreferences.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edit = preferences.edit();
edit.putString(key, value);
edit.apply();
Instead of using boolean, check if sharedPreference value is not a null string.If the sharedPreference value is not a null string, update the imageview with imageUri (or imagePath) from sharedPreference.
For loading image in imageView, i recommend you to use photo loading libraries like Picasso or Glide.

Firebase Storage - Prevent Overwriting of Files

I am allowing users to take pictures and store them to Firebase. Below is my code that contains the intent to load the camera application, save the image, and then upload to the Firebase storage. The problem I am having is each subsequent upload to the Firebase Storage is overriding the previous upload, meaning I have 1 file in storage that keeps being overridden. I want to keep adding multiple files:
private void createAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.add_image_dialog_title);
builder.setItems(new CharSequence[]
{getResources().getString(R.string.add_image_web), getResources().getString(R.string.add_image_camera), getResources().getString(R.string.add_image_gallery)},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
Intent toImageSearch = new Intent(CreateActivity.this, NewImageActivity.class);
startActivityForResult(toImageSearch, USE_WEB);
break;
case 1:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getApplication().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, TAKE_PICTURE);
} else {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.camera_error), Toast.LENGTH_LONG).show();
}
break;
case 2:
Toast.makeText(getApplicationContext(), "clicked 2", Toast.LENGTH_LONG).show();
break;
case 3:
Toast.makeText(getApplicationContext(), "clicked 3", Toast.LENGTH_LONG).show();
break;
}
}
}
);
builder.create().
show();
}
OnActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case USE_WEB:
if (resultCode == CreateActivity.RESULT_OK) {
resultImageURL = data.getStringExtra("result");
mAddImageButton.setVisibility(View.INVISIBLE);
Picasso.with(getApplicationContext())
.load(resultImageURL)
.into(mImagePreview);
}
if (resultCode == CreateActivity.RESULT_CANCELED) {
//Write your code if there's no result
}
case TAKE_PICTURE:
if (resultCode == CreateActivity.RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImagePreview.setImageBitmap(imageBitmap);
encodeBitmapAndSaveToFirebase(imageBitmap);
}
}
}
Save to Firebase:
private void encodeBitmapAndSaveToFirebase(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mPollImageStorage.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getApplicationContext(), "Error Loading Photo", Toast.LENGTH_LONG).show();
}
}).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();
mAddImageButton.setVisibility(View.INVISIBLE);
resultImageURL = downloadUrl.toString();
Picasso.with(getApplicationContext())
.load(resultImageURL)
.into(mImagePreview);
}
});
}
You need to use a separate location or separate file name for each upload.
You can create a custom location like this:
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://myfirebaseproject.appspot.com");
StorageReference fileRef =
storageRef.child(channelId)
.child(String.valueOf(message.getSender()))
.child(String.valueOf(message.getTimestamp()));
UploadTask uploadTask = fileRef.putFile(message.getAttachmentUri());
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
sendMessage(channelId, message.getMessageText(), taskSnapshot.getStorage().toString(), message.getAttachmentType(), callback);
}
});
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
callback.onError(e.toString());
}
});
You can see we are adding custom locations to our base storage reference so that we don't overwrite existing items.
The location that you store your image is determined by what mPollImageStorage is referencing. If mPollingStorage always references the same place, ie, in your onCreate you do something like:
StorageReference mPollingStorage = storageRef.child("polling.jpg");
Then it will keep overriding camerapic.jpg. If you don't want to override it, you could set the image name to something like the time the image was taken or generate a UUID as per this stackoverflow post : Store files with unique/random names

How do I set the Camera Intent as the Main Activity

I want to launch the camera once a user opens up my application.
Right now I have this, and it works fine. When the user launches my application, it automatically opens up the camera. However, then the user hits the "back" button after taking an image, it opens up a blank activity.
How do I get it to go back to the camera?
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_TAKE_PHOTO = 0;
// The URI of photo taken with camera
private Uri mUriPhotoTaken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
takePhoto();
}
// Deal with the result of selection of the photos and faces.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri imageUri;
if (data == null || data.getData() == null) {
imageUri = mUriPhotoTaken;
} else {
imageUri = data.getData();
}
Intent intent = new Intent(MainActivity.this, Result.class);
intent.setData(imageUri);
startActivity(intent);
}
}
// Launch the camera to allow the user to take a photo
public void takePhoto(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null) {
// Save the photo taken to a temporary file.
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
File file = File.createTempFile("IMG_", ".jpg", storageDir);
mUriPhotoTaken = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mUriPhotoTaken);
startActivityForResult(intent, REQUEST_TAKE_PHOTO);
} catch (IOException e) {
Log.d("ERROR", e.getMessage());
}
}
}
}
Try to call takePhoto() method in the onStart() instead of onCreate() and then call the finish() method into the onStop().
Try it.
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this, ActivityYouWantToOpen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
}

Categories

Resources