i try many way but intent not return path that i want , how can i get absolute path ?
this is which i retrieved
/document/image:29163
code for intent
binding.buttonSetVoiceGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 0);
}
});
when activityresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
Log.d(TAG,data.getData().getPath());
}
}
Try this code for getting absolute path:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
Log.d(TAG,data.getData().getPath());
Object objImg = data.getExtras().get("path");
Log.e("Selected", "" + objImg.toString());
/*--getting image uri from object--*/
Uri selectedImage = Uri.parse(String.valueOf(objImg));
Log.e("Selected Image", "" + selectedImage);
/*--create file object using uri--*/
File myFile = new File(selectedImage.getPath());
String path = myFile.getAbsolutePath();
Log.e("AbsolutePath---", ""+path);
}
}
binding.buttonSetVoiceGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
launcher.launch(intent);
}
});
ActivityResultLauncher<Intent> launcher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK ) {
Intent data = result.getData();
Uri uri= data.getData();
File file = new File(FileMyutils.getPath(getContext(),uri));
}
}
});
public class FileMyutils {
private static final String TAG = "FileUtils";
#WorkerThread
#Nullable
public static String getReadablePathFromUri(Context context, Uri uri) {
String path = null;
if ("file".equalsIgnoreCase(uri.getScheme())) {
path = uri.getPath();
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
path = getPath(context, uri);
}
if (TextUtils.isEmpty(path)) {
return path;
}
Log.d(TAG, "get path from uri: " + path);
if (!isReadablePath(path)) {
int index = path.lastIndexOf("/");
String name = path.substring(index + 1);
String dstPath = context.getCacheDir().getAbsolutePath() + File.separator + name;
if (copyFile(context, uri, dstPath)) {
path = dstPath;
Log.d(TAG, "copy file success: " + path);
} else {
Log.d(TAG, "copy file fail!");
}
}
return path;
}
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
Log.d("External Storage", docId);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(uri)) {
String dstPath = context.getCacheDir().getAbsolutePath() + File.separator + getFileName(context,uri);
if (copyFile(context, uri, dstPath)) {
Log.d(TAG, "copy file success: " + dstPath);
return dstPath;
} else {
Log.d(TAG, "copy file fail!");
}
} else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getFileName(Context context, Uri uri) {
Cursor cursor = context.getContentResolver().query(uri,null,null,null,null);
int nameindex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
cursor.moveToFirst();
return cursor.getString(nameindex);
}
private static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private static boolean isReadablePath(#Nullable String path) {
if (TextUtils.isEmpty(path)) {
return false;
}
boolean isLocalPath;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (!TextUtils.isEmpty(path)) {
File localFile = new File(path);
isLocalPath = localFile.exists() && localFile.canRead();
} else {
isLocalPath = false;
}
} else {
isLocalPath = path.startsWith(File.separator);
}
return isLocalPath;
}
private static boolean copyFile(Context context, Uri uri, String dstPath) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = context.getContentResolver().openInputStream(uri);
outputStream = new FileOutputStream(dstPath);
byte[] buff = new byte[100 * 1024];
int len;
while ((len = inputStream.read(buff)) != -1) {
outputStream.write(buff, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return true;
}
}
Related
I'm writing some code for File chooser Activity using Intent. Code work fine in all Devices except onepluse 3. I check Exception I got NumberFormatException Exception. I try to solve this issue but not getting a proper solution. please give an idea to solve this issue.
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, PICK_FILE_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_FILE_REQUEST && resultCode == RESULT_OK) {
if (resultCode != RESULT_CANCELED) {
if (data == null) {
//no data present
return;
}
Uri selectedFileUri = data.getData();
Log.i("suraj", " FuelExpensesActivity Selected Uri Path:" + selectedFileUri);
String selectedFilePath = FilePath.getPath(this, selectedFileUri);
Log.i("suraj", "FuelExpensesActivity Selected File Path:" + selectedFilePath);
if (selectedFilePath != null && !selectedFilePath.equals("")) {
TextView tvFileName = new TextView(this);
tvFileName.setLayoutParams(new android.view.ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
tvFileName.setPadding(5, 5, 5, 5);
tvFileName.setTextColor(Color.parseColor("#FFFFFF"));
tvFileName.setText(getFileName(selectedFileUri));
parent_layout_doc.addView(tvFileName);
parent_layout_doc.setPadding(5, 5, 5, 5);
imgUrl.add(selectedFilePath);
} else {
Toast.makeText(this, "file not found.....", Toast.LENGTH_SHORT).show();
}
}
}
}
Exception Facing
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=11, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/document/raw:/storage/emulated/0/Download/harley-davidson-vrod-tecnobike-img01~2.jpg flg=0x1 }} to activity {com.riya.product.intranet/com.riya.product.allwance_criteria.FoodActivity}: java.lang.NumberFormatException: For input string: "raw:/storage/emulated/0/Download/harley-davidson-vrod-tecnobike-img01~2.jpg"
at android.app.ActivityThread.deliverResults(ActivityThread.java:4517)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4560)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1744)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6798)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NumberFormatException: For input string: "raw:/storage/emulated/0/Download/harley-davidson-vrod-tecnobike-img01~2.jpg"
at java.lang.Long.parseLong(Long.java:590)
at java.lang.Long.valueOf(Long.java:804)
at methodclass.FilePath.getPath(FilePath.java:46)
at com.riya.product.allwance_criteria.FoodActivity.onActivityResult(FoodActivity.java:1415)
at android.app.Activity.dispatchActivityResult(Activity.java:7272)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4513)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4560)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1744)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6798)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
FilePath.java
public class FilePath {
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/"
+ split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] { split[1] };
return getDataColumn(context, contentUri, selection,
selectionArgs);
}
}
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
// MediaStore (and general)
}
return null;
}
public static String getDataColumn(Context context, Uri uri,
String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = { column };
try {
cursor = context.getContentResolver().query(uri, projection,
selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri
.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri
.getAuthority());
}
}
I try below solution also but not solve my issue
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
if (!TextUtils.isEmpty(id)) {
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
try {
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} catch (NumberFormatException e) {
e.printStackTrace();
Log.e("suraj", "Exception in FilePath "+ e.getMessage());
return null;
}
}
}
}
When i press in "addnew" button, the app crash.
The problem is in this part of code:
Boton cbt = new Boton(bt, "","");
listBts.add(cbt);
SharedPreferences sharedPreferences = getSharedPreferences("Array", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
Type type = new TypeToken<BotonClass>() {
}.getType();
String json = gson.toJson(listBts);
editor.remove("Botones").commit();
editor.putString("Botones", json);
editor.commit();
ALL THE CODE:
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
String Tag;
FlexboxLayout fl;
int w;
int h;
ImageView im;
Button curBt;
Boolean delete;
class Boton{
Button bt;
String path;
String fname;
Boton(Button bt, String path, String fname){
this.bt = bt;
this.path = path;
this.fname = fname;
}
}
ArrayList<Boton> listBts;
ArrayList<BotonClass> listClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Chequear_Permisos();
listBts = new ArrayList<>();
listClass = new ArrayList<>();
fl = findViewById(R.id.fl);
DisplayMetrics dm = this.getResources().getDisplayMetrics();
w = Math.round(dm.widthPixels);
h = Math.round(dm.heightPixels);
cargar_bts_agregados();
im = findViewById(R.id.im);
im.getLayoutParams().width = w;
im.getLayoutParams().height = w/3;
}
void cargar_bts_agregados() {
SharedPreferences sharedPreferences = getSharedPreferences("Array", MODE_PRIVATE);
class Boton{
Button bt;
String path;
String fname;
}
Type type = new TypeToken<List<Boton>>() {
}.getType();
String json = sharedPreferences.getString("Botones", "");
Gson gson = new Gson();
if(gson.fromJson(json,type)!= null)
listBts = gson.fromJson(json, type);
if (listBts != null)
for (int i = 0; i < listBts.size(); i++) {
}
}
void Chequear_Permisos(){
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.MANAGE_DOCUMENTS) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.MANAGE_DOCUMENTS}, 1);
}
void config_bt(Button bt, String path, String fname){
bt.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
cargar_cancion(v);
return true;
}
});
bt.getLayoutParams().width = w/2;
bt.getLayoutParams().height = (w/2)/2;
if(fname != "")
bt.setText(fname);
}
public void cargar_cancion(View v){
Tag = v.getTag().toString();
curBt = (Button)v;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent,"Select file or dir"), 1);
setResult(Activity.RESULT_OK);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
class Boton{
Button bt;
String path;
String fname;
}
String path = data.getDataString();
String fname = getFileName(Uri.parse(path));
curBt.setText(fname);
Boton b = new Boton();
/*
b.bt = curBt;
b.path = path;
b.fname = fname;*/
//////lb.get(curBt.getId()).path = path;
//////lb.get(curBt.getId()).fname = fname;
SharedPreferences sharedPreferences = getSharedPreferences("Array", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(listBts);
editor.putString("Botones", json);
editor.commit();
}
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void play(View v){
/*if(Integer.parseInt(v.getTag().toString()) > 8 && delete == true){
String pos = v.getTag().toString();
SharedPreferences shPaths = getSharedPreferences("Paths", MODE_PRIVATE);
SharedPreferences.Editor editPath = shPaths.edit();
SharedPreferences shBts = getSharedPreferences("BtNames", MODE_PRIVATE);
SharedPreferences.Editor editorBts = shBts.edit();
editPath.putString(pos, "deleted");
editorBts.putString(pos, "deleted");
editorBts.commit();
editPath.commit();
Log.d("MESAJE", v.getTag().toString());
Log.d("MESAJE", shPaths.getString(String.valueOf(v.getTag().toString()), "_"));
FlexboxLayout fl = findViewById(R.id.fl);
fl.removeView(v);
delete = false;
}*/
SharedPreferences sharedPreferences = getSharedPreferences("Paths", MODE_PRIVATE);
String filePath = sharedPreferences.getString(v.getTag().toString(), "");
Uri uri = Uri.parse(filePath);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(getRealPathFromURI_API19(this, Uri.parse(filePath)));
mediaPlayer.prepare();
mediaPlayer.start();
Button bt = (Button) v;
bt.setText(getFileName(uri));
} catch (IOException e) {
e.printStackTrace();
//Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
catch (Exception e){
//Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static String getRealPathFromURI_API19(Context context, Uri uri) {
String filePath = "";
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
if (Build.VERSION.SDK_INT > 20) {
//getExternalMediaDirs() added in API 21
File extenal[] = context.getExternalMediaDirs();
if (extenal.length > 1) {
filePath = extenal[1].getAbsolutePath();
filePath = filePath.substring(0, filePath.indexOf("Android")) + split[1];
}
}else{
filePath = "/storage/" + type + "/" + split[1];
}
return filePath;
}
} else if (isDownloadsDocument(uri)) {
// DownloadsProvider
final String id = DocumentsContract.getDocumentId(uri);
//final Uri contentUri = ContentUris.withAppendedId(
// Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
String result = cursor.getString(index);
cursor.close();
return result;
}
} finally {
if (cursor != null)
cursor.close();
}
} else if (DocumentsContract.isDocumentUri(context, uri)) {
// MediaProvider
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String[] ids = wholeID.split(":");
String id;
String type;
if (ids.length > 1) {
id = ids[1];
type = ids[0];
} else {
id = ids[0];
type = ids[0];
}
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{id};
final String column = "_data";
final String[] projection = {column};
Cursor cursor = context.getContentResolver().query(contentUri,
projection, selection, selectionArgs, null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndex(column);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
}
return filePath;
} else {
String[] proj = {MediaStore.Audio.Media.DATA};
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
if (cursor.moveToFirst())
filePath = cursor.getString(column_index);
cursor.close();
}
return filePath;
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public void addnew(Button bt, String fname, String path) {
fl.addView(bt);
config_bt(bt, fname, path);
}
public void addnew(View v){
if(listBts == null)
Log.d("MESAJE", "MMMMMMM");
final Button bt = new Button(this);
bt.setText("Cargar");
bt.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void onClick(View v) {
play(bt);
}
});
bt.setTag(contar_bts());
fl.addView(bt);
/*
BotonClass bbc = new BotonClass(bt, "","");
listClass.add(bbc);
listClass.get(0);
cbt.bt = bt;
cbt.path = "";
cbt.fname = "";*/
Boton cbt = new Boton(bt, "","");
listBts.add(cbt);
SharedPreferences sharedPreferences = getSharedPreferences("Array", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
Type type = new TypeToken<BotonClass>() {
}.getType();
String json = gson.toJson(listBts);
editor.remove("Botones").commit();
editor.putString("Botones", json);
editor.commit();
config_bt(bt,"","");
}
public int contar_bts(){
if(listBts == null || listBts.size() == 0)
return 0;
int c =Integer.parseInt(listBts.get(listBts.size()-1).bt.getTag().toString());
return c;
}
public void Elimnar_bt(View v){
delete = true;
}
}
For the past couple of days, I've been trying to figure out what I'm doing wrong. Whenever the user uploads a file (non-image), and I try to convert the URI object into a file and then into a byte array, I get this error:
java.io.FileNotFoundException: /document/2301 (No such file or directory)
I had obviously uploaded something because it was showing me some sort of path. Here is my code:
MAIN ACTIVITY-
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.MediaFormat;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else {
getFile();
}
}
public void getFile() {
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getFile();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedFile = data.getData();
Log.i("Path", selectedFile.getPath());
File file = new File(selectedFile.getPath());
byte[] b = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
for (int i = 0; i < b.length; i++) {
System.out.print((char)b[i]);
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
}
catch (IOException e1) {
System.out.println("Error Reading The File.");
e1.printStackTrace();
}
}
}
}
Any sort of help is appreciated!
The file does not exist on Internal Storage. Use below code to solve the issue.
public static String getPath(Context context, Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else
if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = { column };
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
Use the below code to browse the file in any format.
public void browseClick() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
//intent.putExtra("browseCoa", itemToBrowse);
//Intent chooser = Intent.createChooser(intent, "Select a File to Upload");
try {
//startActivityForResult(chooser, FILE_SELECT_CODE);
startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"),FILE_SELECT_CODE);
} catch (Exception ex) {
System.out.println("browseClick :"+ex);//android.content.ActivityNotFoundException ex
}
}
Then get that file path in the onActivityResult like below.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_SELECT_CODE) {
if (resultCode == RESULT_OK) {
try {
Uri uri = data.getData();
if (filesize >= FILE_SIZE_LIMIT) {
Toast.makeText(this,"The selected file is too large. Selet a new file with size less than 2mb",Toast.LENGTH_LONG).show();
} else {
String mimeType = getContentResolver().getType(uri);
if (mimeType == null) {
String path = getPath(this, uri);
if (path == null) {
filename = FilenameUtils.getName(uri.toString());
} else {
File file = new File(path);
filename = file.getName();
}
} else {
Uri returnUri = data.getData();
Cursor returnCursor = getContentResolver().query(returnUri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
filename = returnCursor.getString(nameIndex);
String size = Long.toString(returnCursor.getLong(sizeIndex));
}
File fileSave = getExternalFilesDir(null);
String sourcePath = getExternalFilesDir(null).toString();
try {
copyFileStream(new File(sourcePath + "/" + filename), uri,this);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private void copyFileStream(File dest, Uri uri, Context context)
throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = context.getContentResolver().openInputStream(uri);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
is.close();
os.close();
}
}
After this you can open this file from your application external storage where you saved the file with appropriate action.
Courtesy: https://stackoverflow.com/a/36129285/6050536
private String fileToBase64Conversion(Uri file) {
InputStream inputStream = null;//You can get an inputStream using any IO API
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
inputStream = context.getContentResolver().openInputStream(file);
byte[] buffer = new byte[8192];
int bytesRead;
Base64OutputStream outputBase64 = new Base64OutputStream(output, Base64.DEFAULT);
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputBase64.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
outputBase64.close();
} catch (Exception ex) {
}
return outputBase64.toString();
}
In my app, I am using webview to render a webpage from which I need to upload multiple files to the server. OnShowFileChooser() (for lollipop and upper versions) is working fine but onOpenFileChooser() (for other lower android versions). OnshowFileChooser() method not working if I pass an Uri array(Uri[]) to its onValueCallback(). It throws the classCastException. Below is my code which i have used for performing the required opertation. I need a solution to upload multiple file using webview which will work for all android versions.
public class ChromeClient extends WebChromeClient {
// For Android 5.0
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
contentSelectionIntent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
contentSelectionIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri[]> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri[]> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri[]> uploadMsg) {
openFileChooser(uploadMsg, "");
}
}
This is the onActivityResult code
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
if (data.getData() != null) {
String dataString = data.getDataString();
if (dataString != null) {
// results = new Uri[]{Uri.parse(dataString)};
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(Uri.parse(dataString.replace("%3A", ":")));
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String type = wholeID.split(":")[0];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
results = new Uri[]{Uri.parse("file:" + filePath)};
}
cursor.close();
}
} else {
if (data.getClipData() != null) {
ClipData clipData = data.getClipData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
results = new Uri[clipData.getItemCount()];
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item image = clipData.getItemAt(i);
Uri uri = image.getUri();
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String type = wholeID.split(":")[0];
String contentUri;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.DATA;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.DATA;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.DATA;
}
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
results[i] = Uri.parse("file:" + filePath);
}
}
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result[] = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
if (data.getData() != null)
result[0] = data.getData();
else {
if (data.getClipData() != null) {
result = new Uri[data.getClipData().getItemCount()];
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
result[i] = data.getClipData().getItemAt(i).getUri();
}
} else {
result = null;
}
}
// retrieve from the private variable if the intent is null
//result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
this is the Error report
i found a code about gallery picker and it pick photos from google images. But i want to pick photos from normal gallery. Here is the code :
public class ImageCrop {
private static final String TAG = "ImageCrop";
private static final boolean REMOVE_TEMP_FILE = true;
private static final boolean DEBUG = false;
Context context;
public static final int PICK_FROM_CAMERA = 0;
public static final int PICK_FROM_ALBUM = 1;
public static final int PERMISSION_FROM_CAMERA = 3;
private static final int PHOTO_SIZE = 1000;
private static final String ACTIVITY_NAME_PHOTOS = "com.google.android.apps.photos";
private static final String ACTIVITY_NAME_PLUS = "com.google.android.apps.plus";
private static boolean mUseActivityPhoto = false;
private static boolean mUseActivityPlus = false;
private static Uri mImageCaptureUri;
private static Bitmap mCropBitmap;
private static String mTempImagePath;
private static int mLastAction = PICK_FROM_CAMERA;
private static final String CAMERA_TEMP_PREFIX = "camera_";
private static final String CROP_TEMP_PREFIX = "crop_";
private static final String IMAGE_EXT = ".png";
public static void checkPackages(Activity context, Intent intentPhoto) {
final PackageManager pm = context.getPackageManager();
final Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
mUseActivityPhoto = false;
mUseActivityPlus = false;
final List<ResolveInfo> infos = pm.queryIntentActivities(intent, PackageManager.MATCH_ALL);
for (ResolveInfo info : infos) {
if(info.activityInfo.packageName.equals(ACTIVITY_NAME_PHOTOS)) {
final List<ResolveInfo> photoInfos = pm.queryIntentActivities(intentPhoto, PackageManager.MATCH_ALL);
for (ResolveInfo photoInfo : photoInfos) {
if(photoInfo.activityInfo.packageName.equals(ACTIVITY_NAME_PHOTOS)) {
Log.d(TAG,"mUseActivityPhoto TRUE");
mUseActivityPhoto = true;
break;
}
}
}
else if(info.activityInfo.packageName.equals(ACTIVITY_NAME_PLUS)) {
final List<ResolveInfo> photoInfos = pm.queryIntentActivities(intentPhoto, PackageManager.MATCH_ALL);
for (ResolveInfo photoInfo : photoInfos) {
if(photoInfo.activityInfo.packageName.equals(ACTIVITY_NAME_PLUS)) {
Log.d(TAG,"mUseActivityPlus TRUE");
mUseActivityPlus = true;
break;
}
}
}
}
}
public static void takeCameraAction(Activity context) {
if(DEBUG)
Log.d(TAG, "takeCameraAction");
if (ImageCrop.checkPermissions(context)) {
ImageCrop.doTakeCameraAction(context);
} else {
mLastAction = ImageCrop.PICK_FROM_CAMERA;
}
}
public static void takeAlbumAction(Activity context) {
if(DEBUG)
Log.d(TAG, "takeAlbumAction");
if(ImageCrop.checkPermissions(context)) {
ImageCrop.doTakeAlbumAction(context);
}
else {
mLastAction = ImageCrop.PICK_FROM_ALBUM;
}
}
private static void doTakeCameraAction(Activity context) {
if(DEBUG)
Log.d(TAG, "doTakeCameraAction");
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final String url = CAMERA_TEMP_PREFIX + String.valueOf(System.currentTimeMillis()) + IMAGE_EXT;
final File file = new File(Environment.getExternalStorageDirectory(), url);
mTempImagePath = file.getAbsolutePath();
mImageCaptureUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
context.startActivityForResult(intent, PICK_FROM_CAMERA);
}
private static void doTakeAlbumAction(Activity context) {
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction");
final Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(MediaStore.Images.Media.CONTENT_TYPE);
checkPackages(context, intent);
if(mUseActivityPhoto) {
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction setPackage ACTIVITY_NAME_PHOTOS");
intent.setPackage(ACTIVITY_NAME_PHOTOS);
}
else if(mUseActivityPlus) {
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction setPackage ACTIVITY_NAME_PLUS");
intent.setPackage(ACTIVITY_NAME_PLUS);
}
context.startActivityForResult(intent, ImageCrop.PICK_FROM_ALBUM);
}
private static void removeTempFile() {
// 캡쳐 파일 삭제
if(mImageCaptureUri != null) {
final String capturePath = mImageCaptureUri.getPath();
if(capturePath != null) {
Log.w(TAG, "removeTempFile capturePath=" + capturePath);
final File captureFile = new File(capturePath);
if(captureFile != null) {
if (captureFile.getAbsoluteFile().exists()) {
captureFile.delete();
}
}
}
}
if(mTempImagePath != null) {
Log.w(TAG, "removeTempFile mTempImagePath=" + mTempImagePath);
final File tempFile = new File(mTempImagePath);
if(tempFile != null) {
if(tempFile.getAbsoluteFile().exists()) {
tempFile.delete();
}
}
}
}
private static void removeDataFile(Intent data) {
if(data == null) {
Log.w(TAG, "removeDataFile data == null");
return;
}
if(data.getData() == null) {
Log.w(TAG, "removeDataFile data.getData() == null");
return;
}
final String dataPath = data.getData().getPath();
if(dataPath == null) {
Log.w(TAG, "removeDataFile dataPath == null");
return;
}
Log.w(TAG, "removeDataFile dataPath=" + dataPath);
final File dataFile = new File(dataPath);
if(dataFile == null) {
Log.w(TAG, "removeDataFile dataFile == null");
return;
}
if(dataFile.getAbsoluteFile().exists()) {
dataFile.delete();
}
}
private static File cropFileFromPhotoData(Activity context, Intent data) {
if(DEBUG)
Log.d(TAG, "cropFileFromPhotoData");
if(data.getData() == null) {
Log.e(TAG, "cropFileFromPhotoData data.getData() == null");
return null;
}
final String dataPath = data.getData().getPath();
if (dataPath == null) {
Log.e(TAG, "cropFileFromPhotoData dataPath == null");
return null;
}
File dataFile = null;
if(dataPath.startsWith("/external")) {
final Uri dataUri = Uri.parse("content://media"+dataPath);
final String dataFilePath = getRealPathFromURI(context, dataUri);
dataFile = new File(dataFilePath);
boolean exist = dataFile.exists();
long length = dataFile.length();
if(DEBUG)
Log.d(TAG, "cropFileFromPhotoData dataFilePath=" + dataFilePath + " exist="+exist + " length=" +length);
}
else {
dataFile = new File(dataPath);
boolean exist = dataFile.exists();
long length = dataFile.length();
if(DEBUG)
Log.d(TAG, "cropFileFromPhotoData dataPath=" + dataPath + " exist="+exist + " length=" +length);
}
return dataFile;
}
public static void pickFromCamera(Activity context, Intent data) {
if(DEBUG)
Log.d(TAG, "pickFromCamera => launchCropActivity");
if(mTempImagePath == null || mTempImagePath.isEmpty()) {
Log.e(TAG, "pickFromCamera mTempImagePath error");
return;
}
}
public static String getRealPathFromURI(Activity context, Uri contentUri) {
Cursor cursor = null;
final String[] proj = { MediaStore.Images.Media.DATA };
String ret = null;
try {
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
final int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
ret = cursor.getString(column_index);
}
catch(Exception e) {
Log.e(TAG, "getRealPathFromURI exception");
return null;
}
if (cursor != null) {
cursor.close();
}
return ret;
}
if(readEnable && writeEnable && cameraEnable) {
switch(mLastAction) {
case ImageCrop.PICK_FROM_CAMERA:
if(DEBUG)
Log.d(TAG, "doTakeCameraAction");
ImageCrop.doTakeCameraAction(context);
break;
case ImageCrop.PICK_FROM_ALBUM:
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction");
ImageCrop.doTakeAlbumAction(context);
break;
}
}
}
}
I want to use this way to pick photos:
private void selectCover() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, getText(R.string.label_select_img)), SELECT_COVER);
}
But i can't convert this to normal gallery. How to solve this? Thanks
You can use this, it will open only Gallery :
public void handleGallery(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_CODE_GALLERY);
}
public void handleCamera(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
} catch (Exception e) {
Log.d("error", "cannot take picture", e);
}
}
Then onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
Bitmap bitmap;
switch (requestCode) {
case REQUEST_CODE_GALLERY:
try {
Uri uri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
Bitmap bitmapScaled = Bitmap.createScaledBitmap(bitmap, 800, 800, true);
Drawable drawable=new BitmapDrawable(bitmapScaled);
mImage.setImageDrawable(drawable);
mImage.setVisibility(View.VISIBLE);
mImageString=HelperUtils.encodeTobase64(bitmap);
} catch (IOException e) {
Log.v("galeri", "hata var : "+e.getMessage());
}
} catch (Exception e) {
Log.v("kamera", "hata var : "+e.getMessage());
}
break;
case REQUEST_CODE_TAKE_PICTURE:
bitmap = (Bitmap) data.getExtras().get("data");
mImage.setImageBitmap(bitmap);
mImage.setVisibility(View.VISIBLE);
mImageString=HelperUtils.encodeTobase64(bitmap);
break;
}
super.onActivityResult(requestCode, resultCode, data);
}