Android Core API Download File - android

I am trying firstly to download the file and its content from Dropbox in Android app using Dropbox Core API but when i execute the following code the app crushes.
EDIT: I have used two functions downloadDropboxFile and copy functions. The problem is that i am getting blank data when i read the local file which is supposed to contain the dropbox file data.
Here is the code where i call the function
downloadDropboxFile("/userandpass.txt");
if (mDBApi.getSession().isLinked())
{
InputStream instream = new FileInputStream(String.valueOf(getExternalCacheDir()) + "/userandpass.txt");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
mTestOutput.setText(buffreader.readLine());
}
Here is the functions
private boolean downloadDropboxFile(String fileSelected) {
File dir = new File(String.valueOf(getExternalCacheDir()));
if (!dir.exists())
dir.mkdirs();
try {
File localFile = new File(dir + fileSelected);
if (!localFile.exists()) {
localFile.createNewFile();
copy(fileSelected, localFile);
} else {
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
private void copy(final String dbPath, final File localFile) {
new Thread(new Runnable() {
#Override
public void run() {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
DropboxAPI.DropboxInputStream fd = mDBApi.getFileStream(dbPath,null);
br = new BufferedInputStream(fd);
bw = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}). start();
}
Dropbox Core API Implementation on Android Studio:
On app/libs i have the:
dropbox-android-sdk-1.6.3.jar
httpmime--4.0.3.jar
json_simple-1.1.jar

Your issue is here :
if (!localFile.exists()) {
localFile.createNewFile(); //otherwise dropbox client will fail silently
}
The exception is :
java.io.IOException: open failed: EROFS (Read-only file system)
This means you're trying to create a File on a location that is read only in the phone's memory, I'm guessing the internal storage. Have a look at this excellent answer by Mark Murphy on creating a File based on locations that can be written to.
Hoping this has been of some help, happy coding ;-)

Related

Unable to view image, video after decryption android

I am using following method to encrypt and decrypt the files. File is getting decrypted properly but I am unable to view Image or video in application. File is opening in gallery and I can view image and watch video clearly. The same I am unable to do in application using Imageview and Videoview
Below is my code :
public void run() {
boolean successful = true;
operationInProgress = true;
lastUpdateAtByteNumber = 0;
totalBytesRead = 0;
timeOperationStarted = System.currentTimeMillis();
if (operationType == OPERATION_TYPE_ENCRYPTION) {
completedMessageStringId = R.string.encryption_completed;
} else {
completedMessageStringId = R.string.decryption_completed;
}
InputStream inputStream = null;
OutputStream outputStream = null;
//get the input stream
try {
inputStream = new FileInputStream(inputFileName);
} catch (IOException ioe) {
successful = false;
ioe.printStackTrace();
}
//get the output stream
try {
outputStream = new FileOutputStream(outputFileName);
} catch (IOException ioe) {
successful = false;
ioe.printStackTrace();
}
if (inputStream != null && outputStream != null) {
//call AESCrypt
try {
fileSize = inputStream.available();
AESCrypt aesCrypt = new AESCrypt(password);
if (operationType == OPERATION_TYPE_ENCRYPTION) {
//Encrypt
aesCrypt.encrypt(version, inputStream, outputStream);
} else {
//Decrypt
aesCrypt.decrypt(fileSize, inputStream, outputStream);
}
} catch (GeneralSecurityException gse) {
successful = false;
gse.printStackTrace();
} catch (UnsupportedEncodingException uee) {
successful = false;
uee.printStackTrace();
} catch (IOException ioe) {
successful = false;
} catch (NullPointerException npe) {
successful = false;
}
}
//close the streams
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ioe) {
successful = false;
ioe.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException ioe) {
successful = false;
}
}
operationInProgress = false;
}
The reference code is https://www.aescrypt.com/download/
AndroidCrypt (AES Crypt compatible) for Android phones (source code)
File getting encrypted and decrypted properly. When I am trying to open the load the file using Imageview for image and videoview for video.
I am using below code to view image
File url1 = new File(path to my file);
Bitmap bmp = BitmapFactory.decodeFile(url1.getAbsolutePath());
objImageView.setImageBitmap(bmp);
It gives error **"libjpeg error 105 < Ss=0, Se=63, Ah=0, Al=0> from Incomplete image data"** . or **Failed to create image decoder with message 'unimplemented'**
For Video I am using below code
getPackageName is name of package
FileProvider I have declared in manifest and also in xml I have menioned fielpath
File url1 = new File(path to video file)
videoView.setVideoURI(FileProvider.getUriForFile(
this, getPackageName(),url1));
The same image and video is clearly visible in Gallery application.
Please help me.
Thanks

Can't create file in the internal storage

i am trying to create a file in the internal storage, i followed the steps in android developers website but when i run the below code there is no file created
please let me know what i am missing in the code
code:
File file = new File(this.getFilesDir(), "myfile");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fOut = null;
try {
fOut = openFileOutput("myfile",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fOut.write("SSDD".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
By default these files are private and are accessed by only your application and get deleted , when user delete your application
For saving file:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
For loading file:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Try to get the path for storing files were the app has been installed.The below snippet will give app folder location and add the required permission as well.
File dir = context.getExternalFilesDir(null)+"/"+"folder_name";
If you are handling files that are not intended for other apps to use, you should use a private storage directory on the external storage by calling getExternalFilesDir(). This method also takes a type argument to specify the type of subdirectory (such as DIRECTORY_MOVIES). If you don't need a specific media directory, pass null to receive the root directory of your app's private directory.
Probably, this would be the best practice.
Use this method to create folder
public static void appendLog(String text, String fileName) {
File sdCard=new File(Environment.getExternalStorageDirectory().getPath());
if(!sdCard.exists()){
sdCard.mkdirs();
}
File logFile = new File(sdCard, fileName + ".txt");
if (logFile.exists()) {
logFile.delete();
}
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this method, you have to pass your data string as a first parameter and file name which you want to create as second parameter.

java.io.FileNotFoundException: /: open failed: EISDIR (Is a directory)

File albumF = getVideoAlbumDir();
String path = albumF.getAbsolutePath();
// path =/storage/emulated/0/Pictures/.MyImages (Hidden folder)
// fileSelected.fileName()=IMG_20140417_113847.jpg
File localFile = new File(path + "/" + fileSelected.fileName());
Log.v("", "file exist===" + localFile.exists());
if (!localFile.exists()) {
Log.v("", "inside if===");
Log.v("", "Parent Filet===" + localFile.getParentFile());
localFile.getParentFile().mkdirs();
// localFile.createNewFile();
copy(fileSelected, localFile);
} else {
Log.v("", "inside else===");
mCurrentPhotoPath = localFile.getAbsolutePath();
uploadMediaFile();
}
This copy method copies data from dropbox file to my local storage.
private void copy(final Entry fileSelected, final File localFile) {
final ProgressDialog pd = ProgressDialog.show(ChatActivity.this,
"Downloading...", "Please wait...");
new Thread(new Runnable() {
#Override
public void run() {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
DropboxInputStream fd;
try {
fd = mDBApi.getFileStream(fileSelected.path,
localFile.getAbsolutePath());
br = new BufferedInputStream(fd);
bw = new BufferedOutputStream(new FileOutputStream(
localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
pd.dismiss();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
android.os.Message msg = new android.os.Message();
msg.arg1 = 100;
if (msg.arg1 >= 100) {
progressHandler.sendMessage(msg);
mCurrentPhotoPath = localFile.getAbsolutePath();
}
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
I am creating file in a folder using localFile.getParentFile().mkdirs();
I got above error when I upload this file to server.
how to fix this?
If you've tried all other options - and problem still persists - then maybe you have a case when the file you want to create matches name of already existing directory.(which might be earlier created my some call to mkdirs() maybe accidentally).
Example:
You want to save file Test\test.pdf but you already have folder Test\Test.pdf\

restore database file from dropbox to local memory

I have implemented a database backup on dropbox, i would like to restore the DB from dropbox to the internal memory (data\data\\database),
i think is forbidden to write directly, is possible to read by stream the file on dropbox, and open the local file, clear the data inside , and flush the stream into the file?
If yes, anyone have a code for example?
I hope to be clear.
this is my code...
private boolean downloadDropboxFile(String dbPath, File localFile) throws IOException{
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
if (!localFile.exists()) {
localFile.createNewFile(); //otherwise dropbox client will fail silently
}
byte[] buffer = new byte[4096];
DropboxInputStream fd = mApi.getFileStream (dbPath, null);
br = new BufferedInputStream(fd, buffer.length);
bw = new BufferedOutputStream(new FileOutputStream(localFile));
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
} catch (DropboxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//in finally block:
if (bw != null) {
bw.close();
}
if (br != null) {
br.close();
}
}
return true;
}

Download all types of file from Dropbox

I am working on Dropbox. I see the documentation. This is my code to display list:
Entry entryCheck = mApi.metadata("/", 100, null, true, null);
Log.i("Item Name", entryCheck.fileName());
Log.i("Is Folder", String.valueOf(entryCheck.isDir));
I got all list from dropbox but my question is that
Here entryCheck.isDir always give me true value if it is file or directory so how i can know which is file or which one is directory?
How i downloaded that files.
I tried with this but it is not working:
private boolean downloadDropboxFile(String dbPath, File localFile,
DropboxAPI<?> api) throws IOException {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
if (!localFile.exists()) {
localFile.createNewFile(); // otherwise dropbox client will fail
// silently
}
DropboxInputStream fin = mApi.getFileStream("dropbox", dbPath);
br = new BufferedInputStream(fin);
bw = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
} catch (DropboxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// in finally block:
if (bw != null) {
bw.close();
}
if (br != null) {
br.close();
}
}
return true;
}
This will work
String inPath ="mnt/sdcard/"+filename;
File file=new File(inPath);
try {
mFos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
mErrorMsg = "Couldn't create a local file to store the image";
return false;
}
mApi.getFile("/"+filename, null, mFos, null);
This downloads the file and store it in the sdcard location inPath.
You have to do it in a new thread,not in main thread.Use AsyncTask.
http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html
this link explains why..

Categories

Resources