Downloading Object from Android's Amazon s3 makes file unreadable - android

Currently, I'm trying to download a file I have in a bucket on Amazon s3. I'm using this code to debug, because I always get an EN0ENT / file not found when I try to read from the file in the end.
String str_FilePathInDevice = "/sdcard/" + "/"
+ "RestoreFolderName" + "/" + "filname.extention";
File file = new File(str_FilePathInDevice);
String str_Path = file.getPath().replace(file.getName(), "");
File filedir = new File(str_Path);
try {
filedir.mkdirs();
file.createNewFile();
} catch (Exception ex1) {
}
System.out.println(file.toString());
System.out.println(file.canRead());
System.out.println(file.length());
TransferObserver observer2 = transferUtility.download(
"arabianbucket", /* The bucket to upload to */
"demo.txt", /* The key for the uploaded object */
file /* The file where the data to upload exists*/
);
System.out.println(file.toString());
System.out.println(file.canRead());
System.out.println(file.length());
the file.canread() ends up being flipped from true to false after the transferutility.download link. I'm not particularly sure why this is the case. Does anyone know how to successfully read from an object in Amazon s3? In my manifest, I've already flipped the permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Thank you!

TransferUtility offers asynchronous transfers. In your code transferUtility.download initiates a download and the download happens in a background thread so as not to block the main thread. I don't recommend any file operation until the transfer is done. You can attach a listener to the observer and listens to status and progress changes. See Store and Retrieve Files with Amazon S3 for more information.

Related

Android - Missing files between file explorers

I'm trying to access the two files, Spring v2.json and Test.json, in my Android app. However, I will add them using Windows with my phone connected, but when I run my app, the file seems to disappear.
Getting the file
File file = new File(getExternalFilesDir(null), "Spring v2.json");
Check is the file exists
if (file.exists()) {
TransferObserver observer = transferUtility.download(
"easelbucket", // bucket to download from
"sections/" + objectKey, // key for object to be downloaded
file // file to download object to
);
} else {
Toast.makeText(this, "File does not exist", Toast.LENGTH_SHORT).show();
return null;
}
I know that the file stops existing because (1) the if statement enters the else block, and (2) the app crashes when it attempts to use the result of the file.
File file = new File(getExternalFilesDir(null), "/Spring v2.json")
You forget slash before filename.
Also check if
.canRead();
and
.canExecute();

Android Studios Serialization. Attempt to get length of null array

Okay, so in my project I am trying to serialize a chess game by writing to a folder named data. I did this in eclipse, and it was able to work. However, when I brought it into android studios I got the error of trying to get the length of a null array. Here is my method:
public static void writeData() throws IOException {
System.out.println("WRiting data");
File folder = new File("data" + File.separator);
folder.mkdir();
String[] directories = folder.list();
for (String name : directories) { //error here
File ff = new File(folder + File.separator + name);
if (ff.isDirectory()) {
deleteDirectory(ff);
}
}
//add all user data
for (game u : info.games) {
File f = new File("data" + File.separator + u.name); //make a file with user name
f.mkdir(); //make the file a directory
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(f + File.separator + "game-state"));
//create stream with file name at the end
oos.writeObject(u);
//write objects
oos.close();
}
}
Also, I looked at previous questions and changed my manifest file to allow for the permissions of writing and reading data.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The app does not crash when I read data. However, it crashes when I try to write data. Going crazy over here. Thank you for your help.
This may be due to marshmellow permission request ,you have to call permission request at runtime .
go through link
https://developer.android.com/training/permissions/requesting.html

Android - Unable to save images

