File not found when uploading database file into dropbox - android

I have completed one android application and integrated DropBox to my application to upload a database.When i am uploading a single file it will be upload correctly.My problem is when i get the db file from my application and uploading this to dropbox it show file not found exeception.I am also using this link but not get solution.
Link
FileInputStream inputStream = null;
try {
String databasePath=getDatabasePath("databaseTaskApps.db").getPath();
Log.i(TAG,"DatabasePath:"+databasePath);
File file = new File(databasePath+ "/databaseTaskApps");
inputStream = new FileInputStream(file);
com.dropbox.client2.DropboxAPI.Entry newEntry = mApi.putFileOverwrite("/databaseTaskApps", inputStream,
file.length(), null);
Log.i("DbExampleLog", "The uploaded file's rev is: " + newEntry.rev);
} catch (DropboxUnlinkedException e) {
// User has unlinked, ask them to link again here.
Toast.makeText(getApplicationContext(), "Not Uploading", Toast.LENGTH_SHORT).show();
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
Toast.makeText(getApplicationContext(), "Not Uploading", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
Toast.makeText(getApplicationContext(), "Not Uploading", Toast.LENGTH_SHORT).show();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}

Hai i found answer for my question
File[] files = new File("/data/data/com.dropbox.android.sample/databases/").listFiles();
for (File f:files) {
if (f.getName().equals("databaseTaskApps"))
{
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(f);
com.dropbox.client2.DropboxAPI.Entry newEntry = mApi.putFileOverwrite("/databaseTaskApps", inputStream,
f.length(), null);
Log.i("DbExampleLog", "The uploaded file's rev is: " + newEntry.rev);
} catch (DropboxUnlinkedException e) {
// User has unlinked, ask them to link again here.
Toast.makeText(getApplicationContext(), "Not Uploading", Toast.LENGTH_SHORT).show();
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
Toast.makeText(getApplicationContext(), "Not Uploading", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
Toast.makeText(getApplicationContext(), "Not Uploading", Toast.LENGTH_SHORT).show();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
}

Related

file not playing from Internal storage in Android

here is string to setDataSource
/data/data/com.player/app_player/file.mp3
getting E/Exception: setDataSource failed.
here is the code:
mediaPlayer.setDataSource(context, Uri.parse("/data/data/com.player/app_player/file.mp3"));
I stored that file using this code
getContext().getDir("player", Context.MODE_PRIVATE)
which is same as /data/data/com.player/app_player
using content://data/data/com.player/app_player/file.mp3 did not work.
This is how I solve it.
String musicUrl = "";
if (songSavedInDB()) {
musicUrl = "here is any file path(Internal or external)"
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(musicUrl);
mPlayer.setDataSource(fileInputStream.getFD());
fileInputStream.close();
mPlayer.prepare();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
musicUrl = "here is url";
try {
mPlayer.setDataSource(getContext(), Uri.parse(musicUrl));
mPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}

Check File exist before uploading DropBoxApi

I am using following code to check file exist in dropbox before uploading to avoid duplication.I am using following line to check but it is returning false to PostExceute means "Failed to upload file".
Entry existingentry= dropbox.metadata(path + "sample.txt",1,null,false,null);
Actual Method:
protected Boolean doInBackground(Void... params) {
final File tempDir = context.getCacheDir();
File tempFile;
FileWriter fr;
try {
tempFile = File.createTempFile("file", ".txt", tempDir);
fr = new FileWriter(tempFile);
fr.write("Test file uploaded using Dropbox API for Android");
fr.close();
FileInputStream fileInputStream = new FileInputStream(tempFile);
Entry existingentry= dropbox.metadata(path + "sample.txt",1,null,false,null);
dropbox.putFile(path + "sample.txt", fileInputStream,
tempFile.length(), null, null);
tempFile.delete();
return true;
} catch (IOException e) {
e.printStackTrace();
} catch (DropboxException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
Toast.makeText(context, "File Uploaded Successfully!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Failed to upload file", Toast.LENGTH_LONG)
.show();
}
}

Calculate Speed and Bytes Transfer Rate in FTP download Android

I am planning to create an application for downloading a file from FTP server, Below code has working fine with the functionality, But I need to show current speed and transfer rate while downloading a file, Please help me to solve this problem,
private boolean downloadSingleFile(String remoteFilePath, File downloadFile) {
boolean status = false;
try {
con = new FTPClient();
con.setConnectTimeout(5000);
con.connect(host);
if (con.login(username, password)) {
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
File parentDir = downloadFile.getParentFile();
if (!parentDir.exists())
parentDir.mkdir();
OutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(
new FileOutputStream(downloadFile));
con.setFileType(FTP.BINARY_FILE_TYPE);
status = con.retrieveFile(remoteFilePath, outputStream);
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
con.logout();
con.disconnect();
}
} else {
con.logout();
con.disconnect();
// delayWait(duration);
}
}
catch (UnknownHostException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
}
return status;
}
If i would like to download a more than 5Mb or 50 Mb file this requirement will be useful for the user to know about the current speed of the device , Please help me to finish this issues.
Regards
Priya

Resource leak warning on file stream

private void SaveLog(boolean externalStorage)
{
String s = tv_log.getText().toString();
File file;
FileOutputStream fos;
if ( externalStorage )
{
try
{
file = new File(getExternalFilesDir(null), FILE_LOG);
fos = new FileOutputStream(file); // Warning: Resource leak: 'fos' is never closed
}
catch(FileNotFoundException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
}
else
{
try
{
fos = openFileOutput(FILE_LOG, Context.MODE_PRIVATE);
}
catch(FileNotFoundException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
}
try
{
fos.write(s.getBytes());
fos.close();
}
catch(IOException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
}
Why the warning is shown in the line fos = new FileOutputStream(file)? Interesting, that if I remove if ( externalStorage ) and leave only the first branch, the warning is not shown:
private void SaveLog(boolean externalStorage)
{
String s = tv_log.getText().toString();
File file;
FileOutputStream fos;
try
{
file = new File(getExternalFilesDir(null), FILE_LOG);
fos = new FileOutputStream(file); // OK!
}
catch(FileNotFoundException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
try
{
fos.write(s.getBytes());
fos.close();
}
catch(IOException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
}
I believe that in your specific case there isn't any possibility of resource leak as the line fos = new FileOutputStream(file);is the last line before the end of the try group, and if you have an exception in here the resource fos wouldn´t be created.
However, if you would have a statement after that line, that statement could genetare a exception, the execution would move to the catch group that is terminated with a return without releasing resources allocated in the trygroup.
The easiest way to avoid the warning is to add the following in the catch:
catch(FileNotFoundException e)
{
try { if(fos != null) fos.close();} catch (Exception e2) {} //Add this line
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
This would ensure that resource will be released if there is an exception raised.
In every catch block, close the stream using fos.close().
Otherwise, the program might hit the try block, generate an exception and go to the catch block without ever closing the stream. This might be causing the error.

Trying to download a file from inside an Android application

I'm trying to download a file from within my application. I've set a button's onClickListener to call this method:
private void downloadFile(String fileUrl, File destDir, String fileName) {
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
if (destDir.isDirectory() && !destDir.exists()) {
destDir.mkdirs();
}
FileOutputStream output = new FileOutputStream(new File(destDir.toString() + "/" + fileName));
InputStream input = connection.getInputStream();
byte[] buffer = new byte[1024];
int byteCount = 0;
while ((byteCount = input.read(buffer)) != -1) {
output.write(buffer, 0, byteCount);
}
output.close();
input.close();
} catch (IOException e) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("IOException", "Error: " + e.getMessage(), e);
} finally {
Toast.makeText(this, "File downloaded: " + fileName, Toast.LENGTH_SHORT).show();
}
}
I've been going through various topics, but neither one seemed to come up with a usable solution. When I use the code specified above, nothing seems to happen.
EDIT: The file will download in the background and show a short toast when finished. The button seems to be "clicked" while downloading, though. Any thoughts on this?
Thanks for your help!
Actually I didn't need all that code. I just had to use something similar to this:
private void getFile(String url) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("ActivityNotFoundException", "Error: " + e.getMessage(), e);
} catch (NullPointerException e) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("NullPointerException", "Error: " + e.getMessage(), e);
}
}
This should also be useful to some people:
private void openFile(File file) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
intent.addCategory(Intent.CATEGORY_BROWSABLE);
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("ActivityNotFoundException", "Error: " + e.getMessage(), e);
} catch (NullPointerException e) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("NullPointerException", "Error: " + e.getMessage(), e);
}
}
If nothing happens, you should add some logging to your code.
And you could also show the error to the user, by calling Toast.makeText(context, ex.getMessage(), Toast.LENGTH_SHORT).show()
Better would be to show the root cause message using helper methods like these:
public static String getRootCauseMessage(Throwable ex) {
ex = getRootCause(ex);
String message = ex.getLocalizedMessage();
return message == null ? ex.getClass().getSimpleName() : message;
}
public static Throwable getRootCause(Throwable ex) {
Throwable cause = ex.getCause();
return cause == null ? ex : getRootCause(cause);
}

Categories

Resources