How to display Dropbox files in a listview in android? - android

I've been browsing answers on here for a while and have employed most of the answers in my code but it still doesn't seem to work. I just want to display a listview of the content in a dropbox account and also give the user an option to download a file/folder. My MainActivity used to crash right after opening it, surrounding my onPostExecute content with a try/catch statement handling NullPointerException solved the crashing. But the app still fails to display the contents in Dropbox. At the most basic stage with just a MainActivity and a DLFiles (AsyncTask) class, how do I make this work? I've been at this for days, please help!
Thanks in advance.
MainActivity.java
public class MainActivity extends Activity {
final static private String APP_KEY = "app_key_here";
final static private String APP_SECRET = "app_secret_here";
final static private AccessType ACCESS_TYPE = AccessType.DROPBOX;
private static final boolean USE_OAUTH1 = false;
// 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";
// In the class declaration section:
private DropboxAPI<AndroidAuthSession> mDBApi;
private boolean mLoggedIn;
private final String FILE_DIR = "/";
private String[] mfnames;
private ListView mListView;
private Button listEm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// And later in some initialization function:
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
if (!mLoggedIn){
if (USE_OAUTH1){
mDBApi.getSession().startAuthentication(MainActivity.this);
} else{
mDBApi.getSession().startOAuth2Authentication(MainActivity.this);
}
}
mListView = (ListView) findViewById(R.id.list);
listEm = (Button) findViewById(R.id.listit);
listEm.setOnClickListener(new OnClickListener(){
public void onClick(View v){
DLFiles dlf = new DLFiles(MainActivity.this,mDBApi,
FILE_DIR, mfnames,mListView );
dlf.execute();
}
});
checkLoggedIn(mDBApi.getSession().isLinked());
}
private void checkLoggedIn(boolean loggedIn){
mLoggedIn = loggedIn;
}
protected void onResume() {
super.onResume();
if (mDBApi.getSession().authenticationSuccessful()) {
try {
// Required to complete auth, sets the access token on the session
mDBApi.getSession().finishAuthentication();
String accessToken = mDBApi.getSession().getOAuth2AccessToken();
} catch (IllegalStateException e) {
Log.i("DbAuthLog", "Error authenticating", e);
}
}
}
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));
}
}
/**
* 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 AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(MainActivity.APP_KEY, MainActivity.APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
loadAuth(session);
return session;
}
}
DLFiles.java
public class DLFiles extends AsyncTask<Void, Long, String[]> {
private Context mContext;
private final ProgressDialog mDialog;
private DropboxAPI<?> mApi;
private String mPath;
private FileOutputStream mFos;
private boolean mCanceled;
private Long mFileLen;
private String mErrorMsg;
private String[] fnames;
public DLFiles( Context context, DropboxAPI<?> api,
String dropboxPath,String[] efnames, ListView listView){
// We set the context this way so we don't accidentally leak activities
mContext = context.getApplicationContext();
fnames = efnames;
mApi = api;
mPath = dropboxPath;
mDialog = new ProgressDialog(context);
mDialog.setMessage("Opening Directory");
mDialog.show();
}
#Override
protected String[] doInBackground(Void... params){
// Get the metadata for a directory
try{
ArrayList<String> filenames = new ArrayList<String>();
Entry dirent = mApi.metadata(mPath, 1000, null, true, null);
for (Entry ent: dirent.contents){
if(ent.isDir){
//Add it to the list of thumbs we can choose from
filenames.add("<dir>" + ent.path);}
else{
filenames.add(ent.fileName());
}
}
fnames = filenames.toArray(new String[filenames.size()]);
} 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 fnames;
}
#Override
protected void onProgressUpdate(Long... progress){
int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
mDialog.setProgress(percent);
}
#Override
protected void onPostExecute(String[] result){
try{
if (result != null){
ArrayAdapter<String> array = new ArrayAdapter<String>(mContext,
android.R.layout.simple_list_item_1, result);
Log.d("dropbox", result[1]);
}
else
showToast("result==null");
}
catch (NullPointerException e){
e.printStackTrace();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/listit"
android:text="List directory content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<LinearLayout
android:id="#+id/listing"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</LinearLayout>
</LinearLayout>

I now see that your code is like in DownloadRandomPicture.java.
String fnames [] = null;
In doOnBackGround():
ArrayList<String> filenames = new ArrayList<String>();
for (Entry ent: dirent.contents) {
if (ent.thumbExists) {
filenames.add(ent.path);
}
}
fnames = filenames.toArray(new String[filenames.size()]);
in onPostExecute():
if ( fnames != null )
{
ArrayAdapter<String> array = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, fnames);
listView1.setAdapter(array);
}
else
showToast ( "fnames==null" );

if you fixed your app by catching a null-pointer exception, you still have a null value that needs to be addressed, if you are trying to add a null array as an adapter nothing will show up. From the code it looks like you are creating an array adapter from fnames, and then trying to reassign values to the array adapter twice with the secondary for loop. So I am willing to bet that fnames is null. I would set a break point on fnames in the doInBackground method and check it. Also the value that is returned from doInBackground is the parameter for onPostExecute so if you are returning a value that you want to use, use the parameter result from onPostExecute.

If you want to show the files and folder of a drop box in List View then simply use this code in your project and it will solve your problem.
private void PopulateList()
{
List<String> filename = new ArrayList<String>();
String mPath = "/";
Entry dirent = null;
try
{
dirent = mApi.metadata(mPath, 1000, null, true, null);
} catch (DropboxException e)
{
System.out.println("Error : "+e.getMessage());
}
for (Entry ent: dirent.contents)
{
if(ent.isDir)
{
filename.add(ent.fileName());
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1, filename );
mListView.setAdapter(arrayAdapter);
}

Related

How do I download several images from Dropbox via API?

I wanted to download images via Dropbox API so i followed the sample code # Android Dropbox API file download but i do not understand how to integrate it into my current code. I tried changing api.getFileStream("dropbox", dbPath, null); to dropbox.getFileStream("dropbox", dbPath, null); resulting in the error:
'getFileStream(java.lang.String, java.lang.String)' in 'com.dropbox.client2.DropboxAPI' cannot be applied to '(java.lang.String, java.lang.String, null)'
Updated 1 : Changed to `dropbox.getFileStream(FILE_DIR,null)
Main Code
public class Dropbox extends AppCompatActivity implements View.OnClickListener {
private DropboxAPI<AndroidAuthSession> dropbox;
private final static String FILE_DIR = "/DropboxSample/";
private final static String DROPBOX_NAME = "dropbox_prefs";
private final static String ACCESS_KEY = "Insert Key here";
private final static String ACCESS_SECRET = "Insert Key here";
private boolean isLoggedIn;
private Button logIn;
private Button uploadFile;
private Button downloadFile;
private Button listFiles;
private LinearLayout container;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dropbox);
logIn = (Button) findViewById(R.id.dropbox_login);
logIn.setOnClickListener(this);
uploadFile = (Button) findViewById(R.id.upload_file);
uploadFile.setOnClickListener(this);
downloadFile = (Button) findViewById(download_file);
downloadFile.setOnClickListener(this);
listFiles = (Button) findViewById(R.id.list_files);
listFiles.setOnClickListener(this);
container = (LinearLayout) findViewById(R.id.container_files);
loggedIn(false);
AndroidAuthSession session;
AppKeyPair pair = new AppKeyPair(ACCESS_KEY, ACCESS_SECRET);
SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
String key = prefs.getString(ACCESS_KEY, null);
String secret = prefs.getString(ACCESS_SECRET, null);
if (key != null && secret != null) {
AccessTokenPair token = new AccessTokenPair(key, secret);
session = new AndroidAuthSession(pair ,token);
} else {
session = new AndroidAuthSession(pair );
}
dropbox = new DropboxAPI<>(session);
}
#Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = dropbox.getSession();
if (session.authenticationSuccessful()) {
try {
session.finishAuthentication();
TokenPair tokens = session.getAccessTokenPair();
SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(ACCESS_KEY, tokens.key);
editor.putString(ACCESS_SECRET, tokens.secret);
editor.commit();
loggedIn(true);
} catch (IllegalStateException e) {
Toast.makeText(this, "Error during Dropbox authentication",
Toast.LENGTH_SHORT).show();
}
}
}
public void loggedIn(boolean isLogged) {
isLoggedIn = isLogged;
uploadFile.setEnabled(isLogged);
downloadFile.setEnabled(isLogged);
listFiles.setEnabled(isLogged);
logIn.setText(isLogged ? "Log out" : "Log in");
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
ArrayList<String> result = msg.getData().getStringArrayList("data");
for (String fileName : result) {
Log.i("ListFiles", fileName);
TextView tv = new TextView(Dropbox.this);
tv.setText(fileName);
container.addView(tv);
}
}
};
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.dropbox_login:
if (isLoggedIn) {
dropbox.getSession().unlink();
loggedIn(false);
} else {
dropbox.getSession().startAuthentication(Dropbox.this);
}
break;
case R.id.list_files:
ListDropboxFiles list = new ListDropboxFiles(dropbox, FILE_DIR,
handler);
list.execute();
break;
case R.id.upload_file:
UploadFileToDropbox upload = new UploadFileToDropbox(dropbox, FILE_DIR);
upload.execute();
break;
case R.id.download_file:
try {
downloadDropboxFile(FILE_DIR,(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+"CapturyGallery")));
} catch (IOException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
public class UploadFileToDropbox extends AsyncTask<Void, Long, Boolean> {
private DropboxAPI<?> dropbox;
private String mPath;
private Context mContext;
private final ProgressDialog mDialog;
private DropboxAPI.UploadRequest mRequest;
private String mErrorMsg;
private File[] listFile;
private int mFilesUploaded;
private int mCurrentFileIndex;;
public UploadFileToDropbox(DropboxAPI<?> dropbox, String path) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/CapturyGallery");
listFile = file.listFiles();
mContext = Dropbox.this;
this.dropbox = dropbox;
this.mPath = path;
mFilesUploaded = 0 ;
mCurrentFileIndex = 0 ;
mDialog = new ProgressDialog(mContext);
mDialog.setMax(100);
mDialog.setMessage("Uploading file 1 /" +listFile.length);
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton(ProgressDialog.BUTTON_POSITIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// This will cancel the putFile operation
try {
mRequest.abort();
} catch (Exception e) {
}
}
});
mDialog.show();
mDialog.setCanceledOnTouchOutside(false);
}
#Override
protected Boolean doInBackground(Void... params) {
try {
for (int y = 0; y < listFile.length; y++) {
mCurrentFileIndex = y;
File file = listFile[y];
// 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(file);
String path = mPath + file.getName();
mRequest = dropbox.putFileOverwriteRequest(path, fis, file.length(),
new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 5;
}
#Override
public void onProgress(long bytes, long total) {
if (isCancelled()) {
mRequest.abort();
} else {
publishProgress(bytes);
}
}
});
mRequest.upload();
if(!isCancelled()){
mFilesUploaded++;
}else{
return false;
}
}
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) {
long totalBytes = 0;
long bytesUploaded = 0;
for (int i = 0; i < listFile.length; i++) {
Long bytes = listFile[i].length();
totalBytes += bytes;
if (i < mCurrentFileIndex) {
bytesUploaded += bytes;
}
bytesUploaded += progress[0];
int percent = 100;
int percent1 = (int) (percent * (bytesUploaded/totalBytes));
mDialog.setMessage("Uploading file " + (mCurrentFileIndex + 1) + " / " + listFile.length);
mDialog.setProgress(percent1);
}
}
#Override
protected void onPostExecute(Boolean result) {
mDialog.dismiss();
if (result) {
showToast("Successfully uploaded");
} else {
showToast(mErrorMsg);
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(Dropbox.this, msg, Toast.LENGTH_LONG);
error.show();
}
}
public class ListDropboxFiles extends AsyncTask<Void, Void, ArrayList<String>> {
private DropboxAPI<?> dropbox;
private String path;
private Handler handler;
public ListDropboxFiles(DropboxAPI<?> dropbox, String path, Handler handler) {
this.dropbox = dropbox;
this.path = path;
this.handler = handler;
}
#Override
protected ArrayList<String> doInBackground(Void... params) {
ArrayList<String> files = new ArrayList<String>();
try {
DropboxAPI.Entry directory = dropbox.metadata(path, 1000, null, true, null);
for (DropboxAPI.Entry entry : directory.contents) {
files.add(entry.fileName());
}
} catch (DropboxException e) {
e.printStackTrace();
}
return files;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putStringArrayList("data", result);
msgObj.setData(b);
handler.sendMessage(msgObj);
}
}
Added from Sample code
private boolean downloadDropboxFile(String dbPath, File localFile) throws IOException {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
if (!localFile.exists()) {
localFile.createNewFile(); //otherwise dropbox client will fail silently
}
FileDownload fd = dropbox.getFileStream("dropbox", dbPath, null);
br = new BufferedInputStream(fd.is);
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);
}
} finally {
//in finally block:
if (bw != null) {
bw.close();
}
if (br != null) {
br.close();
}
}
return true;
}
}
>
The error message is indicating that the method definition is:
getFileStream(java.lang.String, java.lang.String)
This is also what the documentation for the getFileStream method in the Dropbox Android Core SDK shows.
However, you're attempting to use three parameters:
(java.lang.String, java.lang.String, null)
So, to properly call the method, you should remove that last parameter (null).

i want to get the mail id in dropbox,how can i retrieve the from dropbox

//i want to get the mail id from dropbox,how can i retrieve the mails and username from dropbox.is their any way to get the username and mailid,please help me how can i retrieve the mail id.i am using coreapi to implement this one please help me how can i get the those deatils.
public class PrefernceDropBox extends Activity {
private static final String TAG = "DBRoulette";
public ProgressDialog dialog;
// /////////////////////////////////////////////////////////////////////////
// Your app-specific settings. //
// /////////////////////////////////////////////////////////////////////////
// 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 = "XXXX";
final static private String APP_SECRET = "XXXXX";
// If you'd like to change the access type to the full Dropbox instead of
// an app folder, change this value.
final static private AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
// /////////////////////////////////////////////////////////////////////////
// End app-specific settings. //
// /////////////////////////////////////////////////////////////////////////
// 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, mDownload;
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);
dialog = new ProgressDialog(PrefernceDropBox.this);
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.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
mApi.getSession()
.startAuthentication(PrefernceDropBox.this);
}
}
});
// 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);
}
}
}
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("signout from Dropbox");
// mDisplay.setVisibility(View.VISIBLE);
} else {
mSubmit.setText("Sign into 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).
*
* #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;
}
}

How to return an Array list from AsyncTask into Main Activity?

I'm trying to display the list of files in a dropbox account in my app. My question is, how do I return the list (fnames) into my MainActivity so I can display it in a listview.
And how do I call it in the MainActivity too?
New to android development, any other tips will be appreciated!
Thanks!
public class DbFileExplorer extends AsyncTask<Void, Long, Boolean> {
private Context mContext;
private final ProgressDialog mDialog;
private DropboxAPI<?> mApi;
private String mPath;
private FileOutputStream mFos;
private boolean mCanceled;
private Long mFileLen;
private String mErrorMsg;
protected String[] fnames;
public DbFileExplorer(Context context, DropboxAPI<?> api,
String dropboxPath, String[] efnames){
// We set the context this way so we don't accidentally leak activities
mContext = context.getApplicationContext();
fnames = efnames;
mApi = api;
mPath = dropboxPath;
mDialog = new ProgressDialog(context);
mDialog.setMessage("Opening Directory");
mDialog.show();
}
#Override
protected Boolean doInBackground(Void... params){
// Get the metadata for a directory
int i = 0;
try{
fnames = null;
Entry dirent = mApi.metadata(mPath, 1000, null, true, null);
ArrayList<Entry> files = new ArrayList<Entry>();
ArrayList<String> dir = new ArrayList<String>();
for (Entry ent: dirent.contents){
//Add it to the list of thumbs we can choose from
files.add(ent);
dir.add(new String(files.get(i++).path));
}
i=0;
fnames = dir.toArray(new String[dir.size()]);
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;
}
#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();
}
private void showToast(String msg){
Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
error.show();
}
}
The third parameter of your AsyncTask templates is the result type of the task. Change it from Boolean to ArrayList or a similar structure. Then return that value from your doInBackground method. It will then be passed to the onPostExecute method of the AsyncTask which will be executed on the UI thread (so you can use the data to manipulate the UI if you want).
I'm solving this kind of problem using execute().get();
Example
call from activity or fragment
ArrayList<String> arraylistitem= new jsonparsing(getActivity()).execute().get();
In async task
public class jsonparsing extends AsyncTask<Void, Void, ArrayList<String>>
{
public jsonparsing(Activity activity)
{
this.activity = activity;
arraylistitem = new ArrayList<String>();
}
protected ArrayList<String> doInBackground(Void... arg0)
{
// Do anything else you need to with the returned list here
return arraylistitem;
}
}

Can not send text file to dropbox from android

I am trying a lot to send a text file to drop-box but it is not working. As per my knowledge i have done all the coding properly. Someone please give me your email-id or reply me on Lalit12131#gmail.com
I will send you all of my files and details and let me solve this problem.
Please HELP
Thanks in advance.
void toDropbox()
{
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String filePath =getApplicationContext().getFilesDir().getPath().toString() + "/DropboxFile1.txt";
File file = new File(filePath);
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();}
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getBaseContext(), "In clickListener", Toast.LENGTH_SHORT).show();
try {
DropboxAPI.Entry response = mDBApi.putFile("/DropboxFile1.txt", inputStream, file.length(), null, null);
} catch (DropboxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This suggests that you are getting the user unlinked exception because either you need to check that you correctly setup Dropbox to allow your app to have access and/or you are not providing the correct access token pair that was provided to you when you setup the access (on the Dropbox site).
"This will happen either because you have not set an com.dropbox.client2.session.AccessTokenPair on your session, or because the user unlinked your app (revoked the access token pair)."
First go to Dropbox and follow the instructions here: Developer Guide and make sure that you have setup app permissions, and make sure that the user (you) have allowed access for the app (linked). You should be given an access key and an access secret that you will need to put into your app. The answer provided by #Hassaan Rabbani has an example of authenticating your app using the app key and secret token pair. Note, that when you tried his code, I'm sure you must have changed the variables
final static private String APP_KEY = "xxxxxxxxx";
final static private String APP_SECRET = "xxxxxxxxx";
to the token pair given you. If you did change those values to the correct ones, it indicates that the error is server side so double check the permission from the link I provided.
To get the app key and secret you need to setup the app on Dropbox. Go to create new app and choose:
Dropbox api, Files and datastores, No, All file types, Your_App_Name
The next page will display your key.
Use this Code and you are good to go, remove a few errors as i was using this code for uploading images, text files and pdf files. i have removed a lot of code,
public class Dropboxupload extends Activity {
private static final String TAG = "Dropbox";
///////////////////////////////////////////////////////////////////////////
// Your app-specific settings. //
///////////////////////////////////////////////////////////////////////////
// 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 = "xxxxxxxxx";
final static private String APP_SECRET = "xxxxxxxxx";
// If you'd like to change the access type to the full Dropbox instead of
// an app folder, change this value.
final static private AccessType ACCESS_TYPE = AccessType.DROPBOX;
///////////////////////////////////////////////////////////////////////////
// End app-specific settings. //
///////////////////////////////////////////////////////////////////////////
// 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;
String filename = Scene.name;
private ImageView mImage;
private final String PHOTO_DIR = "/Your directory here/";
final static private int NEW_PICTURE = 1;
private String mCameraFileName;
DatabaseHandler db = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.GREEN));
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(R.layout.forsettings);
TextView actiontitle=(TextView)findViewById(R.id.textscene);
actiontitle.setText("Upload");
Button homebutton = (Button)findViewById(R.id.home);
homebutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
view.getContext().startActivity(new Intent(view.getContext().getApplicationContext(),Main.class));
}
});
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_dropboxupload);
checkAppKeySetup();
mSubmit = (Button)findViewById(R.id.auth_button);
mSubmit.setBackgroundColor(Color.rgb(175, 246, 179));
Button mEmail = (Button)findViewById(R.id.email_button);
mEmail.setBackgroundColor(Color.rgb(175, 246, 179));
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(Dropboxupload.this);
}
}
});
mSubmit.setVisibility(View.INVISIBLE);
mDisplay = (LinearLayout)findViewById(R.id.logged_in_display);
// This is where a photo is displayed
mImage = (ImageView)findViewById(R.id.image_view);
// 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
public void uploadData() {
String filename = Scene.name;
filename.replaceAll(".txt", "");
filename.replaceAll(".pdf", "");
filename.replaceAll(".fdx", "");
db.getContact(filename);
Contact cn = db.getContact(filename);
String text = cn.getscript();
//// get file path from here
String filePath = getApplicationContext().getFilesDir().getPath().toString() + filename + ".txt";
File file = new File(filePath);
file.canWrite();
FileWriter writer = null;
try {
writer = new FileWriter(file);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
writer.append(text);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
UploadPicture upload = new UploadPicture(this, mApi, PHOTO_DIR, file);
upload.execute();
//v.getContext().startActivity(new Intent(v.getContext().getApplicationContext(),Scene.class));
}
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");
mSubmit.setVisibility(View.INVISIBLE);
// mDisplay.setVisibility(View.VISIBLE);
} else {
mSubmit.setText("Link with Dropbox");
mDisplay.setVisibility(View.GONE);
mImage.setImageDrawable(null);
}
}
////////////////////
//////// Do not look at functions under this
///////////////////
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;
}
}
Use Dropbox api, create mApi object and use upload function
public void uploadFileToDropbox(File file, String uploadPath){
mApi.putFile(uploadPath, new FileInputStream(file), file.length(), null, null);
}

leaked a window ProgressDialog Android Dropbox

I am trying to upload a file to dropbox via AsyncTask and I am gett the window leaked error:
05-16 16:05:53.523: E/WindowManager(4528): Activity com.example.wecharades.ShowVideo has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#2be59ea8 that was originally added here
I looked here and understand it is because my activity is exited and the progressdialog is still there. I can't understand why my activity gets exited. it is just a screen with a button to press to upload the file. I am using almost an identical code to download a file from dropbox and it works perfect.
Any suggestions?
thanks in advance!
public class UploadFile extends AsyncTask<Void, Long, Boolean> {
DropboxAPI<AndroidAuthSession> dDBApi;
Context dContext;
protected final ProgressDialog uDialog;
private long dFileLen;
private String SAVE_PATH;
private String mErrorMsg;
public UploadFile(Context context,DropboxAPI<AndroidAuthSession> mDBApi, String path) {
dDBApi=mDBApi;
dContext=context;
SAVE_PATH = path;
uDialog = new ProgressDialog(context);
uDialog.setMax(100);
uDialog.setMessage("Uploading Video Charade");
uDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
uDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
FileInputStream inputStream = null;
try {
File file = new File(ShowVideo.path);
inputStream = new FileInputStream(file);
Entry newEntry = dDBApi.putFileOverwrite("/GAMES/GAME_BETWEEN_USER_A_USER_B/" + "PresentVideo.mp4", inputStream, file.length(), new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second
return 500;
}
#Override
public void onProgress(long bytes, long total) {
dFileLen = total;
publishProgress(bytes);
}
});
} 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) {
}
catch (Exception e) {
System.out.println("Something went wrong: " + e);
}
finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
Log.d("TAG", "IOException" + e.getMessage());
}
}
Log.d("ErrorMsg", mErrorMsg);
}
return null;
}
#Override
protected void onProgressUpdate(Long... progress) {
int percent = (int)(100.0*(double)progress[0]/dFileLen + 0.5);
uDialog.setProgress(percent);
}
#Override
protected void onPostExecute(Boolean result) {
uDialog.dismiss();
super.onPostExecute(result);
Log.d("TAG","UDialog Should be dismissed");
}
}
Here is my Activity class from where i call the UploadFile:
The methods buidSession and clearKeys are not yet used.
public class ShowVideo extends Activity implements OnClickListener {
/** Dropbox Key and AccessType Information*/
final static private String APP_KEY = "XXXXXXXXXXXX";
final static private String APP_SECRET = "XXXXXXXXXXXX";
final static private AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
/**--------------------------------------------------------------*/
private DropboxAPI<AndroidAuthSession> mDBApi;
UploadFile upload;
static String path = "";
public static String fileName;
private VideoView ww;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Forces landscape orientation which is what the camera uses.
setContentView(R.layout.showvideo);
Button yesButton = (Button) findViewById(R.id.yesButton);
Button noButton = (Button) findViewById(R.id.NoButton);
yesButton.setOnClickListener(this);
noButton.setOnClickListener(this);
ww = (VideoView) findViewById(R.id.satisfiedVideoView);
path = getRealPathFromURI(CaptureVideo.uriVideo);
fileName = getFileNameFromUrl(path);
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
if(!mDBApi.getSession().isLinked())
mDBApi.getSession().startAuthentication(ShowVideo.this);
}
private void playVideo(){
ww.setVideoURI(CaptureVideo.uriVideo);
ww.setMediaController(new MediaController(this));
ww.start();
ww.requestFocus();
}
public static String getFileNameFromUrl(String path) {
String[] pathArray = path.split("/");
return pathArray[pathArray.length - 1];
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.yesButton){
UploadFile upload = new UploadFile(ShowVideo.this,mDBApi,path);
upload.execute();
//if(upload.getStatus() == upload.){
//Intent intentHome = new Intent(ShowVideo.this, StartScreen.class);
//startActivity(intentHome);
//}
}
if(v.getId() == R.id.NoButton){
File file = new File(path);
boolean deleted = false;
deleted = file.delete();
Log.d("TAG", Boolean.toString(deleted));
Intent intent = new Intent(ShowVideo.this, CaptureVideo.class);
startActivity(intent);
}
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**DROPBOX-METHOD------------------------------------------*/
#Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = mDBApi.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);
}
}
}
/**
* 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;
}
private void showToast(String msg) {
Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
error.show();
}
}
Try this, in your constructor you dont get the context like this:
dContext=context.getApplicationContext();
but try passing the activity from which you start your asynctask
UploadFile upFile = new UploadFile( ActivityName.this, mDBApi, path);
so in your constructor you have now only:
dContext=context;
call super.onPostExexute(result) after uDialog.dismiss();
#Override
protected void onPostExecute(Boolean result) {
uDialog.dismiss();
Log.d("TAG","UDialog Should be dismissed");
super.onPostExecute(result);
}
EDIT:
ok, I think you should call this code
if(v.getId() == R.id.NoButton){
File file = new File(path);
boolean deleted = false;
deleted = file.delete();
Log.d("TAG", Boolean.toString(deleted));
Intent intent = new Intent(ShowVideo.this, CaptureVideo.class);
startActivity(intent);
}
in the onPostExecute trigger, because it's executed without waiting the AsyncTask to finish. This means you will have to pass the value of the v.getId() so you can achive the same functionality.

Categories

Resources