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();
}
}
Related
I would like to create a backup file in my memory card but all it does is return a file not found exception. I am specifying the path where the data should be saved. When i choose the Internal storage the file was saved but when i changed it to external storage, it returns me the file not found.
Here are the Screenshots:
enter image description here
final Preference prefStoragePath = findPreference("key_storage_path");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
String pref_storage_path = settings.getString("set_storage_path",null);
startingDir = (pref_storage_path!=null)? pref_storage_path : Environment.getExternalStorageDirectory().toString();
Preference prefBackupManual = findPreference("key_backup_manual");
final String root = Environment.getExternalStorageDirectory().toString();
prefBackupManual.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
createBackupData(startingDir);
return false;
}
});
private void createBackupData(String dir){
String filename = "BackupData.txt";
String data = resultSet().toString();
try{
byte[] sha1hash;
File myFile = new File(dir,filename);
sha1hash = data.getBytes("UTF-8");
String base64 = Base64.encodeToString(sha1hash, Base64.DEFAULT);
FileOutputStream fos = new FileOutputStream(myFile);
fos.write(base64.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "no file", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "file not saved", Toast.LENGTH_SHORT).show();
}finally {
Toast.makeText(getActivity(),"File saved in " + dir + "/" + filename ,Toast.LENGTH_SHORT).show();
}
}
what is happening?
you are trying to write data into a file that does not exist, thus a FileNotFoundException is thrown. The File(String, String) constructor does not create an actual file, you must take care of that by yourself.
How to fix it?
Check that your app has declared <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in the Manifest. If you are targeting SDK 23 or above you should check and request that permission at runtime.
Your save method should look like:
private void createBackupData(String dir) {
String filename = "BackupData.txt";
String data = resultSet().toString();
FileOutputStream fos = null;
try {
byte[] sha1hash;
File myFile = new File(dir, filename);
//NOTE: your file will be overwritten in case it already exists
if (myFile.exists() || myFile.createNewFile()) {
sha1hash = data.getBytes("UTF-8");
String base64 = Base64.encodeToString(sha1hash, Base64.DEFAULT);
fos = new FileOutputStream(myFile);
fos.write(base64.getBytes());
Toast.makeText(getActivity(), "File saved in " + dir + File.separator + filename, Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "no file", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "file not saved", Toast.LENGTH_SHORT).show();
} finally {
if (fos != null)
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note: a better approach is using Environment.getExternalStorageDirectory().getAbsolutePath() instead of Environment.getExternalStorageDirectory().toString()
I have a function to write a text file and it's working fine, the file is visible and can be opened from the file manager of the phone but when I connect the phone to the computer I can't see the file, what is the problem?
public static void writeToFile(String sBody, Activity activity) {
File directoryFile = new File(Environment.getExternalStorageDirectory() +"/platefinder");//ApiCrypter.DIRECTORY);
File file = new File(directoryFile, "plates_notes.txt");
if(file.exists()){
file.delete();
PlateFinderDbAdapter datasource = new PlateFinderDbAdapter(activity);
datasource.open();
String s = datasource.getStringNotes();
writeToFile(s, activity);
datasource.close();
}else{
try {
FileWriter writer = new FileWriter(file,true);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(activity, "تم تصدير الملف", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(activity, "حصل خطأ", Toast.LENGTH_SHORT).show();
}
}
}
Solved it
public static void writeToFile(String sBody, Activity activity) {
File directoryFile = new File(Environment.getExternalStorageDirectory() +"/platefinder");//ApiCrypter.DIRECTORY);
File file = new File(directoryFile, "plates_notes.txt");
if(file.exists()){
file.delete();
PlateFinderDbAdapter datasource = new PlateFinderDbAdapter(activity);
datasource.open();
String s = datasource.getStringNotes();
writeToFile(s, activity);
datasource.close();
}else{
try {
FileWriter writer = new FileWriter(file,true);
writer.append(sBody);
writer.flush();
writer.close();
MediaScannerConnection.scanFile(activity,
new String[] { file.toString() },
null,
null);
Toast.makeText(activity, "تم تصدير الملف", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(activity, "حصل خطأ", Toast.LENGTH_SHORT).show();
}
}
}
I am creating Xmpp application using SMACK api and Spark for test.
I am able to send from Spark but I cannot see Any Directory and File created in android gallery.
I log the method incoming.getAmountWritten() and it is giving me
07-27 21:00:58.789: V/Receiving Status ...(17652): 208861
It means I have got the file and now I have to write on physical storage. May be there is problem with my android code.
Please find Android Code
#Override
public void fileTransferRequest(final FileTransferRequest fileRequest) {
final File dir = Environment.getExternalStorageDirectory();
final File folder = new File(dir+ "/illuxplain/");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
Thread receiving = new Thread(new Runnable() {
#Override
public void run() {
IncomingFileTransfer incoming = fileRequest.accept();
Log.v("Receiving File Name", incoming.getFileName());
File file = new File(folder, incoming.getFileName());
try {
incoming.recieveFile(file);
while (!incoming.isDone()) {
try {
Thread.sleep(1000L);
} catch (Exception e) {
Log.e("", e.getMessage());
}
if (incoming.getStatus().equals(Status.error)) {
Log.e("ERROR!!! ", incoming.getError() + "");
}
if (incoming.getException() != null) {
incoming.getException().printStackTrace();
}
}
Log.v("Receiving Status ... ",""+incoming.getAmountWritten());
} catch (Exception e) {
e.printStackTrace();
Log.e("", e.getMessage());
}
}
});
receiving.start();
}else{
System.out.println("Directory Not Created");
}
}
}
When I go to gallery and see if I got the file. I see no directory created and of course no file.
You need to write the data into the file. Here is an example to code to write the data in to the file
File file = new File(folder, incoming.getFileName());
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(file);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
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\
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) {
}
}
}
}
}