Get the share image file url from dropbox -android Programatically -


i uploading image files dropbox.

while uploading images android app dropbox, want dropbox share url link of each image.

then want save link in local database.

anyone me how programatically.

my upload picture code dropbox

mainactivity .java

public class mainactivity extends actionbaractivity  {     private static final string tag = "my dropbox app";       private static final string app_key = "************";     private static final string app_secret = "***************";     // don't need change these, leave them alone.     private static final string account_prefs_name = "prefs";     private static final string access_key_name = "access_key";     private static final string access_secret_name = "access_secret";      private static final boolean use_oauth1 = false;      dropboxapi<androidauthsession> dropboxapi;      private boolean mloggedin;      // android widgets     private button msubmit;     private linearlayout mdisplay;     private button mphoto;     private button mroulette;      private imageview mimage;      private final string photo_dir = "/photos/myphotos/";      private static final int new_picture = 1;     private string mcamerafilename;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);          if (savedinstancestate != null)          {             mcamerafilename = savedinstancestate.getstring("mcamerafilename");         }          // create new authsession can use dropbox api.         androidauthsession session = buildsession();         dropboxapi = new dropboxapi<androidauthsession>(session);          // basic android widgets         setcontentview(r.layout.activity_main);          checkappkeysetup();          msubmit = (button) findviewbyid(r.id.auth_button);          msubmit.setonclicklistener(new onclicklistener() {             public void onclick(view v) {                 // logs out if you're logged in, or vice versa                 if (mloggedin) {                     logout();                 } /*                  * else { // start remote authentication if (use_oauth1) {                  * mapi.getsession().startauthentication(dbroulette.this); }                  * else {                  * mapi.getsession().startoauth2authentication(dbroulette.this);                  * } }                  */             }         });          mdisplay = (linearlayout) findviewbyid(r.id.logged_in_display);          // photo displayed         mimage = (imageview) findviewbyid(r.id.image_view);          // button take photo         mphoto = (button) findviewbyid(r.id.photo_button);          mphoto.setonclicklistener(new onclicklistener() {             public void onclick(view v)              {                 intent intent = new intent();                 // picture camera                 intent.setaction(mediastore.action_image_capture);                  // not right way this, reason,                 // having                 // store in                 // mediastore.images.media.external_content_uri isn't working                 // right.                  date date = new date();                 dateformat df = new simpledateformat("yyyy-mm-dd-kk-mm-ss");                  string newpicfile = df.format(date) + ".jpg";                 log.i(tag, newpicfile);                 string outpath = new file(environment                         .getexternalstoragedirectory(), newpicfile).getpath();                 file outfile = new file(outpath);                  mcamerafilename = outfile.tostring();                 uri outuri = uri.fromfile(outfile);                 intent.putextra(mediastore.extra_output, outuri);                 log.i(tag, "importing new picture: " + mcamerafilename);                 try {                     startactivityforresult(intent, new_picture);                 } catch (activitynotfoundexception e) {                     showtoast("there doesn't seem camera.");                 }             }         });          // button download photo         mroulette = (button) findviewbyid(r.id.roulette_button);          mroulette.setonclicklistener(new onclicklistener() {             public void onclick(view v) {                 downloadrandompicture download = new downloadrandompicture(                         mainactivity.this, dropboxapi, photo_dir, mimage);                 download.execute();             }         });          // display proper ui state if logged in or not         setloggedin(dropboxapi.getsession().islinked());      }      @override     protected void onsaveinstancestate(bundle outstate) {         outstate.putstring("mcamerafilename", mcamerafilename);         super.onsaveinstancestate(outstate);     }      @override     protected void onresume() {         super.onresume();         androidauthsession session = dropboxapi.getsession();          // next part must inserted in onresume() method of         // activity session.startauthentication() called,         // dropbox authentication completes properly.         if (session.authenticationsuccessful()) {             try {                 // mandatory call complete auth                 session.finishauthentication();                  // store locally in our app later use                 storeauth(session);                 setloggedin(true);             } catch (illegalstateexception e) {                 showtoast("couldn't authenticate dropbox:"                         + e.getlocalizedmessage());                 log.i(tag, "error authenticating", e);             }         }     }      // gets called on finishing media piece import     @override     public void onactivityresult(int requestcode, int resultcode, intent data) {         if (requestcode == new_picture) {             // return file upload             if (resultcode == activity.result_ok) {                 uri uri = null;                 if (data != null) {                     uri = data.getdata();                 }                 if (uri == null && mcamerafilename != null) {                     uri = uri.fromfile(new file(mcamerafilename));                 }                 file file = new file(mcamerafilename);                  if (uri != null) {                     uploadpicture upload = new uploadpicture(this, dropboxapi,                             photo_dir, file);                     upload.execute();                 }             } else {                 log.w(tag, "unknown activity result mediaimport: "                         + resultcode);             }         }     }      private void logout() {         // remove credentials session         dropboxapi.getsession().unlink();          // clear our stored keys         clearkeys();         // change ui state display logged out version         setloggedin(false);     }      /**      * convenience function change ui state based on being logged in      */     private void setloggedin(boolean loggedin) {         mloggedin = loggedin;         if (loggedin) {             msubmit.settext("unlink dropbox");             mdisplay.setvisibility(view.visible);         } else {             msubmit.settext("link dropbox");             mdisplay.setvisibility(view.gone);             mimage.setimagedrawable(null);         }     }      private void checkappkeysetup() {         // check make sure have valid app key         if (app_key.startswith("change") || app_secret.startswith("change")) {             showtoast("you must apply app key , secret developers.dropbox.com, , add them dbroulette ap before trying it.");             finish();             return;         }          // check if app has set manifest properly.         intent testintent = new intent(intent.action_view);         string scheme = "db-" + app_key;         string uri = scheme + "://" + authactivity.auth_version + "/test";         testintent.setdata(uri.parse(uri));         packagemanager pm = getpackagemanager();         if (0 == pm.queryintentactivities(testintent, 0).size()) {             showtoast("url scheme in app's "                     + "manifest not set correctly. should have "                     + "com.dropbox.client2.android.authactivity "                     + "scheme: " + scheme);             finish();         }     }      private void showtoast(string msg) {         toast error = toast.maketext(this, msg, toast.length_long);         error.show();     }      /**      * shows keeping access keys returned trusted authenticator in      * local store, rather storing user name & password, ,      * re-authenticating each time (which not done, ever).      */     private void loadauth(androidauthsession session) {         sharedpreferences prefs = getsharedpreferences(account_prefs_name, 0);         string key = "oauth2:";         string secret = "**************";         if (key == null || secret == null || key.length() == 0                 || secret.length() == 0)             return;          if (key.equals("oauth2:")) {             // if key set "oauth2:", can assume token             // oauth 2.             session.setoauth2accesstoken(secret);         } else {             // still support using old oauth 1 tokens.             session.setaccesstokenpair(new accesstokenpair(key, secret));         }     }      /**      * shows keeping access keys returned trusted authenticator in      * local store, rather storing user name & password, ,      * re-authenticating each time (which not done, ever).      */     private void storeauth(androidauthsession session) {         // store oauth 2 access token, if there one.         string oauth2accesstoken = "****************";         if (oauth2accesstoken != null) {             sharedpreferences prefs = getsharedpreferences(account_prefs_name,                     0);             editor edit = prefs.edit();             edit.putstring(access_key_name, "oauth2:");             edit.putstring(access_secret_name, oauth2accesstoken);             edit.commit();             return;         }         // store oauth 1 access token, if there one.         // necessary if         // you're still using oauth 1.         accesstokenpair oauth1accesstoken = session.getaccesstokenpair();         if (oauth1accesstoken != null) {             sharedpreferences prefs = getsharedpreferences(account_prefs_name,                     0);             editor edit = prefs.edit();             edit.putstring(access_key_name, oauth1accesstoken.key);             edit.putstring(access_secret_name, oauth1accesstoken.secret);             edit.commit();             return;         }     }      private void clearkeys() {         sharedpreferences prefs = getsharedpreferences(account_prefs_name, 0);         editor edit = prefs.edit();         edit.clear();         edit.commit();     }      private androidauthsession buildsession() {         appkeypair appkeypair = new appkeypair(app_key, app_secret);          androidauthsession session = new androidauthsession(appkeypair);         loadauth(session);         return session;     } } 

uploadpicture .java

public class uploadpicture extends asynctask<void, long, boolean> {      private dropboxapi<?> mapi;     private string mpath;     private file mfile;      private long mfilelen;     private uploadrequest mrequest;     private context mcontext;     private final progressdialog mdialog;      private string merrormsg;       public uploadpicture(context context, dropboxapi<?> api, string dropboxpath,             file file) {         // set context way don't accidentally leak activities         mcontext = context.getapplicationcontext();          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(progressdialog.button_positive, "cancel", new onclicklistener() {             @override             public void onclick(dialoginterface dialog, int which) {                 // cancel putfile operation                 mrequest.abort();             }         });         mdialog.show();     }      @override     protected boolean doinbackground(void... params) {         try {             // creating request, handle putfile operation,             // can cancel later if want             fileinputstream fis = new fileinputstream(mfile);             string path = mpath + mfile.getname();             mrequest = mapi.putfileoverwriterequest(path, fis, mfile.length(),new progresslistener()             {                 @override                 public long progressinterval()                 {                     // update progress bar every half-second or                     return 500;                 }                  @override                 public void onprogress(long bytes, long total)                  {                     publishprogress(bytes);                 }             });              if (mrequest != null)              {                  mrequest.upload();                 return true;             }             } catch (dropboxunlinkedexception e) {             // session wasn't authenticated or user unlinked             merrormsg = "this app wasn't authenticated properly.";         } catch (dropboxfilesizeexception e) {             // file size big upload via api             merrormsg = "this file big upload";         } catch (dropboxpartialfileexception e) {             // canceled operation             merrormsg = "upload canceled";         } catch (dropboxserverexception e) {             // server-side exception.  these examples of happen,             // don't special them here.             if (e.error == dropboxserverexception._401_unauthorized) {                 // unauthorized, should unlink them.  may want                 // automatically log user out in case.             } else if (e.error == dropboxserverexception._403_forbidden) {                 // not allowed access             } else if (e.error == dropboxserverexception._404_not_found) {                 // path not found (or if thumbnail, can't                 // thumbnailed)             } else if (e.error == dropboxserverexception._507_insufficient_storage) {                 // user on quota             } else {                 // else             }             // gets dropbox error, translated user's language             merrormsg = e.body.usererror;             if (merrormsg == null) {                 merrormsg = e.body.error;             }         } catch (dropboxioexception e) {             // happens time, want retry automatically.             merrormsg = "network error.  try again.";         } catch (dropboxparseexception e) {             // due 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("image uploaded");         } else {             showtoast(merrormsg);         }     }      private void showtoast(string msg) {         toast error = toast.maketext(mcontext, msg, toast.length_long);         error.show();     } 

need modify uploadpicture class:

  1. extract field variable:

    string path = mpath + mfile.getname(); 
  2. put snippet onpostexecute method in upload successful case:

    dropboxapi.entry filesinpath = mapi.metadata(path, 1, null, true, null);  // basing on provided code, 1 file uploaded dropboxapi.entry uploadedfile = entries.contents.get(0);  string shareurl = mapi.share(uploadedfile.path).url; 

after manipulations shareurl variable contain sharing link image.


Comments

Popular posts from this blog

How to connect android app to App engine -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

php - display validation error message next to the textbox in codeigniter -