Create folder in using dropbox api for android - android

Does anyone know how to create folder programatically using dropbox api for android??I am not using sync api.I have managed to upload images and files but I am unable to create folder.
This is my upload asynctask:
public class UploadFile extends AsyncTask<Void, Long, Boolean> {
private DropboxAPI<?> mApi;
private String mPath;
private File mFile;
private long mFileLen;
private UploadRequest mRequest;
private Context mContext;
private ProgressDialog mDialog;
final static private String ACCOUNT_PREFS_NAME = "prefs";
private String mErrorMsg;
public UploadFile(Context context, DropboxAPI<?> api, String dropboxPath,
File file) {
mContext = context;
mFileLen = file.length();
mApi = api;
mPath = dropboxPath;
mFile = file;
mDialog = new ProgressDialog(context);
mDialog.setMax(100);
mDialog.setMessage("Uploading " + file.getName());
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton("Cancel", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// This will cancel the putFile operation
mRequest.abort();
}
});
mDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
// By creating a request, we get a handle to the putFile operation,
// so we can cancel it later if we want to
FileInputStream fis = new FileInputStream(mFile);
String path = mPath + mFile.getName();
mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(),
new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 500;
}
#Override
public void onProgress(long bytes, long total) {
publishProgress(bytes);
}
});
if (mRequest != null) {
mRequest.upload();
return true;
}
} catch (DropboxUnlinkedException e) {
// This session wasn't authenticated properly or user unlinked
mErrorMsg = "This app wasn't authenticated properly.";
} catch (DropboxFileSizeException e) {
// File size too big to upload via the API
mErrorMsg = "This file is too big to upload";
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Upload canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
e.printStackTrace();
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
} catch (FileNotFoundException e) {
}
return false;
}
#Override
protected void onProgressUpdate(Long... progress) {
int percent = (int) (100.0 * (double) progress[0] / mFileLen + 0.5);
mDialog.setProgress(percent);
}
#Override
protected void onPostExecute(Boolean result) {
mDialog.dismiss();
if (result) {
showToast("Successfully uploaded");
// mApi.getSession().unlink();
//
// // Clear our stored keys
// clearKeys();
} else {
showToast(mErrorMsg);
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
error.show();
}
private void clearKeys() {
SharedPreferences prefs = mContext.getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
}
Please help.

According to dropbox documentation
try {
// creating folder
val fo = client.files().createFolderV2(File.separator + folderPath)
} catch (ex: CreateFolderErrorException) {
if (ex.errorValue.isPath && ex.errorValue.pathValue.isConflict) {
// folder already exist
}
}

You can simply give like this for creating a folder! its very simple
dropbox.putFile("Mynumber2/myregion2/"+"/"+"A"+"/"+"B"+"/"+"ENTRY.db", fileInputStream,file.length(), null, null);
if you do, mynumber2-->myregion2-->A-->B will be your folder structure created on dropbox!

You want the createFolder method of DropboxAPI. See https://www.dropbox.com/static/developers/dropbox-android-sdk-1.6.1-docs/com/dropbox/client2/DropboxAPI.html#createFolder(java.lang.String).

Use the following for DIR:
"/your_folder_name/"

Related

Threading requires that an application's button be clicked twice

I have the following code. submitClick() is triggered when someone clicks the submit button on my application. In the past, submit click would be click once, and all of submitFile() would be carried out. By adding the threading addition to checkContent(), now submitClick has to be clicked twice for all of submitFile() to be completed. Is there any way to make it so that submitFile() finishes (with checkContent()) so the user only has to press my apps submit button?
Thank you in advance.
public void submitClick(View v) throws Exception{
if (!submitted) { submitFile(); }
}
public void submitFile() {
checkContent();
if (valid) {
Picasso.with(this).load(imageAddress).into(imagePreview);
saveImage();
//sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); //refreshes system to show saved file
submitted = true;
submit_but.setText("Encrypt");
}
}
private void checkContent() {
media = null;
if(URLUtil.isValidUrl(imageAddress)) {
Thread thread = new Thread() {
boolean img = false;
boolean youtube = false;
public void run() {
URLConnection connection = null;
try {
connection = new URL(imageAddress).openConnection();
} catch (IOException e) {
e.printStackTrace();
}
String contentType = connection.getHeaderField("Content-Type");
img = contentType.startsWith("image/");
if(img)
media = "image";
if (!img) {
// Check host of url if youtube exists
Uri uri = Uri.parse(imageAddress);
if ("www.youtube.com".equals(uri.getHost())) {
media = "youtube";
youtube = true;
}
}
valid = img || youtube;
}
};
thread.start();
}
}
The problem is that the Thread will finish after the call to if (valid) and the rest in the submitFile().
Easy fix is to include the entire submitFile() in a Thread, instead of just part of it. If the logic is bound to each other, it's better off that they're together.
A more android-esque fix is to use AsyncTask, as such:
public void submitClick(View v) throws Exception {
if (!submitted) { submitFile(); }
}
public void submitFile() {
if(URLUtil.isValidUrl(imageAddress)) {
new AsyncTask<Void, Void, Boolean>() {
protected Long doInBackground(Void... voids) {
boolean img = false;
boolean youtube = false;
URLConnection connection = null;
try {
connection = new URL(imageAddress).openConnection();
} catch (IOException e) {
e.printStackTrace();
}
String contentType = connection.getHeaderField("Content-Type");
img = contentType.startsWith("image/");
if(img)
media = "image";
if (!img) {
// Check host of url if youtube exists
Uri uri = Uri.parse(imageAddress);
if ("www.youtube.com".equals(uri.getHost())) {
media = "youtube";
youtube = true;
}
}
return img || youtube;
}
protected void onPostExecute(Boolean valid) {
if (valid) {
Picasso.with(this).load(imageAddress).into(imagePreview);
saveImage();
//sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); //refreshes system to show saved file
submitted = true;
submit_but.setText("Encrypt");
}
}
}.execute();
}
}

Can't create handler inside thread that has not called Looper.prepare(). RuntimeExcetion while uploading file to DropBox

I m getting exception "Can't create handler inside thread that has not called Looper.prepare()
in the function doFirstTime().
I m trying to upload my data at Dropbox using Dropbox API
Can you tell me how to fix it?
public class DownloadFile extends AsyncTask<Void, Long, Boolean>
`{
private Context mContext;
private DropboxAPI<?> mApi;
private String mPath;
private FileOutputStream mFos;
private String mErrorMsg;
private StringBuilder xmlcode,newXMLCode;
private final static String FILE_NAME = "fuelrecords.xml";
private final static String ZIP_FILE_NAME = "fuelpad.zip";
private String dropbox_xml_records[];
private ArrayList<ArrayList<String>> dropbox_records;
private ArrayList<ArrayList<String>> database_records;
private ExpenseOperations eop;
private UploadFile up;
private boolean no_file;
public DownloadFile(Context context, DropboxAPI<?> api,String dropboxPath)
{
// We set the context this way so we don't accidentally leak activities
mContext = context.getApplicationContext();
mApi = api;
mPath = dropboxPath;
dropbox_records = new ArrayList<ArrayList<String>>();
database_records = new ArrayList<ArrayList<String>>();
eop = new ExpenseOperations(mContext);
xmlcode=new StringBuilder("");
newXMLCode=new StringBuilder("");
no_file = false;
}
#Override
protected Boolean doInBackground(Void... params)
{
Log.d("yes1", " in do in back of download..");
try
{
// Get the metadata for a directory
Entry dirent = mApi.metadata(mPath, 1000, null, true, null);
if (!dirent.isDir || dirent.contents == null)
{
// It's not a directory, or there's nothing in it
mErrorMsg = "Could not locate the file...";
return false;
}
String cachefilePath = mContext.getCacheDir().getAbsolutePath() + "/" + FILE_NAME;
String cachezipPath = mContext.getCacheDir().getAbsolutePath() + "/" + ZIP_FILE_NAME;
try
{
mFos = new FileOutputStream(cachezipPath);
}
catch (FileNotFoundException e)
{
mErrorMsg = "Couldn't create a local file to store the image";
return false;
}
Notification("SmartExpense", "Now syncing to dropbox");
mApi.getFile("/SmartExpenses.zip",null,mFos,null);
try
{
FileInputStream fin = new FileInputStream(cachezipPath);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
if((ze = zin.getNextEntry()) != null)
{
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory())
{
}
else
{
FileOutputStream fout = new FileOutputStream(cachefilePath);
for (int c = zin.read(); c != -1; c = zin.read())
{
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
}
catch(Exception ee)
{
Log.d("In unzip:", ""+ee);
}
try
{
FileInputStream fs =new FileInputStream(cachefilePath);
byte buff[] =new byte[1024];
while(fs.read(buff)>0)
{
xmlcode.append(new String(buff));
}
fs.close();
Log.d("Hhhhhhhhhhhaaaaaaaaaaaaa : ",""+xmlcode);
Looper.prepare();
if(!(xmlcode.toString().contains("<expenserecord>")) && getDBRecords())
{
doFirstTime();
Log.d("1","1");
}
else if((xmlcode.toString().contains("<expenserecord>")) && getDBRecords())
{
Log.d("2","2");
makeDropboxRecordArray();
performSync();
}
else if((xmlcode.toString().contains("<expenserecord>")) && !getDBRecords())
{
Log.d("3","3");
makeDropboxRecordArray();
fillDBwithDropboxRecords();
}
else if(!(xmlcode.toString().contains("<expenserecord>")) && !getDBRecords())
{
Log.d("4","4");
mErrorMsg ="No records exist to sync";
}
}
catch (Exception e)
{
Log.d("Exception in doback: ",""+e);
}
return true;
}
catch (DropboxUnlinkedException e)
{
mErrorMsg = "Error :Dropbox unliked";
// The AuthSession wasn't properly authenticated or user unlinked.
}
catch (DropboxPartialFileException e)
{
// We canceled the operation
mErrorMsg = "Download canceled";
}
catch (DropboxServerException e)
{
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._304_NOT_MODIFIED)
{
mErrorMsg = "Server Error.....";
// won't happen since we don't pass in revision with metadata
}
else if (e.error == DropboxServerException._401_UNAUTHORIZED)
{
mErrorMsg = "Server Error : Unautherized user...";
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
}
else if (e.error == DropboxServerException._403_FORBIDDEN)
{
mErrorMsg = "Server Error : Access denied";
// Not allowed to access this
}
else if (e.error == DropboxServerException._404_NOT_FOUND)
{
no_file = true;
doFirstTime();
// path not found
}
else if (e.error == DropboxServerException._406_NOT_ACCEPTABLE)
{
mErrorMsg = "Server Error : Congestion...";
// too many entries to return
}
else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE)
{
// user is over quota
mErrorMsg = "Server Error : Insufficient Storage...";
}
else
{
// Something else
mErrorMsg = "Server Error...";
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null)
{
mErrorMsg = e.body.error;
}
}
catch (DropboxIOException e)
{
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
}
catch (DropboxParseException e)
{
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
}
catch (DropboxException e)
{
// Unknown error
mErrorMsg = "Unknown error. Try again.";
}
return false;
}
public void fillDBwithDropboxRecords()
{
Log.d("In fill db","yetoy");
try
{
for(int i=0 ; i<dropbox_records.size()-1 ; i++)
{
{
eop.addRecord(Integer.parseInt(dropbox_records.get(i).get(0)), dropbox_records.get(i).get(1), dropbox_records.get(i).get(2), Integer.parseInt(dropbox_records.get(i).get(3)));
}
}
}
catch (Exception e)
{
Log.d("In fill db", ""+e);
}
}
private void doFirstTime()
{
Log.d("yes2", " in do first time of download..");
try
{
if(!getDBRecords())
{
mErrorMsg = "No records exist to sync";
return;
}
newXMLCode.append("<smartexpense>");
for(int i=0 ; i<database_records.size() ; i++)
{
newXMLCode.append("<expenserecord>");
newXMLCode.append("<c_id>"+database_records.get(i).get(0)+"</c_id>");
newXMLCode.append("<title>"+database_records.get(i).get(1)+"</title>");
newXMLCode.append("<date>"+database_records.get(i).get(2)+"</date>");
newXMLCode.append("<amount>"+database_records.get(i).get(3)+"</amount>");
newXMLCode.append("</expenserecord>");
}//for
newXMLCode.append("</smartexpense>");
up = new UploadFile(mContext,mApi,newXMLCode.toString());
up.execute();
}
catch(Exception e)
{
Log.d("Exception in doFirtstTime : ",""+e);
}
}//doFirstTime
public void makeDropboxRecordArray()
{
Log.d("yes3", " in make record array of download..");
try
{
dropbox_xml_records = (xmlcode.toString()).split("</expenserecord>");
for(int i=0 ; i< dropbox_xml_records.length ; i++)
{
dropbox_records.add(new ArrayList<String>());
dropbox_records.get(i).add(dropbox_xml_records[i].substring(
((dropbox_xml_records[i].indexOf("<c_id>"))+
("<c_id>".length())),
dropbox_xml_records[i].indexOf("</c_id>")
));
dropbox_records.get(i).add(dropbox_xml_records[i].substring(
((dropbox_xml_records[i].indexOf("<title>"))+
("<title>".length())),
dropbox_xml_records[i].indexOf("</title>")
));
dropbox_records.get(i).add(dropbox_xml_records[i].substring(
((dropbox_xml_records[i].indexOf("<date>"))+
("<date>".length())),
dropbox_xml_records[i].indexOf("</date>")
));
dropbox_records.get(i).add(dropbox_xml_records[i].substring(
((dropbox_xml_records[i].indexOf("<amount>"))+
("<amount>".length())),
dropbox_xml_records[i].indexOf("</amount>")
));
}
}
catch (Exception e)
{
Toast.makeText(mContext,"In fill records :"+e , 2000).show();
}
}
public boolean getDBRecords()
{
Log.d("yes4", " in get dbrecords of download..");
try
{
Cursor cc = eop.getRecords();
if(cc.getCount() == 0)
return false;
int i=0;
if(cc.moveToFirst())
{
do
{
database_records.add(new ArrayList<String>());
database_records.get(i).add(cc.getString(cc.getColumnIndex("c_id")));
database_records.get(i).add(cc.getString(cc.getColumnIndex("title")));
database_records.get(i).add(cc.getString(cc.getColumnIndex("date")));
database_records.get(i).add(cc.getString(cc.getColumnIndex("amount")));
i++;
}while(cc.moveToNext());
}
cc.close();
}
catch(Exception ee)
{
Toast.makeText(mContext,"getDBRecords :"+ee , 2000).show();
}
return true;
}
public void performSync()
{
try
{
//compare database records with dropbox records
newXMLCode.append("<smartexpense>");
for(int i=0 ; i<database_records.size() ; i++)
{
newXMLCode.append("<expenserecord>");
newXMLCode.append("<c_id>"+database_records.get(i).get(0)+"</c_id>");
newXMLCode.append("<title>"+database_records.get(i).get(1)+"</title>");
newXMLCode.append("<date>"+database_records.get(i).get(2)+"</date>");
newXMLCode.append("<amount>"+database_records.get(i).get(3)+"</amount>");
newXMLCode.append("</expenserecord>");
}
for(int i=0 ; i<dropbox_records.size()-1 ; i++)
{
eop.addRecord(Integer.parseInt(dropbox_records.get(i).get(0)),
dropbox_records.get(i).get(1),
dropbox_records.get(i).get(2),
Integer.parseInt(dropbox_records.get(i).get(3)));
newXMLCode.append("<expenserecord>");
newXMLCode.append("<c_id>"+dropbox_records.get(i).get(0)+"</c_id>");
newXMLCode.append("<title>"+dropbox_records.get(i).get(1)+"</title>");
newXMLCode.append("<date>"+dropbox_records.get(i).get(2)+"</date>");
newXMLCode.append("<amount>"+dropbox_records.get(i).get(3)+"</amount>");
newXMLCode.append("</expenserecord>");
}
//}
newXMLCode.append("</smartexpense>");
Log.d("Comming : ","yetoy..");
up = new UploadFile(mContext,mApi,newXMLCode.toString());
up.execute();
}
catch (Exception e)
{
Log.d("Perform sync: ",""+e);
}
}
#Override
protected void onPostExecute(Boolean result)
{
//mDbHelper.close();
if (result)
{
//showToast("File successfully downloaded");
}
else
{
if(!no_file)
{
// Couldn't download it, so show an error
showToast("Error in sync.Check notification.");
Notification("SmartExpense", mErrorMsg);
}
}
}
private void showToast(String msg)
{
Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
error.show();
}
// Notification Function
private void Notification(String notificationTitle, String notificationMessage)
{
NotificationManager notificationManager = (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(android.R.drawable.ic_menu_save, "Dropbox Sync", System.currentTimeMillis());
Intent notificationIntent = new Intent(mContext, UploadFile.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);
notification.setLatestEventInfo(mContext, notificationTitle, notificationMessage, pendingIntent);
notificationManager.notify(10001, notification);
}
}
This error is received while you try and update your UI from a background thread. In your case the doInBackground method.
It appears that you are trying to post a notification from doInBackground from the following line.
Notification("SmartExpense", "Now syncing to dropbox");
This might be causing the issue. Try commenting this and any other UI updates you might be doing in doInBackground
This Exception indicates that you are trying to access UI elements in a non UI thread. From your code probably the problem is caused by these two lines inside your doInBackground method (you are accessing the Activity's context):
String cachefilePath = mContext.getCacheDir().getAbsolutePath() + "/" + FILE_NAME;
String cachezipPath = mContext.getCacheDir().getAbsolutePath() + "/" + ZIP_FILE_NAME;
If you declare this two variables outside the doInBackgroud method and instatiate them in your constructor, you should be ok. Also, remove the lines in your code that you are calling Looper.prepare() since they will not fix the problem.

App freezes with TimerTask with AsyncTask

I have scheduled a AsyncTask using a Timer by following code
public void toCallAsynchronous() {
TimerTask doAsynchronousTask;
final Handler handler = new Handler();
Timer timer = new Timer();
doAsynchronousTask = new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
handler.post(new Runnable() {
public void run() {
try {
if(mLoggedIn)
{
DownloadRandomPicture download = new DownloadRandomPicture(this, mApi, CLIENT_ID, mImage);
download.execute();
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0,50000);//execute in every 50000 ms
}
#Override
protected Boolean doInBackground(Void... params) {
try {
if (mCanceled) {
return false;
}
// Get the metadata for a directory
Entry dirent = mApi.metadata(mPath, 1000, null, true, null);
if (!dirent.isDir || dirent.contents == null) {
// It's not a directory, or there's nothing in it
mErrorMsg = "File or empty directory";
return false;
}
// Make a list of everything in it that we can get a thumbnail for
ArrayList<Entry> thumbs = new ArrayList<Entry>();
for (Entry ent: dirent.contents) {
if (ent.thumbExists) {
// Add it to the list of thumbs we can choose from
thumbs.add(ent);
}
}
if (mCanceled) {
return false;
}
if (thumbs.size() == 0) {
// No thumbs in that directory
mErrorMsg = "No pictures in that directory";
return false;
}
// Now pick a random one
int index = (int)(Math.random() * thumbs.size());
Entry ent = thumbs.get(index);
String path = ent.path;
mFileLen = ent.bytes;
String cachePath = mContext.getCacheDir().getAbsolutePath() + "/" + IMAGE_FILE_NAME;
try {
mFos = new FileOutputStream(cachePath);
} catch (FileNotFoundException e) {
mErrorMsg = "Couldn't create a local file to store the image";
return false;
}
// This downloads a smaller, thumbnail version of the file. The
// API to download the actual file is roughly the same.
mApi.getThumbnail(path, mFos, ThumbSize.BESTFIT_960x640,
ThumbFormat.JPEG, null);
if (mCanceled) {
return false;
}
mDrawable = Drawable.createFromPath(cachePath);
// We must have a legitimate picture
return true;
} catch (DropboxUnlinkedException e) {
// The AuthSession wasn't properly authenticated or user unlinked.
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Download canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._304_NOT_MODIFIED) {
// won't happen since we don't pass in revision with metadata
} else if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._406_NOT_ACCEPTABLE) {
// too many entries to return
} else if (e.error == DropboxServerException._415_UNSUPPORTED_MEDIA) {
// can't be thumbnailed
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
}
return false;
}
I am calling this from onCreate of my activity. My async task basically downloads some data from server. My main activity allows user to login to server and then I go for fetching the data. What I am doing wrong here ? Any idea about it

AsyncTask with Timer keeps on running

I have scheduled a AsyncTask using a Timer by following code
public void toCallAsynchronous() {
TimerTask doAsynchronousTask;
final Handler handler = new Handler();
Timer timer = new Timer();
doAsynchronousTask = new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
handler.post(new Runnable() {
public void run() {
try {
if(mLoggedIn)
{
DownloadRandomPicture download = new DownloadRandomPicture(this, mApi, CLIENT_ID, mImage);
download.execute();
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0,50000);//execute in every 50000 ms
}
#Override
protected Boolean doInBackground(Void... params) {
try {
if (mCanceled) {
return false;
}
// Get the metadata for a directory
Entry dirent = mApi.metadata(mPath, 1000, null, true, null);
if (!dirent.isDir || dirent.contents == null) {
// It's not a directory, or there's nothing in it
mErrorMsg = "File or empty directory";
return false;
}
// Make a list of everything in it that we can get a thumbnail for
ArrayList<Entry> thumbs = new ArrayList<Entry>();
for (Entry ent: dirent.contents) {
if (ent.thumbExists) {
// Add it to the list of thumbs we can choose from
thumbs.add(ent);
}
}
if (mCanceled) {
return false;
}
if (thumbs.size() == 0) {
// No thumbs in that directory
mErrorMsg = "No pictures in that directory";
return false;
}
// Now pick a random one
int index = (int)(Math.random() * thumbs.size());
Entry ent = thumbs.get(index);
String path = ent.path;
mFileLen = ent.bytes;
String cachePath = mContext.getCacheDir().getAbsolutePath() + "/" + IMAGE_FILE_NAME;
try {
mFos = new FileOutputStream(cachePath);
} catch (FileNotFoundException e) {
mErrorMsg = "Couldn't create a local file to store the image";
return false;
}
// This downloads a smaller, thumbnail version of the file. The
// API to download the actual file is roughly the same.
mApi.getThumbnail(path, mFos, ThumbSize.BESTFIT_960x640,
ThumbFormat.JPEG, null);
if (mCanceled) {
return false;
}
mDrawable = Drawable.createFromPath(cachePath);
// We must have a legitimate picture
return true;
} catch (DropboxUnlinkedException e) {
// The AuthSession wasn't properly authenticated or user unlinked.
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Download canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._304_NOT_MODIFIED) {
// won't happen since we don't pass in revision with metadata
} else if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._406_NOT_ACCEPTABLE) {
// too many entries to return
} else if (e.error == DropboxServerException._415_UNSUPPORTED_MEDIA) {
// can't be thumbnailed
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
}
return false;
}
protected void onProgressUpdate(Long... progress) {
int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
//mDialog.setProgress(percent);
}
#Override
protected void onPostExecute(Boolean result) {
//mDialog.dismiss();
if (result) {
// Set the image now that we have it
mView.setImageDrawable(mDrawable);
} else {
// Couldn't download it, so show an error
showToast(mErrorMsg);
}
}
I am calling this from onCreate of my activity. My async task basically downloads some data from server. Main activity allows user to login to server and then I go for fetching the data. The problem that I am facing is that each AsyncTask creates its own thread. Also, none of those goes to completion.The thread status is always running. Is there a way to check that the new AsyncTask is only launched when the earlier is finished.
Following links can helps you, please have a look, Thanks.
Android: Can I chain Async task sequentially (starting one after the previous asynctask completes)
and
Android calling AsyncTask right after an another finished
Try this way
public ArrayBlockingQueue<Runnable> threadList = new ArrayBlockingQueue<Runnable>(
2000, true);
public ThreadPoolExecutor threadPool = new ThreadPoolExecutor(0,
2000, 1000, TimeUnit.MILLISECONDS, threadList);
TimerTask t=new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
//your code here
}
};
ThreadPool.execute(t);
The line timer.schedule(doAsynchronousTask, 0,50000);//execute in every 50000 ms is responsible for the repetitive task.
As per the description of Timer class's schedule( TimerTaskObject, int start, int repete ) method , this will repeat a particular TimerTask for the defined time interval, i suggest you to change it as follows,
timer.schedule(doAsynchronousTask, 1000);//execute once after one second

Async Task Network Error

I am creating an android application that uses async task to login and send data(HTTP Post Request. The application works fine when internet connection is good but when logging and it takes too long to post data due to slow connection the application force closes. i would like to display a toast "Error in Connection" when this happens. Please Help
Your application probably crashes, because you are trying to show Toast not in a UI Thread. That is you always should make any changes to UI by using Handler, or within onPostExecute() method, which also runs in UI Thread.
How to catch exceptions in doInBackground's thread and represent them in UI Thread is another question, I can suggest you this solution:
private class LoginTask extends
AsyncTask<Void, Integer, JSONArray[]> {
private static final int NETWORK_NO_ERROR = -1;
private static final int NETWORK_HOST_UNREACHABLE = 1;
private static final int NETWORK_NO_ACCESS_TO_INTERNET = 2;
private static final int NETWORK_TIME_OUT = 3;
// You can continue this list...
Integer serverError = NETWORK_NO_ERROR;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show(); // Don't forget to create it before
}
#Override
protected JSONArray[] doInBackground(Void... v) {
JSONArray[] result = null;
try {
result = NetworkManager.login(/* All params you need */);
} catch (JSONException e) {
return null;
} catch (ConnectException e) {
serverError = NETWORK_NO_ACCESS_TO_INTERNET;
return null;
} catch (UnknownHostException e) {
serverError = NETWORK_HOST_UNREACHABLE;
return null;
} catch (SocketTimeoutException e) {
serverError = NETWORK_TIME_OUT;
return null;
} catch (URISyntaxException e) {
// ..
return null;
} catch (ClientProtocolException e) {
// ..
return null;
} catch (Exception e) {
// ..
return null;
}
return result;
}
#Override
protected void onPostExecute(JSONArray[] result) {
progressDialog.dismiss();
if (result != null) {
processAndShowResult(result);
} else {
switch (serverError) {
case NETWORK_NO_ERROR:
Toast.makeText(YourActivity.this, "Probably, invalid response from server", Toast.LENGTH_LONG).show();
break;
case NETWORK_NO_ACCESS_TO_INTERNET:
// You can customize error message (or behavior) for different type of error
case NETWORK_TIME_OUT:
case NETWORK_HOST_UNREACHABLE:
Toast.makeText(YourActivity.this, "Error in Connection", Toast.LENGTH_LONG).show();
break;
}
}
}
}
By this means, you can flexibly control network errors and undertake appropriate actions, according to these errors.

Categories

Resources