I am trying to take a photo and then upload it to a database however each time I take a photo and try to post it I get an error :
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference.
Whenever I take a photo I never see the preview in the image view.
So what I assume is I am not adding the photo to the bitmap properly for the ImageUploadImageToServerFunction() to store the image. However it makes no sense to me for it not to work.
Heres the functions I have problems with.
Button CaptureImageFromCamera,UploadImageToServer;
ImageView ImageViewHolder;
EditText imageName;
ProgressDialog progressDialog ;
Intent intent ;
public static final int RequestPermissionCode = 1 ;
Bitmap bitmap;
boolean check = true;
String GetImageNameFromEditText;
String ImageNameFieldOnServer = "image_name" ;
String ImagePathFieldOnServer = "image_path" ;
String ImageUploadPathOnSever ="https://androidjsonblog.000webhostapp.com/capture_img_upload_to_server.php" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_activity);
CaptureImageFromCamera = (Button)findViewById(R.id.mapsPicButton);
ImageViewHolder = (ImageView)findViewById(R.id.imageView);
UploadImageToServer = (Button) findViewById(R.id.postPicBtn);
imageName = (EditText)findViewById(R.id.editText);
EnableRuntimePermissionToAccessCamera();
CaptureImageFromCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 7);
}
});
UploadImageToServer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GetImageNameFromEditText = imageName.getText().toString();
ImageUploadToServerFunction();
}
});
}
// Start activity for result method to Set captured image on image view after click.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 7 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
// Adding captured image in bitmap.
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
// adding captured image in imageview.
ImageViewHolder.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Upload captured image online on server function.
public void ImageUploadToServerFunction(){
ByteArrayOutputStream byteArrayOutputStreamObject ;
byteArrayOutputStreamObject = new ByteArrayOutputStream();
// Converting bitmap image to jpeg format, so by default image will upload in jpeg format.
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStreamObject);
byte[] byteArrayVar = byteArrayOutputStreamObject.toByteArray();
final String ConvertImage = Base64.encodeToString(byteArrayVar, Base64.DEFAULT);
class AsyncTaskUploadClass extends AsyncTask<Void,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog at image upload time.
progressDialog = ProgressDialog.show(Photo.this,"Image is Uploading","Please Wait",false,false);
}
#Override
protected void onPostExecute(String string1) {
super.onPostExecute(string1);
// Dismiss the progress dialog after done uploading.
progressDialog.dismiss();
// Printing uploading success message coming from server on android app.
Toast.makeText(Photo.this,string1,Toast.LENGTH_LONG).show();
// Setting image as transparent after done uploading.
ImageViewHolder.setImageResource(android.R.color.transparent);
}
#Override
protected String doInBackground(Void... params) {
ImageProcessClass imageProcessClass = new ImageProcessClass();
HashMap<String,String> HashMapParams = new HashMap<String,String>();
HashMapParams.put(ImageNameFieldOnServer, GetImageNameFromEditText);
HashMapParams.put(ImagePathFieldOnServer, ConvertImage);
String FinalData = imageProcessClass.ImageHttpRequest(ImageUploadPathOnSever, HashMapParams);
return FinalData;
}
}
AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();
AsyncTaskUploadClassOBJ.execute();
}
You can use this library to compress your image
compile 'id.zelory:compressor:2.1.0'
Here is this link
https://android-arsenal.com/details/1/3758
You can customize quality, height, weight etc .
compressedImageBitmap = new Compressor(this).compressToBitmap(actualImageFile);
compressedImageFile = new Compressor(this).compressToFile(actualImageFile);
If you want some customization:
compressedImage = new Compressor(this)
.setMaxWidth(640)
.setMaxHeight(480)
.setQuality(75)
.setCompressFormat(Bitmap.CompressFormat.WEBP)
.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath())
.compressToFile(actualImage);
Related
Once you have recovered an image of the user, how to save it in drawable in the app ?
For use it in other activities.
Retrieve the image from the user's gallery and put it in ImageView :
public class Profil extends AppCompatActivity {
private Button btnImport;
public ImageView selectedImg;
static final int RESULT_LOAD_IMG = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profil);
ImageView btn_supervisor = findViewById(R.id.btn_supervisor);
ImageView btn_add = findViewById(R.id.btn_add);
ImageView btn_profile = findViewById(R.id.btn_profile);
btnImport = findViewById(R.id.modifie_button);
selectedImg = findViewById(R.id.modifie_image);
btnImport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);
}
});
}
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
selectedImg.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Une erreur s'est produite",Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(getApplicationContext(),"Vous n'avez pas choisi d'image", Toast.LENGTH_LONG).show();
}
}
}
Thank you in advance.
You should never save the image drawable/ bitmap to use in other activities. Instead, you can save the Uri of the image file in some variable in your application class or some static properties holder and then can fetch bitmap from that Uri accross all your activities.
you can use BitmapDrawable to achieve this
//Convert bitmap to drawable.
Drawable drawable = new BitmapDrawable(context.getResources(), bitmap);
My app keeps resetting after I close it.
public class MainActivity extends AppCompatActivity {
public static final int FILE_REQUEST_CODE = 1;
ImageView IMG ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IMG = (ImageView) findViewById(R.id.imageView1);
Button pickBtn = (Button) findViewById(R.id.pickBtn);
pickBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pickImg();
}
});
}
private void pickImg() {
new MaterialFilePicker()
.withActivity(this)
.withRequestCode(1)
.withFilter(Pattern.compile(".*\\.(jpg|jpeg|png)$"))
.withHiddenFiles(true)
.withTitle("Sample title")
.start();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == FILE_REQUEST_CODE && resultCode == RESULT_OK) {
String filePath = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
// Do anything with file
File imgFile = new File(filePath);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
IMG.setImageBitmap(myBitmap);
}
}
}
}
My app is only filled with one button and one image default. With the button I can pick an image to replace the default image.
But when I close the app and open it again the image is back to default.
How to make it show the last picked image when I start the app??
If this app is performing simple and offline task, you could use Shared Preference to store the location of the Image. When onCreate, check whether the sharedpreference object is null or not, if not, load with the value stored.
I have searched through google and even youtube for videos. The code works perfectly when uploading and displaying the large image but crashes when sending it to the next activity. I have tried images with smaller quality or size and it worked perfectly
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 123;
public static Bitmap bitmap;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.img);
}
public void upload(View view) {
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
switch (requestCode) {
case PICK_IMAGE_REQUEST:
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
Log.i("TAG", "Some exception" + e);
}
break;
}
}
public void Submit(View view) {
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
if(bitmap !=null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, stream);
byte[] byteArray = stream.toByteArray();
intent.putExtra("bitmap", byteArray);
}
startActivity(intent);
}
}
This is where the image sent from the MainActivity.java is displayed:
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ImageView img = (ImageView) findViewById(R.id.imgg);
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("bitmap");
Bitmap bitmap = null;
try {
if (byteArray != null) {
bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
} catch (IndexOutOfBoundsException e){
e.printStackTrace();
}
img.setImageBitmap(bitmap);
}
}
Here is the error message:
java.lang.OutOfMemoryError: Failed to allocate a 3244812 byte allocation with 1765075 free bytes and 1723KB until OOM
You can't send big image via Intent, from the documentation:
When sending data via an intent, you should be careful to limit the
data size to a few KB. Sending too much data can cause the system to
throw a TransactionTooLargeException exception.
So, it's better if you send the Uri and process the Uri in the receiver Activity.
First, you need to send the Uri instead of Bitmap in the First Activity:
private Uri mFileUri;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
switch (requestCode) {
case PICK_IMAGE_REQUEST:
// Save uri for submit process.
mFileUri = data.getData();
...
break;
}
}
public void Submit(View view) {
Intent intent = new Intent(this, Main2Activity.class);
intent.setData(mFileUri);
startActivity(intent);
}
Then handle it in your receiver activity:
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ImageView img = (ImageView) findViewById(R.id.imgg);
// get the fileUri from the intent
Uri fileUri = getIntent().getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
img.setImageBitmap(bitmap);
} catch (IndexOutOfBoundsException e){
// handle the exception.
}
}
}
This:
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
This line drains memory so hard. Now you have the URI of the image right?
Uri filePath = data.getData();
Now use Picasso to load the image like below
1. If you want to send the image somewhere else:
com.squareup.picasso.Target mTarget = new com.squareup.picasso.Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
imageView.setImageBitmap(bitmap);
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
Picasso.with(mContext).load(filePath).into(mTarget);
If you want to Use the image in lower quality, Just do this:
Picasso.with(mContext).load(filePath).centerInside().resize(YourWidth,YourHeight).into(imageview);
The answers simple. Store the image in a the devices file storage, pass the Uri of the image in storage to the Intent that is launching another activity, then fetch the Uri from said intent, and load from the file.
Your Bitmap object in MainActivity is marked as static, I doubt why is that necessary.
Making it static makes Android cannot GC it when you start Main2Activity,
A potential reason of why you are running out of memory.
Try to change it to private Bitmap bitmap. It might solves your problem.
But generally passing a bitmap object over an Activity is rare.
Since you mentioned that the image is uploaded, it is much better to get an image URL from server after you have uploaded it, and then use some Image Library such as Glide or Fresco to load it from the internet.
I am new in android ,and am trying to upload a file to server using ion library
ion library but the file crashes. with this error.
FATAL EXCEPTION: Thread-55725
Process: transitions.com.example.huzy_kamz.interview, PID: 4635
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:209)
at android.os.Handler.<init>(Handler.java:123)
at android.app.Dialog.<init>(Dialog.java:122)
at android.app.AlertDialog.<init>(AlertDialog.java:200)
at android.app.AlertDialog.<init>(AlertDialog.java:196)
at android.app.AlertDialog.<init>(AlertDialog.java:141)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at transitions.com.example.huzy_kamz.interview.MainActivity.uploadFile(MainActivity.java:131)
at transitions.com.example.huzy_kamz.interview.MainActivity$2$1.run(MainActivity.java:66)
at java.lang.Thread.run(Thread.java:818)
This is how am using ion library to upload my file
public class MainActivity extends AppCompatActivity {
private static final int PICK_FILE_REQUEST = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private String selectedFilePath;
private String SERVER_URL = "http://192.168.43.104:8093/PoliceApp/FileUpload.aspx";
ImageView ivAttachment;
private String UPLOAD_URL ="http://192.168.43.104:8093/PoliceApp/ImageUpload.aspx";
ProgressDialog dialog;
private ImageView imageView;
private EditText firstname_edt,lastname_edt,email_edt,jobtitle_edt,source_edt;
private TextView directory_txt;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView= (ImageView)findViewById(R.id.imageView);
firstname_edt=(EditText)findViewById(R.id.firstname_edt);
lastname_edt=(EditText)findViewById(R.id.lastname_edt);
email_edt=(EditText)findViewById(R.id.email_edt);
jobtitle_edt=(EditText)findViewById(R.id.jobtitle_edt);
source_edt=(EditText)findViewById(R.id.source_edt);
button=(Button)findViewById(R.id.button);
directory_txt=(TextView)findViewById(R.id.directory_txt);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selectedFilePath != null){
dialog = ProgressDialog.show(MainActivity.this,"","Uploading File...",true);
new Thread(new Runnable() {
#Override
public void run() {
//creating new thread to handle Http Operations
uploadFile(selectedFilePath);
// OnSendFileInfo();
}
}).start();
}else{
Toast.makeText(MainActivity.this,"Please choose a File First",Toast.LENGTH_SHORT).show();
}
}
});
}
// Gallery pick
private void showFileChooser() {
Intent intent = new Intent();
//sets the select file to all types of files
intent.setType("*/*");
//allows to select data and return it
intent.setAction(Intent.ACTION_GET_CONTENT);
//starts new activity to select file and return data
startActivityForResult(Intent.createChooser(intent,"Choose File to Upload.."),PICK_FILE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK){
if(requestCode == PICK_FILE_REQUEST){
if(data == null){
//no data present
return;
}
Uri selectedFileUri = data.getData();
selectedFilePath = FilePath.getPath(this,selectedFileUri);
Log.i(TAG,"Selected File Path:" + selectedFilePath);
if(selectedFilePath != null && !selectedFilePath.equals("")){
directory_txt.setText(selectedFilePath);
}else{
Toast.makeText(this,"Cannot upload file to server",Toast.LENGTH_SHORT).show();
}
}
}
}
public void uploadFile(final String selectedFilePath){
final ProgressDialog pd;
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Uploading File...");
pd.setCancelable(false);
pd.show();
final String url_ = "";
Ion.with(MainActivity.this)
.load(SERVER_URL)
.uploadProgressDialog(pd)
.setMultipartParameter("uploaded_file",selectedFilePath)
.setMultipartFile("archive", "application/zip", new File(selectedFilePath))
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
Toast.makeText(MainActivity.this," "+result,Toast.LENGTH_LONG).show();
pd.dismiss();
}
});
}
}
My Method Contain ion library to Upload a PDF file .
public void uploadFile(final String selectedFilePath){
final ProgressDialog pd;
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Uploading ...");
pd.setCancelable(false);
pd.show();
final String url_ = "";
//File file = new File(this.getFilesDir().getAbsolutePath() + "/thesubdirectory/the.zip");
File f = new File(getApplicationContext().getFilesDir().getAbsolutePath()+selectedFilePath);
try {
RandomAccessFile rf = new RandomAccessFile(f, "rw");
rf.setLength(1024 * 1024 * 2);
} catch (Exception e) {
System.err.println(e);
}
File echoedFile = getFileStreamPath("echo");
Ion.with(MainActivity.this)
.load(SERVER_URL)
.uploadProgressDialog(pd)
.setMultipartFile("uploaded_file",f)
.write(echoedFile)
.setCallback(new FutureCallback<File>() {
#Override
public void onCompleted(Exception e, File result) {
try {
Toast.makeText(MainActivity.this, " " + result, Toast.LENGTH_LONG).show();
System.out.println("Error " + result);
pd.dismiss();
} catch (Exception e1) {
System.out.println("Error " + e1);
}
pd.dismiss();
}
});
}
I don't where am wrong please i need your help, where am i wrong.
My back end is working fine , but the problem is in the uploading process.
This is my C# Api to locate the File in a specified folder.
public void FileSave(HttpPostedFile file)
{
try
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/FileStorage"), fileName);
file.SaveAs(path);
}
Response.Write("Upload successfull");
}
catch
{
Response.Write("An Error Ocurred");
}
}
Remove Thread from calling chain as Ion manages that for you and your exception is not related to Ion FYI.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selectedFilePath != null){
dialog = ProgressDialog.show(MainActivity.this,"","Uploading File...",true);
uploadFile(selectedFilePath);
// OnSendFileInfo();
}else{
Toast.makeText(MainActivity.this,"Please choose a File First",Toast.LENGTH_SHORT).show();
}
}
});
You can not use a View in Non Ui thread . So as i am seeing that you are creating a progress dialog inside your upload method which is being called for a thread .That code should be in Main thread only.
Well i have found out a simple way of uploading or posting multipart/form-data with an upload progress bar. may be this could help.
Suppose you server is waiting for the following data :
1.File(PDF,Image,Audio,Video etc.).
2.Name
3.Email
4.Address.
and you want to upload that information once in a URL be it an Absolute URL or a Relative URL, ion library is easy , precise, efficient and much better in this.
STEP 1:
declare your URI
private Uri filePath;
STEP 2:
then Pick the file from your gallery , here it's your choice you identify any kind of files you want a user to view, me here i have identified a PDF file.
on this line intent.setType("application/pdf");
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_PDF_REQUEST);
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
Toast.makeText(getApplicationContext(), "" + filePath, Toast.LENGTH_LONG).show();
}
}
then you can call showFileChooser() in the Button for a click to access your gallery.
STEP 3:
a) Make a method Upload() containing ion library to start the job. If you see in this method , i first declared the file,name, email,address , for file it gets the URI data of a selected file or the path file , then name, email,address, it gets the data from EditText , you have to declare EditText to get the data.
b) Then identify the URL you want to use in Posting mine is url_. but make sure you include POST, in the load section .load("POST",url_).
c) Then you set the file by using .setMultipartFile("File", file) and the rest of the parameters by setting MultipartParameter .setMultipartParameter("Name", name) and so on.
public void Upload() {
String file= FilePath.getPath(this, filePath);
final String name = name_edt.getText().toString();
final String email = email_edt.getText().toString();
final String address = address_edt.getText().toString();
final ProgressDialog pd;
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Logging in...");
pd.setCancelable(false);
pd.show();
final String url_ = "xxxxxxxxxxxxxxx";
final File file = new File(Uri.parse(path).toString());
Ion.with(MainActivity.this)
.load("POST",url_)
.progressDialog(pd)
.setMultipartFile("file", file)
.setMultipartParameter("Name", name)
.setMultipartParameter("Email", email)
.setMultipartParameter("Address.", address)
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
// Toast.makeText(getApplicationContext(),""+file,Toast.LENGTH_LONG).show();
System.out.println("Error " + e);
// Toast.makeText(getApplicationContext(), "Exception : " + e, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(),""+e,Toast.LENGTH_LONG).show();
pd.dismiss();
}
});
}
Then you are good to go , according to your C# API , the file will be able to save in the Folder. Even others use Php or any other language you can create your own Api to save a file in your server folder
Hope it works well.
I currently have a app where the user click on the floating action button and selects a video file, the file is then saved to a different folder. I want to then show thumbnails of all the video's. I've seen a tutorial series where it is done with MediaStore, but then I can't set the path of the uri.
Can someone please point me in the right direction?
Here is my class to open the gallery and save the video to a different path:
public class Activity extends AppCompatActivity {
private static final int pick = 100;
Uri videoUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openGallery();
}
});
}
private void openGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, pick);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == pick) {
try
{
Log.e("videopath","videopath");
AssetFileDescriptor videoAsset = getContentResolver().openAssetFileDescriptor(data.getData(), "r");
FileInputStream fis = videoAsset.createInputStream();
File root=new File(Environment.getExternalStorageDirectory(),"MYFOLDER");
if (!root.exists()) {
root.mkdirs();
}
File file;
file=new File(root,"android_"+System.currentTimeMillis()+".mp4" );
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
videoUri = data.getData();
}
}
}
You can use the ThumbnailUtils class in Android for this purpose.
public static Bitmap createVideoThumbnail (String filePath, int kind)
this method returns a bitmap of the video.
First parameter is the filepath, ie the location of the video file to be passed as String.
Second parameter is the kind of bitmap that you need, there are two types:
MediaStore.Images.Thumbnails.MICRO_KIND which generates thumbnail of size 96 x 96
MediaStore.Images.Thumbnails.MINI_KIND which generates thumbnail of size 512 x 384.
Eg:
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(filePath, Thumbnails.MINI_KIND);
Here is the API docs for further info[Here].
You can easily do it with Glide :
Glide.with(context).load(videoPath).asBitmap().into(imageView);