dropbox application for android - android

i have made an application that gives user option to upload and download dropbox application. i am giving my app secret and app key. the question is when some one else use my application do they need to enter their app secret and app key?
if yes, why? and if no then whats the actual purpose of app secret and app key. i am sharing the code as well:
upload file:
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.DropboxAPI.UploadRequest;
import com.dropbox.client2.ProgressListener;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.exception.DropboxFileSizeException;
import com.dropbox.client2.exception.DropboxIOException;
import com.dropbox.client2.exception.DropboxParseException;
import com.dropbox.client2.exception.DropboxPartialFileException;
import com.dropbox.client2.exception.DropboxServerException;
import com.dropbox.client2.exception.DropboxUnlinkedException;
/**
* Here we show uploading a file in a background thread, trying to show
* typical exception handling and flow of control for an app that uploads a
* file from Dropbox.
*/
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 final ProgressDialog mDialog;
private String mErrorMsg;
public UploadFile(Context context, DropboxAPI<?> api, String dropboxPath,
File file) {
// We set the context this way so we 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) {
// 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) {
// 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("File successfully uploaded");
} else {
showToast(mErrorMsg);
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
error.show();
}
}
Download file:
/**
* Here we show getting metadata for a directory and downloading a file in a
* background thread, trying to show typical exception handling and flow of
* control for an app that downloads a file from Dropbox.
*/
public class DownloadFile extends AsyncTask<Void, Long, Boolean> {
private Context mContext;
private final ProgressDialog mDialog;
private DropboxAPI<?> mApi;
private String mPath;
private ImageView mView;
private Drawable mDrawable;
private FileOutputStream mFos;
private boolean mCanceled;
private Long mFileLen;
private String mErrorMsg;
// Note that, since we use a single file name here for simplicity, you
// won't be able to use this code for two simultaneous downloads.
private final static String IMAGE_FILE_NAME = "dbroulette.png";
private String localFilePath;
private String dropboxPath;
public DownloadFile(Context context, DropboxAPI<?> api,
String dropboxPath, String localFilePath) {
// We set the context this way so we don't accidentally leak activities
mContext = context.getApplicationContext();
this.localFilePath = localFilePath;
this.dropboxPath= dropboxPath;
mApi = api;
mPath = dropboxPath;
mDialog = new ProgressDialog(context);
mDialog.setMessage("Downloading File");
mDialog.setButton("Cancel", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mCanceled = true;
mErrorMsg = "Canceled";
// This will cancel the getThumbnail operation by closing
// its stream
if (mFos != null) {
try {
mFos.close();
} catch (IOException e) {
}
}
}
});
mDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
try{
File localFile = new File(localFilePath);
File fileSelected = new File(dropboxPath);
if (!localFile.exists()) {
localFile.createNewFile();
} else {
//copy(fileSelected, localFile);
//mApi.copy("/Test/test.png", "/sdcard/testfile.png");
BufferedInputStream br = null;
BufferedOutputStream bw = null;
DropboxInputStream fd;
try {
fd = mApi.getFileStream(fileSelected.getPath(), null);
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);
}
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}/*
else {
showToast("File already exists");
}*/
}
catch (IOException e) {
showToast("Exception");
e.printStackTrace();
}
catch (Exception e) {
showToast("Exception");
e.printStackTrace();
}
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) {
// Set the image now that we have it
//mView.setImageDrawable(mDrawable);
showToast("Successful download");
} else {
// Couldn't download it, so show an error
showToast(mErrorMsg);
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
error.show();
}
}
main activity:
public class MainActivity extends Activity {
// Replace this with your app key and secret assigned by Dropbox.
// Note that this is a really insecure way to do this, and you shouldn't
// ship code which contains your key & secret in such an obvious way.
// Obfuscation is good.
final static private String APP_KEY = "";
final static private String APP_SECRET = "";
// You don't need to change these, leave them alone.
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 static final boolean USE_OAUTH1 = false;
DropboxAPI<AndroidAuthSession> mApi;
private boolean mLoggedIn;
private Button mSubmit;
private Button btnUpload;
private Button btnDownload;
private LinearLayout mDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We create a new AuthSession so that we can use the Dropbox API.
AndroidAuthSession session = buildSession();
mApi = new DropboxAPI<AndroidAuthSession>(session);
setContentView(R.layout.main);
mSubmit = (Button)findViewById(R.id.auth_button);
btnDownload = (Button)findViewById(R.id.roulette_button);
btnUpload = (Button)findViewById(R.id.photo_button);
mDisplay = (LinearLayout)findViewById(R.id.logged_in_display);
mSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mLoggedIn) {
logOut();
} else {
// Start the remote authentication
if (USE_OAUTH1) {
mApi.getSession().startAuthentication(MainActivity.this);
} else {
mApi.getSession().startOAuth2Authentication(MainActivity.this);
}
}
}
});
// Upload File
String testFile = "DeviceAdmin.apk";
String outPath = new File(Environment.getExternalStorageDirectory(), testFile).getPath();
Toast.makeText(MainActivity.this, outPath, Toast.LENGTH_LONG).show();
final File outFile = new File(outPath);
btnUpload.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try{
UploadFile upload = new UploadFile(MainActivity.this, mApi, "/Test/", outFile);
upload.execute();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "File not found", Toast.LENGTH_LONG).show();
}
}
});
// Download File
final String localFilePath = "/sdcard/testfile.txt";
final String dropboxPath= "/abc.txt";
btnDownload.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
DownloadFile download = new DownloadFile(MainActivity.this, mApi, dropboxPath, localFilePath);
download.execute();
}
});
setLoggedIn(mApi.getSession().isLinked());
}
private void setLoggedIn(boolean loggedIn) {
mLoggedIn = loggedIn;
if (loggedIn) {
Toast.makeText(MainActivity.this, "Successful login", Toast.LENGTH_LONG).show();
mDisplay.setVisibility(View.VISIBLE);
} else {
Toast.makeText(MainActivity.this, "logged out", Toast.LENGTH_LONG).show();
mDisplay.setVisibility(View.GONE);
}
}
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
loadAuth(session);
return session;
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a local
* store, rather than storing user name & password, and re-authenticating each
* time (which is not to be done, ever).
*/
private void loadAuth(AndroidAuthSession session) {
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 || key.length() == 0 || secret.length() == 0) return;
if (key.equals("oauth2:")) {
// If the key is set to "oauth2:", then we can assume the token is for OAuth 2.
session.setOAuth2AccessToken(secret);
} else {
// Still support using old OAuth 1 tokens.
session.setAccessTokenPair(new AccessTokenPair(key, secret));
}
}
#Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = mApi.getSession();
// The next part must be inserted in the onResume() method of the
// activity from which session.startAuthentication() was called, so
// that Dropbox authentication completes properly.
if (session.authenticationSuccessful()) {
try {
// Mandatory call to complete the auth
session.finishAuthentication();
// Store it locally in our app for later use
storeAuth(session);
setLoggedIn(true);
} catch (IllegalStateException e) {
Toast.makeText(MainActivity.this, "Couldn't authenticate with Dropbox:" + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
Log.i("Exception: ", "Error authenticating", e);
}
}
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a local
* store, rather than storing user name & password, and re-authenticating each
* time (which is not to be done, ever).
*/
private void storeAuth(AndroidAuthSession session) {
// Store the OAuth 2 access token, if there is one.
String oauth2AccessToken = session.getOAuth2AccessToken();
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 the OAuth 1 access token, if there is one. This is only 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 void logOut() {
// Remove credentials from the session
mApi.getSession().unlink();
// Clear our stored keys
clearKeys();
// Change UI state to display logged out version
setLoggedIn(false);
}
}
this is the code for reference, please have a look and give some suggestion.my main task is to retrieve a file, encrypt and upload it on dropbox.

No, users don't have to enter a different app key and secret. The app key and secret identifies your app. For example, when a user authorizes your app, they see the name of the app they're authorizing. That comes from the app key.

Related

How to save session of dropbox api in android

I am uploading a file in the dropbox using dropbox api in android. I have successfully uploaded file in the dropbox but problem is that each time i need to allow the access of dropbox. Each time i have to go to the browser and allow the access.
I dont know how to solve this issue.
I have used these codes to upload files in dropbox:
public class DropboxFileUploadMainForContact extends Activity {
private static final int TAKE_PHOTO = 1;
final String DIR = "/";
private File f;
private boolean mLoggedIn, onResume;
public DropboxAPI<AndroidAuthSession> mApi;
String upload_filepath = "abc/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get the file which we want to upload
Bundle b = getIntent().getExtras();
upload_filepath = upload_filepath + b.getString("fileNameToUpload");
AndroidAuthSession session = buildSession();
mApi = new DropboxAPI<AndroidAuthSession>(session);
setLoggedIn(false);
createDir();
if (mLoggedIn) {
logOut();
}
if (Utils.isOnline(DropboxFileUploadMainForContact.this)) {
mApi.getSession().startAuthentication(DropboxFileUploadMainForContact.this);
onResume = true;
} else {
Utils.showNetworkAlert(DropboxFileUploadMainForContact.this);
finish();
}
}
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(Constants.DROPBOX_APP_KEY,
Constants.DROPBOX_APP_SECRET);
AndroidAuthSession session;
String[] stored = getKeys();
if (stored != null) {
AccessTokenPair accessToken = new AccessTokenPair(stored[0],
stored[1]);
session = new AndroidAuthSession(appKeyPair, Constants.ACCESS_TYPE,
accessToken);
} else {
session = new AndroidAuthSession(appKeyPair, Constants.ACCESS_TYPE);
}
return session;
}
private String[] getKeys() {
SharedPreferences prefs = getSharedPreferences(
Constants.ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(Constants.ACCESS_KEY_NAME, null);
String secret = prefs.getString(Constants.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;
}
}
private void logOut() {
mApi.getSession().unlink();
clearKeys();
}
private void clearKeys() {
SharedPreferences prefs = getSharedPreferences(
Constants.ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
private void createDir() {
File dir = new File(Utils.getPath());
if (!dir.exists()) {
dir.mkdirs();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == TAKE_PHOTO) {
// f = new File(Utils.getPath() + "/temp.jpg");
if (Utils.isOnline(DropboxFileUploadMainForContact.this)) {
mApi.getSession().startAuthentication(
DropboxFileUploadMainForContact.this);
onResume = true;
} else {
Utils.showNetworkAlert(DropboxFileUploadMainForContact.this);
}
}
}
}
public void setLoggedIn(boolean loggedIn) {
mLoggedIn = loggedIn;
if (loggedIn) {
// new
// Now make a backup file of sms
// BackUpAllSms();
DropboxFileUpload uploadFile = new DropboxFileUpload(this, mApi,
DIR, upload_filepath);
uploadFile.execute();
onResume = false;
finish();
}
}
private void storeKeys(String key, String secret) {
SharedPreferences prefs = getSharedPreferences(
Constants.ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(Constants.ACCESS_KEY_NAME, key);
edit.putString(Constants.ACCESS_SECRET_NAME, secret);
edit.commit();
}
private void showToast(String msg) {
Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
error.show();
}
#Override
protected void onResume() {
try {
AndroidAuthSession session = mApi.getSession();
Log.d("ppp", "session.authenticationSuccessful() on resume = "+session.authenticationSuccessful());
if (session.authenticationSuccessful()) {
try {
session.finishAuthentication();
TokenPair tokens = session.getAccessTokenPair();
storeKeys(tokens.key, tokens.secret);
setLoggedIn(onResume);
} catch (IllegalStateException e) {
showToast("Couldn't authenticate with Dropbox:"
+ e.getLocalizedMessage());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onResume();
}
}
Could anyone tell me how to solve this issue??
In order to avoid having to authorize the app to connect to the user's Dropbox account manually each time (i.e., calling startAuthentication), the app should store and re-use the resulting access token, so that this only needs to be done once.
It seems you already have code to do this in buildSession, using storeKeys and getKeys, which use SharedPreferences to persist the access token.
So, you just need to know if the AndroidAuthSession already has an access token loaded. You can use the AndroidAuthSession.isLinked method for this:
https://www.dropboxstatic.com/static/developers/dropbox-android-sdk-1.6.3-docs/com/dropbox/client2/session/AbstractSession.html#isLinked()
Call that before calling startAuthentication so you can know if you already have an access token.

How to integrate Google Plus and Facebook Authentication together in the same activity of Android project?

I need to to integrate both Facebook and Google Plus in the same activity but I'm not getting success in it. I have tried both in individual projects and they work fine but when I add both projects together my app gets crashed. Even I have tried them with custom buttons too but they don't work either.
Currently my Facebook part is working fine but I get error when I click on Google's button at the time of login. I get error in these methods:
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
and
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
I'm implementing in this class:
public class LoginActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
// Your Facebook APP ID
private static String APP_ID = "XXXXXXXXXXXXXXX"; // Replace with your App
// ID
LinearLayout ll;
// Strings of Facebook
String fb_mUserId = "", fb_mUserToken = "", fb_mUserName = "",
fb_mUserEmail = "", fb_verified_value = "", fb_Task_message;
boolean fb_verified, google_verified;
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
#SuppressWarnings("unused")
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
EditText edittext_username, edittext_password;
Button Btn_login, Btn_register;
TextView Text_univesity, errorMsg, tv_forget_password;
LinearLayout ll_google, ll_fb;
static String Username, password, name, Twilio_Id = "",
name_candidate = "", phone_no = "", email_candidate = "",
country = "", mobile_verification = "", fb_id = "";
ImageView im;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
int id, Mode = 0, fb_clicked = 0, google_clicked = 0;
static int user_ids;
String IMEI_number;
GPSTracker gps;
static double latitude = 0.00, longitude = 0.00;
Context context;
private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG = "LoginActivity";
// Profile pic image size in pixels
// private static final int PROFILE_PIC_SIZE = 400;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
/**
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
// Strings of Google Plus
String google_email="", google_id="", google_name="", google_verified_value="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
IMEI_number = telephonyManager.getDeviceId();
im = (ImageView) findViewById(R.id.header);
mAsyncRunner = new AsyncFacebookRunner(facebook);
if (Mode == 3) {
if (login_details.contains("name")) {
name = login_details.getString("name", "");
Intercom.client().registerIdentifiedUser(
new Registration().withUserId(name));
} else {
Intercom.client().registerIdentifiedUser(
new Registration().withUserId("123456"));
}
// We're logged in, we can register the user with Intercom
// Carry on as normal
Intent mode = new Intent(LoginActivity.this, MenuItems.class);
startActivity(mode);
finish();
} else {
edittext_password = (EditText) findViewById(R.id.et_login_password);
Btn_login = (Button) findViewById(R.id.btn_login);
Btn_register = (Button) findViewById(R.id.btn_login_register);
ll_fb = (LinearLayout) findViewById(R.id.login_fb);
ll_google = (LinearLayout) findViewById(R.id.login_google);
tv_forget_password = (TextView) findViewById(R.id.tv_login_forget_password);
Btn_login.setOnClickListener(this);
Btn_register.setOnClickListener(this);
ll_fb.setOnClickListener(this);
ll_google.setOnClickListener(this);
tv_forget_password.setOnClickListener(this);
// Initializing google plus api client
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_PROFILE).build();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_login:
// Direct Login Process
break;
case R.id.btn_login_register:
// Direct register process
finish();
break;
case R.id.login_fb:
fb_clicked++;
loginToFacebook();
getProfileInformation();
if (!fb_mUserEmail.equals("")) {
if (fb_verified == true) {
fb_verified_value = "1";
} else {
fb_verified_value = "0";
}
new FacebookAsynTask().execute();
}
break;
case R.id.login_google:
google_clicked++;
signInWithGplus();
// getGoogleProfileInformation();
if (!google_email.equals("")) {
if (google_verified == true) {
google_verified_value = "1";
} else {
google_verified_value = "0";
}
new GoogleAsynTask().execute();
}
break;
case R.id.tv_login_forget_password:
break;
}
}
#Override
protected void onResume() {
super.onResume();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/** LOGIN TO FACEBOOK */
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
Log.d("FB Sessions", "" + facebook.isSessionValid());
Toast.makeText(LoginActivity.this, "FIRST CASE", Toast.LENGTH_SHORT)
.show();
getProfileInformation();
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_actions" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
Toast.makeText(LoginActivity.this, "SECOND CASE",
Toast.LENGTH_SHORT).show();
getProfileInformation();
// Making Login button invisible
}
public void onError(DialogError error) {
// Function to handle error
}
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (fb_clicked != 0) {
facebook.authorizeCallback(requestCode, resultCode, data);
fb_clicked = 0;
}
else if (google_clicked != 0) {
if (requestCode == RC_SIGN_IN) {
if (resultCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
google_clicked = 0;
}
}
/**
* Get Profile information by making request to Facebook Graph API
* */
public void getProfileInformation() {
try {
JSONObject profile = Util.parseJson(facebook.request("me"));
Log.e("Profile", "" + profile);
fb_mUserId = profile.getString("id");
fb_verified = profile.getBoolean("verified");
fb_mUserToken = facebook.getAccessToken();
fb_mUserName = profile.getString("name");
fb_mUserEmail = profile.getString("email");
runOnUiThread(new Runnable() {
public void run() {
Log.e("FaceBook_Profile", "" + fb_mUserId + "\n"
+ fb_mUserToken + "\n" + fb_mUserName + "\n"
+ fb_mUserEmail);
}
});
} catch (FacebookError e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/** AsyncTask of Direct Login */
class FacebookAsynTask extends AsyncTask<Void, Void, Void> {
}
/** GOOGLE's CODE STARTS */
/**
* Sign-in into google
* */
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
// Get user's information
getGoogleProfileInformation();
// Update the UI after signin
// updateUI(true);
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
// updateUI(false);
}
/**
* Fetching user's information name, email, profile pic
* */
private void getGoogleProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
google_name = currentPerson.getDisplayName();
google_id = currentPerson.getId();
google_verified = currentPerson.isVerified();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
google_email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + google_name + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + google_email
+ ", Image: " + personPhotoUrl);
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
class GoogleAsynTask extends AsyncTask<Void, Void, Void> {
}
It would be great if anybody helps me in it.
Thanks.
I've solved my problem myself yesterday by adding few lines in onClick part
if (mGoogleApiClient.isConnected()) {
getProfileInformation();
} else {
signInWithGplus();
getProfileInformation();
}
}
It appears that if you call signInWithGplus() the first time, it'll try to access mConnectionResult which is null at that point.
The reason for that is because you're only setting it in onConnectionFailed() which would have not been called.

Get the share image file url from dropbox -android Programatically

I am Uploading image files to Dropbox.
while uploading the images from android app to Dropbox, i want the Dropbox share Url link of each image.
then i want to save that link in local database.
Anyone Help me How to get this programatically.
my upload picture code to 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 = "***************";
// You don't need to 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");
}
// We create a new AuthSession so that we can use the 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) {
// This logs you out if you're logged in, or vice versa
if (mLoggedIn) {
logOut();
} /*
* else { // Start the remote authentication if (USE_OAUTH1) {
* mApi.getSession().startAuthentication(DBRoulette.this); }
* else {
* mApi.getSession().startOAuth2Authentication(DBRoulette.this);
* } }
*/
}
});
mDisplay = (LinearLayout) findViewById(R.id.logged_in_display);
// This is where a photo is displayed
mImage = (ImageView) findViewById(R.id.image_view);
// This is the button to take a photo
mPhoto = (Button) findViewById(R.id.photo_button);
mPhoto.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
Intent intent = new Intent();
// Picture from camera
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
// This is not the right way to do this, but for some reason,
// having
// it store it 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 to be a camera.");
}
}
});
// This is the button to 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 the 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();
// The next part must be inserted in the onResume() method of the
// activity from which session.startAuthentication() was called, so
// that Dropbox authentication completes properly.
if (session.authenticationSuccessful()) {
try {
// Mandatory call to complete the auth
session.finishAuthentication();
// Store it locally in our app for later use
storeAuth(session);
setLoggedIn(true);
} catch (IllegalStateException e) {
showToast("Couldn't authenticate with Dropbox:"
+ e.getLocalizedMessage());
Log.i(TAG, "Error authenticating", e);
}
}
}
// This is what gets called on finishing a media piece to import
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == NEW_PICTURE) {
// return from 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 from mediaImport: "
+ resultCode);
}
}
}
private void logOut() {
// Remove credentials from the session
dropboxApi.getSession().unlink();
// Clear our stored keys
clearKeys();
// Change UI state to display logged out version
setLoggedIn(false);
}
/**
* Convenience function to change UI state based on being logged in
*/
private void setLoggedIn(boolean loggedIn) {
mLoggedIn = loggedIn;
if (loggedIn) {
mSubmit.setText("Unlink from Dropbox");
mDisplay.setVisibility(View.VISIBLE);
} else {
mSubmit.setText("Link with Dropbox");
mDisplay.setVisibility(View.GONE);
mImage.setImageDrawable(null);
}
}
private void checkAppKeySetup() {
// Check to make sure that we have a valid app key
if (APP_KEY.startsWith("CHANGE") || APP_SECRET.startsWith("CHANGE")) {
showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the DBRoulette ap before trying it.");
finish();
return;
}
// Check if the app has set up its 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 your app's "
+ "manifest is not set up correctly. You should have a "
+ "com.dropbox.client2.android.AuthActivity with the "
+ "scheme: " + scheme);
finish();
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
error.show();
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a
* local store, rather than storing user name & password, and
* re-authenticating each time (which is not to be 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 the key is set to "oauth2:", then we can assume the token is
// for OAuth 2.
session.setOAuth2AccessToken(secret);
} else {
// Still support using old OAuth 1 tokens.
session.setAccessTokenPair(new AccessTokenPair(key, secret));
}
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a
* local store, rather than storing user name & password, and
* re-authenticating each time (which is not to be done, ever).
*/
private void storeAuth(AndroidAuthSession session) {
// Store the OAuth 2 access token, if there is 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 the OAuth 1 access token, if there is one. This is only
// 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) {
// We set the context this way so we 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) {
// 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) {
// 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("Image successfully uploaded");
} else {
showToast(mErrorMsg);
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
error.show();
}
Need to modify UploadPicture class:
Extract field from this variable:
String path = mPath + mFile.getName();
Put this snippet into onPostExecute method in upload successful case:
DropboxAPI.Entry filesInPath = mApi.metadata(path, 1, null, true, null);
// Basing on provided code, only one file is uploaded
DropboxAPI.Entry uploadedFile = entries.contents.get(0);
String shareUrl = mApi.share(uploadedFile.path).url;
After this manipulations shareUrl variable will contain sharing link for the image.
I think you're looking for share.

