Android Create String from XML-filepath - android

In my app the user can select a xml file via an Intent:
Selecting:
Intent chooseFileXML = new Intent(Intent.ACTION_GET_CONTENT);
chooseFileXML.setType("text/xml");
Intent intentXML = Intent.createChooser(chooseFileXML, getString(R.string.importXMLDatei));
startActivityForResult(intentXML, REQUEST_CODE_IMPORT_XML_FILE);
Receiving:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
switch (requestCode){
case REQUEST_CODE_IMPORT_XML_FILE:
if(resultCode == RESULT_OK){
Uri uri = data.getData();
String filePath = uri.getPath();
File fl = new File(filePath);
//Get xml-code from file and put it in a String
FileInputStream fin = null;
try {
fin = new FileInputStream(fl);
BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
System.out.println(sb.toString());
fin.close();
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
}
I receive the correct filepath. But in this line: fin = new FileInputStream(fl); I get this error:
java.io.FileNotFoundException: /document/primary:Android/data/com.oli.myapp/Files/test.xml: open failed: ENOENT (No such file or directory)

Actually problem in file path .your file path is not vaild so find real path of file
String filePath = getRealPathFromURI(uri);
getRealPathFromURI methods
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}

Related

Image path return null in Android

I want to get image path and upload to the server.
Here i successfully read image from gallery and set into image view but image path return null.
public void onActivityResult(int requestCode, int resultCode, Intent data)
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
// Get the url from data
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getRealPathFromURI(getActivity(), selectedImageUri);
Log.i(TAG, "IMAGE" + path);
Log.d("INFO", selectedImageUri.toString());
// Set the image in ImageView
profilepicture.setImageURI(selectedImageUri);
}
}
}
}
/* Get the real path from the URI */
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Delete getRealPathFromURI(), as it is not going to work reliably.
Instead, use your favorite image-loading library (e.g., Picasso, Glide) to load the image from the Uri.
Or, in a worst-case scenario, use getContentResolver().openInputStream() to get an InputStream on the content identified by the Uri, then pass that stream to BitmapFactory.decodeStream(). Just do this I/O on a background thread, please (which image-loading libraries will handle for you, among other benefits).
Update your method getRealPathFromURI:
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String imagePath = cursor.getString(column_index);
if (imagePath == null) {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "New");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File file;
String path = "img_" + timeStamp + ".jpg";
file = new File(mediaStorageDir.getPath() + File.separator + path);
imagePath = file.getAbsolutePath();
ParcelFileDescriptor parcelFileDescriptor = null;
try {
parcelFileDescriptor = context.getContentResolver()
.openFileDescriptor(contentUri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory
.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
saveBitmapToPath(image, imagePath);
} catch (IOException e) {
e.printStackTrace();
}
}
return imagePath;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Use this function to convert String URL to Bitmap
public Bitmap getImage(String url) {
try {
BufferedInputStream bis = new BufferedInputStream(new
URL(url).openStream(), BUFFER_IO_SIZE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos,
BUFFER_IO_SIZE);
copy(bis, bos);
bos.flush();
return BitmapFactory.decodeByteArray(baos.toByteArray(), 0,
baos.size());
} catch (IOException e) {
Log.d(TAG, "loadImageFromArrayList: IMAGE DOWNLOAD FAILED!" +e);
}
return null;
}
try this
String path = yourAndroidURI.toString() // "/mnt/sdcard/FileName.mp3"
File file = new File(new URI(path));

Not able to copy image using ACTION_GET_CONTENT

I am trying to copy image using below code:
Intent intentImage = new Intent();
intentImage.setType("image/*");
intentImage.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intentImage, 10);
With this i am able to open all image content.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 10) {
if (resultCode != RESULT_OK) return;
Uri selectedImageUri = data.getData();
try {
String selectedImagePath1 = getPath(selectedImageUri);
File file = new File(selectedImagePath1);
String fna = file.getName();
String pna = file.getParent();
File fileImage = new File(pna, fna);
copyFileImage(fileImage, data.getData());
} catch (Exception e) {
}
}
}
private void copyFileImage(File src, Uri destUri) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(getContentResolver().openOutputStream(destUri));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != -1);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now i am successfully get path and name of the image .
Now when i run the above code then it gives me error of requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission().
so i have put the permission in manifest :
i have also defined the permission for read and write internal/external storage.
But still i am getting this error.
How can i copy image ?
Select picture using below code
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), 1);
this will open gallery, after selecting pic you will get selected pic uri in below code
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch(requestCode) {
case 1:
if(resultCode == RESULT_OK)
{
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
File sel = new File(selectedImagePath);
Bitmap bitmap = BitmapFactory.decodeFile(sel.getAbsolutePath());
imageView1.setImageBitmap(bitmap);
Bitmap resized = Bitmap.createScaledBitmap(bitmap, 600,370, true);
ByteArrayOutputStream blob = new ByteArrayOutputStream();
resized.compress(Bitmap.CompressFormat.JPEG, 100, blob);
String StrBase64 = Base64.encodeToString(blob.toByteArray(), Base64.DEFAULT);
imageView1.setImageBitmap(resized);
// Toast.makeText(getApplicationContext(), ""+selectedImagePath, Toast.LENGTH_LONG).show();
}
break;
}
}
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}
add permission in manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
this way you will get selected image in Base64 to string
Try this code-
Image will copy in SaveImage folder in sd card
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch(requestCode) {
case 1:
if(resultCode == RESULT_OK)
{
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
File sel = new File(selectedImagePath);
Bitmap bitmap = BitmapFactory.decodeFile(sel.getAbsolutePath());
imageView1.setImageBitmap(bitmap);
SaveImage(bitmap);
}
break;
}
}
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/SaveImage");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Unable to read picked file android