I'm currently trying to get image saving to happen using the device built in camera. This is the code I'm using:
PackageManager pm = getActivity().getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// * Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(pm) != null) {
// * Create the File where the photo should go
File photoFile = null;
try {
photoFile = ImageFileHelper.createImageFile();
} catch (IOException ex) {
// * Error occurred while creating the File
Timber.d("An error occurred while creating file: " + ex.getLocalizedMessage());
}
// * Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PICTURE);
} else {
alertUserOfError(0);
}
}
} else {
// * Inform user that they need a camera
// * to use this feature
alertUserOfError(1);
}
And here is the ImageFileHelper.createImageFile() function:
public static File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyy-MM-dd.ss", Locale.getDefault()).format(new Date());
String imageFileName = "Original_Avatar_" + timeStamp;
// * Create MyApp folder if not exist
String path = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_PICTURES;
File dir = new File(path + "/MyApp/Originals/");
dir.mkdirs();
File image = File.createTempFile(
imageFileName, /* prefix */
".png", /* suffix */
dir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
filePath = "file:" + image.getAbsolutePath();
Timber.d("image created at: " + filePath);
return image;
}
My permissions & features:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
This seems to work just fine on my test devices and the majority of my beta tester devices. However, there is one guy who reports that he gets an error message generated by alertUserOfError(0) (you'll see that in the above code), essentially that the photoFile is null.
He is using a rooted HTC One (M8) (htc_m8). Could this be an issue due to the device being rooted?
Any help is appreciated.
UPDATE 2015-05-30
I haven't had a chance to add reporting to the catch statement yet, but I did add a method to test for valid paths/directories. Here is how it works:
StringBuilder build = new StringBuilder();
String path_1 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "MyApp" + File.separator + "Cropped" + File.separator;
File dir_1 = new File(path_1);
dir_1.mkdirs();
if (dir_1.exists()) {
build.append("path 1 valid, ");
} else {
build.append("path 1 invalid, ");
}
Using this same setup I also tested the following dirs:
Environment.getExternalStorageDirectory() + File.separator + "MyApp" + File.separator + "Cropped" + File.separator;
Environment.getDataDirectory() + File.separator + "MyApp" + File.separator + "Cropped" + File.separator;
The StringBuilder.toString() is then used as the message in an alert for the tester to send the results back to us.
The above resulted in all paths being invalid:
path_1 invalid, path_2 invalid, path_3 invalid
So does this mean that those directories just don't exist on the HTC One (M8) (htc_m8) and cannot be created?
I had a similar situation. You are implementing the example given in the official docs. There is a problem implementing that example in some devices. This is how I solved it.
Replace:
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
With:
private File createImageFile() throws IOException {
// Create an image file name
Finally, make sure you call:
mkdirs() // and not mkdir()
Here's the code that should work for you:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = new File(Environment.getExternalStorageDirectory().toString(), "whatever_directory_existing_or_not/sub_dir_if_needed/");
storageDir.mkdirs(); // make sure you call mkdirs() and not mkdir()
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
Log.e("our file", image.toString());
return image;
}
I had a bad experience following the example given in Android Studio Documentation and I found out that there are many others experiencing the same about this particular topic here in stackoverflow, that is because even if we set
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
the problem persists in some devices.
My experience was that the example worked when I tried it in debug mode, after that 3 more tests passed, it so happened that my SD was suddenly corrupted, but I don't think it had to do with their example (funny). I bought a new SD card and tried it again (because I could not reformat my sd, however I tried), only to realize that still both release and debug mode did the same error log: directory does not exist ENOENT. Finally, I had to create the directories myself whick will contain the captured pictures from my phone's camera. And I was right, it works just perfect.
I hope this will help the ones out there searching for answers, because obviously, considering the age of your enquiry, you must have already solved this issue.

Error while uploading file to Amazon S3 bucket

When I run my app and logins with google account, it gives me the cognito provider. Now I am trying to upload a file to S3 bucket from the app. First I am trying to upload a file from my local laptop, then I will change it to upload from the app. Here is my code
provider = new CognitoCachingCredentialsProvider(mContext,
AWS_ACCOUNT_ID, IDENTITY_POOL_ID, UNAUTH_ROLE_ARN, AUTH_ROLE_ARN,Regions.EU_WEST_1);
client = new CognitoSyncManager(mContext, IDENTITY_POOL_ID, Regions.EU_WEST_1, provider);
String BUCKET_NAME = "uni-cloud";
String access_key = "something";
TransferManager transferManager = new TransferManager(provider);
File file = new File("E:\\Google Drive\\Year 3\\Project\\dummy.docx");
Log.e("Cognito Provider ID","Data " + provider.getIdentityId());
try {
Upload upload = transferManager.upload(BUCKET_NAME,access_key, file);
while (!upload.isDone()){
Log.i("upload","Uploading");
}
Log.i("upload","Uploaded");
}catch(Exception e) {Log.i("Upload", "Error while uploading");}
This is what I get in my logs.
03-04 17:27:57.789 24584-24712/com.unicloud.mittal I/upload﹕ Uploading
03-04 17:27:57.789 24584-24712/com.unicloud.mittal I/upload﹕ Uploading
03-04 17:27:57.799 24584-24712/com.unicloud.mittal I/upload﹕ Uploaded
Now when I check the S3 bucket on AWS site, it doesn't show the file. There are no errors but the file is also not uploaded. It would be helpful if you can point out my mistake.
Thanks.
I have solved this issue. If someone is looking for the method, here it is. It was not uploading because it didn't have permission to read the file. I gave the permissions in AndroidManifest.xml and it worked.
Permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Working code
TransferManager transferManager = new TransferManager(provider);
String bucket = "uni-cloud";
File file = new File("//sdcard//Download//cw.pdf");
if(file.exists())
{
Log.e(TAG,"File found " + file.getName());
}
else {
Log.e(TAG,"File not found");
}
Upload upload = transferManager.upload(bucket, file.getName(), file);
while (!upload.isDone()){
//Show a progress bar...
TransferProgress transferred = upload.getProgress();
Toast.makeText(this, "Uploading... ", Toast.LENGTH_LONG).show();
Log.i("Percentage", "" +transferred.getPercentTransferred());
}
Toast.makeText(this, "Uploaded", Toast.LENGTH_LONG).show();

Creating Folder in Internal memory

I am unable to get the methods for creating folder in Internal Memory,
i gone through few conversations in Android create folders in Internal Memory and Problem facing in reading file from Internal memory of android. But still i am unable to meet my requirement.
My requirement is , I want to create a folder in Internal Memory, there i want to Store one video.
Thankyou you very much in advance for valuable feedbacks.
try the below
File mydir = context.getDir("users", Context.MODE_PRIVATE); //Creating an internal dir;
if (!mydir.exists())
{
mydir.mkdirs();
}
Here is the code which I am using for creating files in internal memory :
File myDir = context.getFilesDir();
// Documents Path
String documents = "documents/data";
File documentsFolder = new File(myDir, documents);
documentsFolder.mkdirs(); // this line creates data folder at documents directory
String publicC = "documents/public/api." + server;
File publicFolder = new File(myDir, publicC);
publicFolder.mkdirs(); // and this line creates public/api.myservername folder in internal memory
To create directory on phone primary storage memory (generally internal memory) you should use following code. Please note that ExternalStorage in Environment.getExternalStorageDirectory() does not necessarily refers to sdcard, it returns phone primary storage memory
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "MyDirName");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("App", "failed to create directory");
return null;
}
}
Directory created using this code will be visible to phone user. The other method (as in accepted answer) creates directory in location (/data/data/package.name/app_MyDirName), hence normal phone user will not be able to access it easily and so you should not use it to store video/photo etc.
You will need permissions, in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
File direct = new File(Environment.getExternalStorageDirectory()+"/folder_name");
if(!direct.exists()) {
if(direct.mkdir()); //directory is created;
}
There is a "cacheDirectory" in your "data/package_name" directory.
If you want to store something in that cache memory,
File cacheDir = new File(this.getCacheDir(), "temp");
if (!cacheDir.exists())
cacheDir.mkdir();
where this is context.
try {
File cashDir = new File(dir.getCanonicalPath(),"folder");
if(!(cashDir.exists())) cashDir.mkdirs();
} catch (IOException e) {
e.printStackTrace();
}

Categories

Resources