Issue with core dropbox API Android

I am sync the dropbox api for the first time. i am using the core api directly as i want to download and upload my files from my application to dropbox. I have change the app-key to my app key and app-secret to my app secret, i have included the files in lib folder of my application but i am getting this error
Invalid User
This is my code is in maindrobbox activity
public class Dropbox extends Activity {
private static final String TAG = "Dropbox";
// You don't need to change these, leave them alone.
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";
DropboxAPI<AndroidAuthSession> mApi;
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/";
final static private int NEW_PICTURE = 1;
private String mCameraFileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mCameraFileName = savedInstanceState.getString("mCameraFileName");
}
// We create a new AuthSession so that we can use the Dropbox API.
AndroidAuthSession session = buildSession();
mApi = new DropboxAPI<AndroidAuthSession>(session);
// Basic Android widgets
setContentView(R.layout.activity_dropbox);
checkAppKeySetup();
mSubmit = (Button)findViewById(R.id.auth_button);
mSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// This logs you out if you're logged in, or vice versa
if (mLoggedIn) {
logOut();
} else {
// Start the remote authentication
mApi.getSession().startAuthentication(Dropbox.this);
}
}
});
mDisplay = (LinearLayout)findViewById(R.id.logged_in_display);
// This is where a photo is displayed
mImage = (ImageView)findViewById(R.id.image_view);
// This is the button to take a photo
mPhoto = (Button)findViewById(R.id.photo_button);
mPhoto.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
// Picture from camera
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
// This is not the right way to do this, but for some reason, having
// it store it 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";
String outPath = "/sdcard/" + newPicFile;
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 to be a camera.");
}
}
});
// This is the button to take a photo
mRoulette = (Button)findViewById(R.id.roulette_button);
mRoulette.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
DownloadRandomPicture download = new DownloadRandomPicture(Dropbox.this, mApi, PHOTO_DIR, mImage);
download.execute();
}
});
// Display the proper UI state if logged in or not
setLoggedIn(mApi.getSession().isLinked());
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("mCameraFileName", mCameraFileName);
super.onSaveInstanceState(outState);
}
#Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = mApi.getSession();
// The next part must be inserted in the onResume() method of the
// activity from which session.startAuthentication() was called, so
// that Dropbox authentication completes properly.
if (session.authenticationSuccessful()) {
try {
// Mandatory call to complete the auth
session.finishAuthentication();
// Store it locally in our app for later use
TokenPair tokens = session.getAccessTokenPair();
storeKeys(tokens.key, tokens.secret);
setLoggedIn(true);
} catch (IllegalStateException e) {
showToast("Couldn't authenticate with Dropbox:" + e.getLocalizedMessage());
Log.i(TAG, "Error authenticating", e);
}
}
}
// This is what gets called on finishing a media piece to import
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == NEW_PICTURE) {
// return from 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, mApi, PHOTO_DIR, file);
upload.execute();
}
} else {
Log.w(TAG, "Unknown Activity Result from mediaImport: "
+ resultCode);
}
}
}
private void logOut() {
// Remove credentials from the session
mApi.getSession().unlink();
// Clear our stored keys
clearKeys();
// Change UI state to display logged out version
setLoggedIn(false);
}
/**
* Convenience function to change UI state based on being logged in
*/
private void setLoggedIn(boolean loggedIn) {
mLoggedIn = loggedIn;
if (loggedIn) {
mSubmit.setText("Unlink from Dropbox");
mDisplay.setVisibility(View.VISIBLE);
} else {
mSubmit.setText("Link with Dropbox");
mDisplay.setVisibility(View.GONE);
mImage.setImageDrawable(null);
}
}
private void checkAppKeySetup() {
// Check to make sure that we have a valid app key
if (APP_KEY.startsWith("CHANGE") ||
APP_SECRET.startsWith("CHANGE")) {
showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the Dropbox ap before trying it.");
finish();
return;
}
// Check if the app has set up its 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 your app's " +
"manifest is not set up correctly. You should have a " +
"com.dropbox.client2.android.AuthActivity with the " +
"scheme: " + scheme);
finish();
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
error.show();
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a local
* store, rather than storing user name & password, and re-authenticating each
* time (which is not to be done, ever).
*
* #return Array of [access_key, access_secret], or null if none stored
*/
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;
}
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a local
* store, rather than storing user name & password, and re-authenticating each
* time (which is not to be done, ever).
*/
private void storeKeys(String key, String secret) {
// Save the access key for later
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, key);
edit.putString(ACCESS_SECRET_NAME, secret);
edit.commit();
}
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;
String[] stored = getKeys();
if (stored != null) {
AccessTokenPair accessToken = new AccessTokenPair(stored[0], stored[1]);
session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE, accessToken);
} else {
session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
}
return session;
}