I am using intent to let user select a video file for processing using the code below
Intent mediaIntent = new Intent(Intent.ACTION_PICK,MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
mediaIntent.setType("video/*"); //set mime type as per requirement
mediaIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(mediaIntent,4);
And I get the result from the intent as
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == 4 && resultCode == Activity.RESULT_OK) {
String filePath = "";
Uri _uri = data.getData();
filePath=getRealPathFromURI(_uri);
File org = new File(filePath);
File news=new File(saveFile());
copy (org,news);
}
} catch (Exception ex) {
Log.e("RESULT","ERROR",ex);
}
}
I am unable to read/copy the user selected file in the above code. What could be the issue? Also I checked the path returned by Intent from other file manager application and couldn't find the file in path.

Not able to get file path when using GoogleDrive in android version 4.4.2

In my android application, i have used google drive to pick images and files to my application, it works perfectly in all API version except 4.4.2, whenever i tried to pick image or file i can get the file name but not able to get file path, it always returns empty path
My code :
// Get real path from Google Drive
public String getPathfromGoogleDrive(Intent data, Uri contentURI) {
if (contentURI == null) {
return null;
}
String[] filePathColumn = { MediaStore.Images.Media.DATA };
String mCurrentPhotoPath = new String();
Cursor cursor = null;
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
LogUtil.d("currentapiVersion" + currentapiVersion);
if (currentapiVersion == 19) {
String wholeID = DocumentsContract.getDocumentId(contentURI);
// Split at colon, use second item in the array
String id = wholeID.split(";")[0];
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
cursor = getActivity().getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
filePathColumn, sel, new String[] { id }, null);
LogUtil.d("Cursor Count" + cursor.getCount());
if (cursor.getCount() > 0 && cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mCurrentPhotoPath = cursor.getString(columnIndex);
cursor.close();
}
}
My Intent :
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion == 19) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
String strType = "*/*";
intent.setDataAndType(null, strType);
startActivityForResult(intent, Gallery);
} else {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setPackage("com.google.android.apps.docs");
String strType = "*/*";
intent.setDataAndType(null, strType);
startActivityForResult(intent, Gallery);
}
Please correct me if i have did any mistake
Thanks in advance
Instead of getting file real path, we can use input stream as like below
Bitmap bitmap = null;
InputStream input = null;
try {
input = getActivity().getContentResolver().openInputStream(selectedImageURI);
bitmap = BitmapFactory.decodeStream(input);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
To Get File from drive and write that into locale(sd card)
sourceuri - your cnontent uri
destination - path where you want to save in sd card
public boolean savefile(String name, Uri sourceuri, String destination)
throws IOException {
// String sourceFilename = sourceuri.getPath();
int originalsize = 0;
InputStream input = null;
try {
input = getContentResolver().openInputStream(sourceuri);
Log.Logger().finest("input in profileview Activity" + input);
} catch (FileNotFoundException e) {
e.printStackTrace();
filenotfoundexecption = true;
}
try {
originalsize = input.available();
Log.Logger().finest(
"Profile view activity originalsize" + originalsize);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(input);
bos = new BufferedOutputStream(new FileOutputStream(
destination, false));
byte[] buf = new byte[originalsize];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != -1);
} catch (IOException e) {
Mint.logException(e);
filenotfoundexecption = true;
return false;
}
} catch (NullPointerException e1) {
Mint.logException(e1);
filenotfoundexecption = true;
}
/*
* String[] cmd = new String[] { "logcat", "-f", GridViewDemo_LOGPATH,
* "-v", "time", "ActivityManager:W", "myapp:D" };
*
* Runtime.getRuntime().exec(cmd);
*/
return true;
}

How to read all content of file from file path in android?

I am getting the file path .How to get content of file. Then I need to send to javascript.
I need all data in string or stringbuilder so that I can send in javascipt.can you please tell me how to read content of file with path
------------------FilePath------------------/storage/sdcard0/Download/a.txt
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (mUploadMessage == null)
return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
if (result!=null){
String filePath = null;
if ("content".equals(result.getScheme())) {
Cursor cursor = this.getContentResolver().query(result, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
filePath = cursor.getString(0);
cursor.close();
} else {
filePath = result.getPath();
System.out.println("------------------FilePath------------------"+filePath);
// content send to java script
//String msgToSend = Msg.getText().toString();
// web.loadUrl("javascript:loadData(\""+msgToSend+"\")");
// web.loadUrl("javascript:loadData()");
filePath = result.getPath();
}
Uri myUri = Uri.parse(filePath);
mUploadMessage.onReceiveValue(myUri);
} else {
mUploadMessage.onReceiveValue(result);
}
mUploadMessage = null;
}
}
If you have the filePath you can try something like the following:
File file = new File(filePath);
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//Exception-handling
}

Categories

Resources