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);
}
Related
//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;
}
}
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);
}
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.
I am trying to report the install event to flurry.
I have implemented ReferralReceiver to be called when the app is being installed.
I have all the parameters in a map.
I am calling Flurry using my flurry code:
FlurryAgent.onStartSession(context, FlurryCode);
FlurryAgent.logEvent("Referral", referralParams);
FlurryAgent.onEndSession(context);
The data is being stored to the SharedPreferences but it is not being sent to flurry.
Has anyone encountered this problem.
#Override
public void onReceive(Context context, Intent intent)
{
LogManager.Info("ReferralReceiver intent.action=" + intent.getAction());
LogManager.Info("ReferralReceiver intent.DataString=" + intent.getDataString());
LogManager.Info("ReferralReceiver intent.intent=" + intent.toString());
// Workaround for Android security issue: http://code.google.com/p/android/issues/detail?id=16006
try
{
final Bundle extras = intent.getExtras();
if (extras != null) {
extras.containsKey(null);
}
}
catch (final Exception e) {
return;
}
Map<String, String> referralParams = new HashMap<String, String>();
// Return if this is not the right intent.
if (! intent.getAction().equals("com.android.vending.INSTALL_REFERRER")) { //$NON-NLS-1$
return;
}
String referrer = intent.getStringExtra("referrer"); //$NON-NLS-1$
if( referrer == null || referrer.length() == 0) {
return;
}
try
{
referrer = URLDecoder.decode(referrer, "UTF-8");
}
catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
LogManager.Info("ReferralReceiver intent.referrer=" + intent.getStringExtra("referrer"));
SharedPreferences storage = context.getSharedPreferences(ReferralReceiver.PREFS_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = storage.edit();
editor.putString("referrer", referrer);
editor.commit();
try {
if (intent.hasExtra("referrer")) {
String referrers[] = referrer.split("&");
for (String referrerValue : referrers)
{
String keyValue[] = referrerValue.split("=");
if (keyValue.length==2)
{
referralParams.put(keyValue[0], keyValue[1]);
}
}
}
}
catch (Exception e)
{
LogManager.Error(e);
return;
}
ReferralReceiver.storeReferralParams(context, referralParams);
String FlurryCode = SaverrUtils.GetFlurryCode();
FlurryAgent.onStartSession(context, FlurryCode);
FlurryAgent.logEvent("Referral", referralParams);
FlurryAgent.onEndSession(context);
LogManager.Info("New_Install");
}
public final static String PREFS_FILE_NAME = "ReferralParamsFile";
/*
* Stores the referral parameters in the app's sharedPreferences.
* Rewrite this function and retrieveReferralParams() if a
* different storage mechanism is preferred.
*/
public static void storeReferralParams(Context context, Map<String, String> params)
{
SharedPreferences storage = context.getSharedPreferences(ReferralReceiver.PREFS_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = storage.edit();
for(String key : SaverrUtils.EXPECTED_REFERRER_PARAMETERS)
{
String value = params.get(key);
if(value != null)
{
editor.putString(key, value);
}
}
editor.commit();
}
// Referral Parameters
public final static String[] EXPECTED_REFERRER_PARAMETERS = {
"utm_source",
"utm_medium",
"utm_term",
"utm_content",
"utm_campaign",
"referrer"
};
I think flurry has a minimum amount of seconds between start/end session for it to actually count. You can save all the data to shared preference or file, then when the user starts your activity check if it's been given to flurry. If it's new do FlurryAgent.logEvent(...).
I am trying to send tweets to twitter via my android app. The libraries I'm using are signpost core, signpost commonshttp, and jtwitter. My code in my main activity is as follows:
public class MainActivity extends Activity implements View.OnClickListener {
static final String TAG = "TweetExample";
private Twitter twitter;
SharedPreferences prefs;
private EditText textStatus;
private static final String CONSUMER_KEY = "my key";
private static final String CONSUMER_SECRET = "my secret";
private static String ACCESS_KEY = null;
private static String ACCESS_SECRET = null;
private static final String REQUEST_URL = "http://twitter.com/oauth/request_token";
private static final String ACCESS_TOKEN_URL = "http://twitter.com/oauth/access_token";
private static final String AUTH_URL = "http://twitter.com/oauth/authorize";
private static final String CALLBACK_URL = "TweetExample://twitt";
private static CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
private static CommonsHttpOAuthProvider provider = new CommonsHttpOAuthProvider
(REQUEST_URL, ACCESS_TOKEN_URL, AUTH_URL);
//Called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Retrieve the shared preferences
prefs = getSharedPreferences(USER_PREFERENCES,
Context.MODE_PRIVATE);
// Find views by id
ImageView buttonUpdate = (ImageView) findViewById(R.id.ImageView_Update);
textStatus = (EditText) findViewById(R.id.textStatus);
ImageView btnLogin = (ImageView) findViewById(R.id.ImageView_Twit);
// Add listener
buttonUpdate.setOnClickListener(this);
btnLogin.setOnClickListener(this);
// Initialize preferences
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
twitter = null;
}
});
}
public void onClick(View v) {
switch(v.getId()){
case R.id.ImageView_Update:
String status = textStatus.getText().toString();
String message = "Status set to: " + status;
Log.d(TAG, message);
// Ignore empty updates
if (status.length() == 0)
return;
// Connect to twitter.com and update your status
try {
Log.d(TAG, "1");
twitter.setStatus(status);
Log.d(TAG, "2");
} catch (TwitterException e) {
Log.e(TAG, "Twitter exception: " + e);
}
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
break;
case R.id.ImageView_Twit:
try {
String authURL = provider.retrieveRequestToken(consumer, CALLBACK_URL);
Log.d(TAG, authURL);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authURL)));
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
break;
}
}
#Override
public void onResume() {
super.onResume();
Uri uri = this.getIntent().getData();
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
Log.d(TAG, uri.toString());
String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
Log.d(TAG, verifier);
try {
provider.retrieveAccessToken(consumer, verifier);
ACCESS_KEY = consumer.getToken();
ACCESS_SECRET = consumer.getTokenSecret();
Log.d(TAG, ACCESS_KEY);
Log.d(TAG, ACCESS_SECRET);
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
}
}
I know the callback url is right. Could it be that I authenticate using signpost and try to tweet using jtwitter? Right now, I can sign into twitter to authorize the app and get redirected back to my app, but when I type something in to try to post to twitter it gets as far as twitter.setStatus(status);
Any help would be greatly appreciated.
Possibly I'm being blind, or you forgot to include some code, but it looks like the Twitter object is never constructed. So you'd get a NullPointerException when you come to use it.
Somewhere you want code along the lines of:
OAuthSignpostClient oauthClient = new OAuthSignpostClient(app_token, app_secret, user_access_token, user_secret);
Twitter twitter = new Twitter(null, oauthClient);