I am using following code to upload a file to Dropbox. But I want to check if the file exists on Dropbox already, to avoid duplications. So how can I check if a file already exists or not? As I am new to Android, I don't know what to do now
public class UploadFileToDropbox extends AsyncTask<Void, Void, Boolean>
{
private DropboxAPI<?> dropbox;
private String path;
private Context context;
public UploadFileToDropbox(Context context, DropboxAPI<?> dropbox,
String path) {
this.context = context.getApplicationContext();
this.dropbox = dropbox;
this.path = path;
}
#Override
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);
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();
}
}
}
If the file exists, then the Entry is not null
public boolean isExists(String path) {
boolean ret = false;
try {
Entry existingEntry = metadata(path, 1, null, false, null);
if (existingEntry != null) {
ret = true;
}
} catch (DropboxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ret = false;
}
return ret;
}
private void loadFiles(final String directory) {
new Thread() {
#Override
public void run() {
String mPath = directory;
Entry direntEx = null;
try {
direntEx = mApi.metadata(mPath, 1000, null, true, null);
} catch (DropboxException e) {
e.printStackTrace();
}
if (direntEx.contents.size() != 0) {
for (Entry ent : direntEx.contents) {
String name = ent.fileName();
/*Compare file here*/
}
}
super.run();
}
}.start();
}
Related
I created an image gallery app.
My requirment: I want to select multiple images, click on button cut and come back to activity which displays all folders (ImageGallery.java). Now, I want to select a folder and paste all the selected images in that folder, on selecting the folder.
What is happening? I am able to select images using my app and come back to activity which displays all folders but not able to move them using my app.
I put the code for moving images in a background thread using task. I select images from one folder, come back to the activity which displays all the folders (ImageGallery.java) and select the folder to which the images are to be moved. But when I try to move images, selected images do not move to other folder being selected, on selecting a folder. I guess the code inside AsyncTask isn't even getting executed.
How do I fix it ?
PhotosActivity.java (Activity used to select images):
int int_position;
private GridView gridView;
GridViewAdapter adapter;
ArrayList<Model_images> al_menu = new ArrayList<>();
private ArrayList<Integer> mSelected = new ArrayList<>();
boolean boolean_folder;
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position, long id) {
if (mSelected.contains(position)) {
mSelected.remove(position);
view.setBackgroundColor(Color.TRANSPARENT);// remove item from list
// update view (v) state here
// eg: remove highlight
} else {
mSelected.add(position);
view.setBackgroundColor(Color.LTGRAY);// add item to list
// update view (v) state here
// eg: add highlight
}
buttoncut.setVisibility(View.VISIBLE);
button2.setVisibility(View.VISIBLE);
button3.setVisibility(View.VISIBLE);
button4.setVisibility(View.VISIBLE);
button5.setVisibility(View.VISIBLE);
buttoncut.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
buttoncut.setVisibility(View.GONE);
button2.setVisibility(View.GONE);
button3.setVisibility(View.GONE);
button4.setVisibility(View.GONE);
button5.setVisibility(View.GONE);
Intent moveIntent = new Intent(PhotosActivity.this, ImageGallery.class);
moveIntent.putIntegerArrayListExtra("selected_images", mSelected);
startActivity(moveIntent);
}
});
ImageGallery.java:
public static ArrayList<Model_images> al_images = new ArrayList<>();
ArrayList<Integer> selectedImages = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
private static final int REQUEST_PERMISSIONS = 100;
int int_position;
selectedImages = getIntent().getIntegerArrayListExtra("selected_images");
if (selectedImages != null) {
Toast.makeText(ImageGallery.this, "This code gets executed", Toast.LENGTH_SHORT)
.show();
new LongOperation().execute();
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
for (int image : selectedImages) {
File sourceImage = new File(al_images.get(int_position).getAl_imagepath().get(image)); //returns the image File from model class to be moved.
File destinationImage = new File(al_images.get(int_position).getStr_folder(), ".jpeg");
try {
copyOrMoveFile(sourceImage, destinationImage, true);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
//Method to move the file
private void copyOrMoveFile(File file, File dir, boolean isCopy) throws IOException {
File newFile = new File(dir, file.getName());
FileChannel outChannel = null;
FileChannel inputChannel = null;
try {
outChannel = new FileOutputStream(newFile).getChannel();
inputChannel = new FileInputStream(file).getChannel();
inputChannel.transferTo(0, inputChannel.size(), outChannel);
inputChannel.close();
if (!isCopy)
file.delete();
} finally {
if (inputChannel != null) inputChannel.close();
if (outChannel != null) outChannel.close();
}
}
}
You have to use Intent.ACTION_MEDIA_SCANNER_SCAN_FILE for updating media store.
Inside AsyncTask -> onPostExecute method fetch latest images from MediaStore
private class LongOperation extends AsyncTask<String, Void, File> {
#Override
protected File doInBackground(String... params) {
for (String imagePath : selectedImages) {
File sourceImage = new File(imagePath); //returns the image File from model class to
// be// moved.
File destinationImage = new File(al_images.get(int_position).getDirectoryPath() +
File.separator + sourceImage.getName());
try {
moveFile(sourceImage, destinationImage, true);
return destinationImage;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(File file) {
super.onPostExecute(file);
getBaseContext().sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
fn_imagespath(); // Call method to fetch latest images.
}
}, 1000); // additional delay time of 1 sec to update media scanner
}
}
Just a better method to move file
private void moveFile(File file_Source, File file_Destination, boolean isCopy) throws IOException {
FileChannel source = null;
FileChannel destination = null;
if (!file_Destination.exists()) {
file_Destination.createNewFile();
}
try {
source = new FileInputStream(file_Source).getChannel();
destination = new FileOutputStream(file_Destination).getChannel();
long count = 0;
long size = source.size();
while ((count += destination.transferFrom(source, count, size - count)) < size) ;
if (!isCopy) {
file_Source.delete();
}
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
Not much changes in code added MediaScannerConnection. Give it a try .
private class LongOperation extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(String... params) {
int movedCount=0;
for (int i=0;i<selectedImages.size();i++) {
File sourceImage = new File(al_images.get(int_position).getAl_imagepath().get(i));
File destinationImage = new File(al_images.get(int_position).getStr_folder(), ".jpeg");
try {
boolean isMoved= copyOrMoveFile(sourceImage, destinationImage, true);
if(isMoved) {
movedCount++;
callMediaScanner(ImageGallery.this, destinationImage.getAbsolutePath());
}
} catch (IOException e) {
e.printStackTrace();
}
}
return movedCount;
}
#Override
protected void onPostExecute(Integer val) {
super.onPostExecute(val);
// Here you have to modify return type of doInBackground as per your convineance
if(val.intValue()==selectedImages.size()){
Log.e("Moved","Allfile moved");
}else{
Log.e("Moved","Some file missing");
}
}
public boolean copyOrMoveFile(File localFile, File destinationFile, boolean isCopy) {
FileChannel outputChannel = null;
FileChannel inputChannel = null;
try {
outputChannel = new FileOutputStream(destinationFile).getChannel();
inputChannel = new FileInputStream(localFile).getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
inputChannel.close();
if (!isCopy)
localFile.delete();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (inputChannel != null) inputChannel.close();
if (outputChannel != null) outputChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
}
public void callMediaScanner(Context context, String path) {
MediaScannerConnection.scanFile(context,
new String[] { path }, null,null);
}
My video is not playing on my android device, however the video is present in the package folder. The video is copied from my Asset folder.
`public class MainActivity extends Activity
{
private static final String TAG = "Copying File or Folder";
//Shared Preference
private String appName = "com.example.nadeemstc.webviewvideo";
private SharedPreferences pref;
private Editor editor;
//WebView Variables
private JsHandler _jsHandler;
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.webView);
myWebView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN && !view.hasFocus()) {
view.requestFocus();
}
return false;
}
});
pref = getApplicationContext().getSharedPreferences(appName, MODE_PRIVATE);
//pref = getSharedPreferences(appName,0);
// pref.getBoolean("flag",true);
Boolean b = (pref.getBoolean(appName, false));
Log.d("BgCopy", "Boolean Data is " + b);
if (b == false) {
MyTask task = new MyTask();
task.execute("Nadeem");
} else if (b == true) {
Log.d("BgCopy", "Folder Already Exists, do Not Copy");
initWebView();
}
}
private void initWebView() {
//Tell the WebView to enable javascript execution.
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setBackgroundColor(Color.parseColor("#808080"));
//Set whether the DOM storage API is enabled.
myWebView.getSettings().setDomStorageEnabled(true);
//setBuiltInZoomControls = false, removes +/- controls on screen
myWebView.getSettings().setBuiltInZoomControls(false);
myWebView.getSettings().setPluginState(PluginState.ON);
myWebView.getSettings().setAllowFileAccess(true);
myWebView.getSettings().setAppCacheMaxSize(1024 * 8);
myWebView.getSettings().setAppCacheEnabled(true);
_jsHandler = new JsHandler(this, myWebView);
myWebView.addJavascriptInterface(_jsHandler, "JsHandler");
myWebView.getSettings().setUseWideViewPort(false);
myWebView.setWebChromeClient(new WebChromeClient());
myWebView.setWebViewClient(new WebViewClient());
// these settings speed up page load into the webview
myWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
myWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
myWebView.requestFocus(View.FOCUS_DOWN);
// load the main.html file that kept in assets folder
myWebView.loadUrl("file:///android_asset/index.html");
}
private void copyAssets(String path) {
String[] files = null;
try {
files = getAssets().list(path);
for (String fileName: files) {
Log.d("CopyAsset", "file / folder name " + fileName);
}
} catch (IOException e) {
e.printStackTrace();
}
if (files.length == 0) {
copyFile(path);
} else {
File dir = new File(getExternalFilesDir(null), path);
if (!dir.exists()) {
dir.mkdir();
}
for (int i = 0; i < files.length; i++) {
copyAssets(path + "/" + files[i]);
}
}
Log.d("CopyAssets ", "Done" + path + "is at " + files);
doneCopy();
}
private void copyFile(String filename) {
InputStream in = null;
filename = "rah.mp4";
File file;
OutputStream out = null;
try { in = getAssets().open(filename);
} catch (IOException e) {
e.printStackTrace();
}
file = new File(getExternalFilesDir(null), filename);
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
Log.e(TAG, "ERROR WITH out = new FileOutputStream(file);");
e.printStackTrace();
}
// byte[] data = new byte[1024];
// int read;
// try {
// while ((read = in.read(data)) != -1) {
// out.write(data, 0, read);
// }
// in.close();
// out.flush();
// out.close();
// } catch (Exception e) {
// Log.e(TAG, e.getMessage());
// }
byte[] data;
try {
data = new byte[ in .available()]; in .read(data);
out.write(data); in .close();
out.flush();
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
private void doneCopy() {
Log.d("BgCopy", "Done Copying Files");
}
public class MyTask extends AsyncTask < String, Long, Boolean > {
ProgressDialog progress;
protected void onPreExecute() {
progress = ProgressDialog.show(MainActivity.this, "", "Loading...", true);
}
#Override
protected Boolean doInBackground(String...files) {
// TODO Auto-generated method stub
copyMe(files[0]);
return true;
}
#Override
protected void onPostExecute(Boolean success) {
Log.d("onPostExecute", "Check The Boolean data ");
progress.dismiss();
editor = pref.edit();
editor.putBoolean(appName, true);
editor.commit();
initWebView();
}
protected void onProgressUpdate(Long...values) {
progress.setMessage("Transferred " + values[0] + " bytes");
}
private void copyMe(String si) {
copyAssets(si);
}
}
}`
Until now I could programmatically copy files from the internal memory of the phone to an USB-OTG connected to it. I just had to give root permissions and edit platform.xml. But now my device (Samsung Galaxy S6 Edge +) has been updated to Android 6 and made my code stop working.
I'm getting this error everytime I try to copy files the way I did before:
Caused by java.lang.RuntimeException: java.io.FileNotFoundException: /mnt/media_rw/4265-1803/requiredfiles/Oculus/360Photos/Pisos/Chalet Anna/R0010008.JPG: open failed: EACCES (Permission denied)
String from = Environment.getExternalStorageDirectory() + File.separator + getString(R.string.FOLDER_SDCARD);
String to = Utils.getUsbPath() + File.separator + getString(R.string.FOLDER_USB);
FileManager fileManager = new FileManager(getActivity(), from, to, false);
fileManager.execute(true);
My getUsbPath function
public static String getUsbPath() {
String finalpath = null;
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
String[] patharray = new String[10];
int i = 0;
int available = 0;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
String mount = new String();
if (line.contains("secure"))
continue;
if (line.contains("asec"))
continue;
if (line.contains("fat")) {// TF card
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
mount = mount.concat(columns[1] + "/requiredfiles");
patharray[i] = mount;
i++;
// check directory is exist or not
File dir = new File(mount);
if (dir.exists() && dir.isDirectory()) {
// do something here
available = 1;
finalpath = mount;
break;
} else {
}
}
}
}
if (available == 1) {
} else if (available == 0) {
finalpath = patharray[0];
}
} catch (Exception e) {
}
return finalpath;
}
My FileManager.class
public class FileManager extends AsyncTask<Boolean, Integer, Boolean> {
private Context context;
private String from;
private String to;
private ProgressDialog progressDialog;
private int filesCount=0;
private int filesTotal=0;
Boolean completed;
Boolean move;
MainActivity main;
public static final String TAG = "FileManager";
public FileManager(Context context, String from, String to, Boolean move) {
this.context = context;
this.from = from;
this.to = to;
this.move = move;
this.main = (MainActivity) context;
}
#Override
protected Boolean doInBackground(Boolean... params) {
File source = new File(from);
File target = new File(to);
try {
countFiles(source);
copyDirectory(source, target);
if (move) {
deleteFiles(source);
}
completed = true;
} catch (Exception error) {
Log.e(TAG, "doInBackground", error);
completed = false;
try {
throw error;
} catch (IOException e) {
e.printStackTrace();
}
throw new RuntimeException(error.toString());
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
if (move) {
progressDialog.setMessage(context.getString(R.string.moving_files));
} else {
progressDialog.setMessage(context.getString(R.string.copying_files));
}
progressDialog.setIndeterminate(true);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
progressDialog.dismiss();
if (completed) {
if (move) {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.move_completed), Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.copy_completed), Snackbar.LENGTH_LONG).show();
}
} else {
if (move) {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.move_failed), Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.copy_failed), Snackbar.LENGTH_LONG).show();
}
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setIndeterminate(false);
progressDialog.setMax(filesTotal);
progressDialog.setProgress(filesCount);
}
private void copyDirectory(File sourceLocation, File targetLocation) throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdirs();
}
String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {
copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
}
} else {
if (!targetLocation.exists()) {
filesCount++;
publishProgress();
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
scanFile(targetLocation.getCanonicalPath(), false);
}
}
}
private void countFiles(File file) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < file.listFiles().length; i++) {
countFiles(new File(file, children[i]));
}
} else {
filesTotal++;
}
}
public void deleteFiles(File folder) {
if (folder.isDirectory()) {
File[] list = folder.listFiles();
if (list != null) {
for (int i = 0; i < list.length; i++) {
File tmpF = list[i];
if (tmpF.isDirectory()) {
deleteFiles(tmpF);
}
tmpF.delete();
String path;
try {
path = tmpF.getCanonicalPath();
} catch (Exception error) {
Log.e(TAG, "", error);
path = tmpF.getAbsolutePath();
}
scanFile(path, true);
}
}
}
}
private void scanFile(String path, final boolean isDelete) {
try {
MediaScannerConnection.scanFile(context, new String[] { path },
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
if (isDelete) {
if (uri != null) {
context.getContentResolver().delete(uri,
null, null);
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
How can I solve it?
I am trying to upload a file from dropbox in another activity from where i autenticate to dropbox. I have this RegisterActivity.java where the user registers and then later when the registration is completed the webbrowser comes up and the user has to allow the dropbox authentication.
later in my app on another activity the user is going to upload a video to dropbox. the upload is made by ASyncTask and works well. The problem is now that i dont want to reauthenticate again. How do i fix that? Is it on the same session or do i start a new session? Now Iam trying to use the sam mDBApi form RegisterAcitivity but i think that is wrong. The keys are stored in the storeKeys() method and saves them in SharedPreferences.
Thank you very much in advance
Here is my RegisterActivity in pastebin which works. http://pastebin.com/K06JUWXv
Here is the activity that where i call my ASyncTask UploadFile:
public class ShowVideo extends Activity{
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
private DropboxAPI<AndroidAuthSession> mDBApi = RegisterActivity.mDBApi;
private String[] storedKeys = getKeys();
UploadFile upload;
public static String path = "";
public static String fileName;
private VideoView ww;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Forces landscape orientation which is what the camera uses.
setContentView(R.layout.showvideo);
Button yesButton = (Button) findViewById(R.id.yesButton);
Button noButton = (Button) findViewById(R.id.NoButton);
Button dbButton = (Button) findViewById(R.id.dropboxButton);
dbButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(v.getId() == R.id.dropboxButton){
if (mDBApi.getSession().isLinked() == true){
Log.d("ShowVideo", "TRUE");
}
if (mDBApi.getSession().isLinked() == false){
Log.d("ShowVideo", "FALSE");
}
}
}
});
yesButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(v.getId() == R.id.yesButton){
UploadFile upload = new UploadFile(ShowVideo.this,mDBApi,path);
upload.execute();
}
}
});
noButton.setOnClickListener(new OnClickListener() {
public void onClick(View w) {
File file = new File(path);
boolean deleted = false;
deleted = file.delete();
Log.e("TAG", Boolean.toString(deleted));
Intent intent = new Intent(ShowVideo.this, CaptureVideo.class);
startActivity(intent);
}
});
ww = (VideoView) findViewById(R.id.satisfiedVideoView);
path = getRealPathFromURI(CaptureVideo.uriVideo);
fileName = getFileNameFromUrl(path);
//AndroidAuthSession session = new AndroidAuthSession(new AppKeyPair(ret[0], ret[1]), AccessType.APP_FOLDER);
//mDBApi = new DropboxAPI<AndroidAuthSession>(session);
}
private void playVideo(){
ww.setVideoURI(CaptureVideo.uriVideo);
ww.setMediaController(new MediaController(this));
ww.start();
ww.requestFocus();
}
public static String getFileNameFromUrl(String path) {
String[] pathArray = path.split("/");
return pathArray[pathArray.length - 1];
}
public String getRealPathFromURI(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);
}
/**DROPBOX-METHOD------------------------------------------*/
private String[] getKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(ACCESS_KEY_NAME, null);
String secret = prefs.getString(ACCESS_SECRET_NAME, null);
if (key != null && secret != null) {
String[] ret = new String[2];
ret[0] = key;
ret[1] = secret;
return ret;
} else {
return null;
}
}
}
Here is my ASyncTask if you would take a look at that. Shouldn't be needed.
public class UploadFile extends AsyncTask<Void, Long, Boolean> {
DropboxAPI<AndroidAuthSession> dDBApi;
Context dContext;
private String SAVE_PATH;
public UploadFile(Context context,DropboxAPI<AndroidAuthSession> mDBApi, String path) {
dContext = context.getApplicationContext();
dDBApi = mDBApi;
SAVE_PATH = path;
}
#Override
protected Boolean doInBackground(Void... params) {
FileInputStream inputStream = null;
try {
File file = new File(SAVE_PATH);
inputStream = new FileInputStream(file);
Entry newEntry = dDBApi.putFileOverwrite("/GAMES/GAME_BETWEEN_USER_A_USER_B/" + "PresentVideo.mp4", inputStream, file.length(), null);
}
catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} catch (IOException e) {
Log.e("DbExampleLog", "Another Exception:" + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
Log.e("DbExampleLog", "Another Exception:" + e.getMessage());
e.printStackTrace();
}
finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
}
}
}
return null;
}
}
I have this code:
public static class ExportDatabaseFileTask extends AsyncTask<String, Void, Boolean> {
private Context ctx;
/**
*
*/
public ExportDatabaseFileTask(Context ctx) {
super();
this.ctx = ctx;
}
// automatically done on worker thread (separate from UI thread)
protected Boolean doInBackground(final String... args) {
File dbFile = new File(Environment.getDataDirectory()
+ "/data/com.mypkg/databases/log.db");
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
try {
file.createNewFile();//*
this.copyFile(dbFile, file);
return true;
} catch (IOException e) {
Log.e("mytag", e.getMessage(), e);
return false;
}
}
// can use UI thread here
protected void onPostExecute(final Boolean success) {
if (success) {
Toast.makeText(ctx, "Export successful!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ctx, "Export failed", Toast.LENGTH_SHORT).show();
}
}
void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
}
On the marked line of
file.createNewFile();
I get java.io.IOException: Parent directory of file is not writable: /sdcard/log.db
I have an sdcard installed and I can easily copy files to it. What might be wrong?
Just when someone rushes it makes mistakes
it was a missing permission
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>