Null reference when choosing a pdf file to send to server - android

When i choose a PDF file from my device's folders, I keep getting a null reference no matter the path I set it to, I have no idea what is causing this null reference so I need help.
I referred to this to pick the PDF file from the device, but it does not show how to send to the server.
The following is my code.
public void btnOtherFilesOnClick(View v){
int PDF = 1;
Intent i = new Intent();
i.setType("application/pdf");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i, "Select Pdf"), PDF);
btnNo = 6;
}
else if (btnNo == 6 ) {
// File downloads = new File(String.valueOf(Environment.getExternalStorageState()));
//create new file directory object
//File downloads = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Files.FileColumns.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
cursor.close();
picturePath = cursor.getString(columnIndex);
file = new File(picturePath);
copyDatabaseToSD();
createServerPDFStorage();
my picturePath keeps being null even though my filePathColumn[0] is not. I'm trying to send the PDF to SQLite server.

Related

Android pick file from 'Recent'

Below is code which I wrote for pick files from my application
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("*/*");
intent.putExtra("return-data", true);
This code works fine when I pick files through other file manager apps installed. But while picking a file from Recent category it fails while converting selected file Uri to absolute path.
Uri selectedImage = intent.getData();
String[] filePathColumn = {MediaStore.Files.FileColumns.DATA};
Cursor cursor = context.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
In the above code I get picturePath as null whenever I choose file from Recent category. Please help me with this.
But while picking a file from Recent category it fails while converting selected file Uri to absolute path
A Uri is not a file. There is no reliable means of "converting selected file Uri to absolute path". Please use ContentResolver and openInputStream() to use the content backed by the Uri, just like how use an HTTP client API (e.g., HttpUrlConnection) to use the content backed by a URL.

captured image in android is not fetched from another activity

I am having the following: From my first activity, I am taking an image from the camera and then a new activity opens, where the iage should be previewed and uploaded to the server as a FILE argument in httpPOST request.
In my first activity I am using this code:
public void onClick(View v) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE,fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,RESULT_LOAD_IMAGE_FROM_CAMERA);
}
and onMyActivityResult I have:
if (requestCode == RESULT_LOAD_IMAGE_FROM_CAMERA
&& resultCode == RESULT_OK && null != data) {
System.out.println("Photo selected from the camera");
String[] projection = {MediaStore.Images.Media.DATA};
//Uri selectedImage = data.getData();
Cursor cursor = getContentResolver().query(mCapturedImageURI, projection, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//int columnIndex = cursor.getColumnIndex(projection[0]);
//file path of captured image
picturePath = cursor.getString(columnIndex);
//file path of captured image
File f = new File(picturePath);
String filename = f.getName();
Toast.makeText(CommunityMain.this, "Your Path:"+picturePath, 2000).show();
Toast.makeText(CommunityMain.this, "Your Filename:"+filename, 2000).show();
cursor.close();
Intent myIntent = new Intent(CommunityMain.this,PhotoPostActivity.class);
startActivity(myIntent);
The image is saved in the gallery and I do see the picturePath.
When my photoPost activity opens I do have:
f = new File(CommunityMain.picturePath);
System.out.println("Picture path:"+CommunityMain.picturePath);
ImageButton image = (ImageButton) findViewById(R.id.photo1);
image.setImageBitmap(BitmapFactory
.decodeFile(CommunityMain.picturePath));
The picture path is the same, but my ImageButton is not set.
I do get this:
12-08 17:37:22.670: E/BitmapFactory(13357): Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/1386524213331.jpg: open failed: ENOENT (No such file or directory)
but the path is the same with the toast message. What am I missing?
I need to be able also to get the file f since I need that for my HttpPost request.
EDIT: the problem lies in the picturePath. The one I get is different with how the image is being saved?
I see a number like the one above, and the actual path inside the photo has something like IMG_2313.jpg for example.
You should use a different technique. Try to provide the camera with a file url you want the image to be written in like here : https://stackoverflow.com/a/16392587/693752. Next, read that file instead of reading what's provided by the camera.

accessing an existing Amazon S3 bucket

I'm trying to make an app that uploads images to an S3 service. from what I read in the documentation and from the sample project, I saw that it's fairly easy to create a bucket and upload an Image to it and that is no problem, but how do I test if the bucket already exists and connect to it if it does?
my code is taken from the Amazon sample project but I'll add it anyway:
case R.id.button_upload:
if (flag && fileUri != null) {
Uri selectedImage = fileUri;
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
// Put the image data into S3.
try {
s3Client.createBucket(Constants.getPictureBucket());
// I DON"T WANT TO CREATE ONE, I WANT TO CONNECT TO ONE
PutObjectRequest por = new PutObjectRequest(
Constants.getPictureBucket(),
Constants.PICTURE_NAME, new java.io.File(filePath)); // Content
// type
// is
// determined
// by
// file
// extension.
s3Client.putObject(por);
} catch (Exception exception) {
displayAlert("Upload Failure", exception.getMessage());
}
}
break;
any thoughts on how to connect to an existing bucket?
You should not create many buckets. One should be enough and then just have folders in it.
String bucket = "foo";
File file = new File(fileName);
//Just set your directory
PutObjectRequest request = new PutObjectRequest(bucket,"thumbnails/" + fileName, file)
.withCannedAcl(CannedAccessControlList.PublicRead)
.withMetadata(meta);
client.putObject(request);

Store picture on sd directory problem

I'm using the follow code to take a picture using the native camera:
private File mImageFile;
private String mTempImagePath;
public static Uri imageUri;
public void imageFromCamera() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d("fototemp", "No SDCARD");
} else {
mImageFile = new File(Environment.getExternalStorageDirectory()+File.separator+"testFolder", "Pic"+System.currentTimeMillis()+".jpg");
imageUri = Uri.fromFile(mImageFile);
DataClass dc = (DataClass) getApplicationContext();
File tempFile = new File(Environment.getExternalStorageDirectory()+File.separator+"testFolder");
Uri tempUri = Uri.fromFile(tempFile);
dc.setString(DataClass.IMAGE_PATH, tempUri.toString());
Log.d("fototemp", "ImagePath: " + tempUri.toString());
mTempImagePath = mImageFile.getAbsolutePath();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mImageFile));
startActivityForResult(intent, 0);
}
}
The ImagePath I print out in the imageFromCamera() method is: 4file:///file%3A/mnt/sdcard/testFolder
Now when I try to access these foto's by using managedQuery I get a different directory.
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI.toString() gives content://media/external/images/thumbnails
What is the difference between these 2 paths? And how can I get the managedQuery to go to the testFolder map to look for pictures?
edit:
I'm trying to connect:
Uri phoneUriII = Uri.parse(Environment.getExternalStorageDirectory()+File.separator+"testFolder");
imagecursor = managedQuery(phoneUriII, img, null,null, MediaStore.Images.Thumbnails.IMAGE_ID + "");
but this code crashes
Sorry don't really understand your question.
Just send this as the URI path.
Environment.getExternalStorageDirectory()+File.separator+"testFolder"
Also
Check if you have the permissions to write to the sd card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I'm using this function in a couple of projects and it works fine.
/**
* Retrieves physical path to the image from content Uri
* #param contentUri
* #return
*/
private String getRealImagePathFromURI(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);
}

Android: How to Upload Images from the SD Card

In my application, I want to upload the images from the SD card with restricting the user to upload only less than 2mb. How can I accomplish this?
Use following steps:
1) Use the following intent to open gallery with images:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 101);
2) Receive the Uri of selected file in onActivityResult func.
if (requestCode == 101 && data != null) {
Uri selectedImageUri = data.getData();
} else {
Toast toast = Toast.makeText(this, "No Image is selected.",
Toast.LENGTH_LONG);
toast.show();
}
Convert the Uri into a path using following func:
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
After that create a File object from the path and then check the size of file:
File mFile = new File(path);
int length = mFile.length(); // file size in bytes
After that you can simply put an if-else to check the file size restriction and then use multi-part upload process for uploading the file.
you can use this article for multipart upload.

Categories

Resources