Notify when download finish dropbox Core API

I'm making a module that can download all file from apps folder on dropbox to devices.
Now, I'm using Core API to download a file. Everything works fine. But with multiple file, I don't know when the current file finish download to go to the next file.
Here is my download code:
final String cachePath = FileHandler.ROOT_LOCAL_FOLDER_DIR + "/" + mFile.getFileName();
try {
mFos = new FileOutputStream(cachePath);
} catch (FileNotFoundException e) {
mErrorMsg = "Couldn't create a local file to store the image";
return false;
}
ProgressListener mProgressLisenter = new ProgressListener() {
#Override
public void onProgress(long arg0, long arg1) {
// TODO Auto-generated method stub
tmpFile = new File(cachePath);
OnDownloadProgressDropboxChecked(FileHandler.PROGRESS_STATUS_ONPROGRESS, (int) (arg0 * 100 / arg1));
}
#Override
public long progressInterval() {
return 100;
}
};
mDownloaded = mApi.getFile(mFile.getFileId(), null, mFos, mProgressLisenter);
OnDownloadDropboxChecked(TRUE, "Download complete");
} catch (DropboxUnlinkedException e) {
mErrorMsg = "Unlinked";
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Download canceled";
} catch (DropboxServerException e) {
}
}
I've tried:
Catch progress download, when reached 100% then notify - On this way, the OnProgress of dropbox isn't show up imediately and sometime It not reach 100%
Put It in a asynctask - Useless
I'm out of idea now, any advance are good for me.
Edited:
the solution is put some trigger under getFile() then It work.
here is my complete class:
public class DownloadFile extends AsyncTask<Void, Long, Boolean> implements DConst {
Context act;
private DropboxAPI<?> mApi;
// private String mPath;
private FileOutputStream mFos;
private boolean mCanceled;
private Long mFileLen;
private String mErrorMsg;
private String mFileName;
String path;
DFile mFile;
DropboxAPI.DropboxFileInfo mDownloaded;
#SuppressWarnings("deprecation")
public DownloadFile(Context act, DropboxAPI<?> api, DFile mDFile) {
// We set the context this way so we don't accidentally leak activities
this.act = act;
mApi = api;
mFile = mDFile;
path = mDFile.getFileId();
mFileName = mDFile.getFileName();
OnDownloadProgressDropboxChecked(FileHandler.PROGRESS_STATUS_START, 0);
}
File tmpFile;
#Override
protected Boolean doInBackground(Void... params) {
try {
final String cachePath = FileHandler.ROOT_LOCAL_FOLDER_DIR + "/" + mFile.getFileName();
try {
mFos = new FileOutputStream(cachePath);
} catch (FileNotFoundException e) {
mErrorMsg = "Couldn't create a local file to store the image";
return false;
}
ProgressListener mProgressLisenter = new ProgressListener() {
#Override
public void onProgress(long arg0, long arg1) {
// TODO Auto-generated method stub
tmpFile = new File(cachePath);
OnDownloadProgressDropboxChecked(FileHandler.PROGRESS_STATUS_ONPROGRESS, (int) (arg0 * 100 / arg1));
Log.d("Dolphin got interval", String.valueOf(tmpFile.length() + " - " + arg0 + " - " + arg1));
}
#Override
public long progressInterval() {
return 100;
}
};
mDownloaded = mApi.getFile(mFile.getFileId(), null, mFos, mProgressLisenter);
} catch (DropboxUnlinkedException e) {
mErrorMsg = "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.";
} finally {
if (mFos != null) {
try {
mFos.close();
return true;
} catch (IOException e) {
}
}
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
OnDownloadProgressDropboxChecked(FileHandler.PROGRESS_STATUS_FINISH, 0);
if (result) {
OnDownloadDropboxChecked(TRUE, "Download complete");
} else {
OnDownloadDropboxChecked(FALSE, mErrorMsg);
}
}
OnAsyncDownloadListener onAsyncDownloadListener;
OnAsyncDownloadProgressListener onAsyncDownloadProgressListener;
private void OnDownloadDropboxChecked(int res, String messenger) {
if (onAsyncDownloadListener != null) {
onAsyncDownloadListener.OnAsyncDownload(res, messenger);
}
}
private void OnDownloadProgressDropboxChecked(int status, int percent) {
if (onAsyncDownloadProgressListener != null) {
onAsyncDownloadProgressListener.OnAsyncDownloadProgress(status, percent);
}
}
public void setOnAsyncDownloadListener(OnAsyncDownloadListener listener) {
onAsyncDownloadListener = listener;
}
public void setOnAsyncDownloadProgressListener(OnAsyncDownloadProgressListener listener) {
onAsyncDownloadProgressListener = listener;
}
public interface OnAsyncDownloadListener {
public abstract void OnAsyncDownload(int res, String messenger);
}
public interface OnAsyncDownloadProgressListener {
public abstract void OnAsyncDownloadProgress(int status, int percent);
}
}
The error caused by 'OnDownloadDropboxChecked()' of Asynctask fired before the one of getFile(). So It return a false notify.
Converting my comment to an answer:
If I'm reading this right, you're using the Android Core API SDK, right? If so, I think that when mApi.getFile returns, the file has been downloaded. So you can do whatever you need to do on the next line.

Categories

Resources