1

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();
            }
Lalit
  • 1,713
  • 1
  • 11
  • 19
  • What is the error you are receiving? Please post it. – ialexander Dec 24 '13 at 13:15
  • Thanks for replying. The error is **User has unlinked.** Here i am giving the code that i am using for upload text file to dropbox. `DropboxAPI.Entry entry = mDBApi.putFileOverwrite("/DropboxFile1.txt", fis, file.length(), null);` Is it correct or i should have to use ".putFile" method only? Please Help @wormtown – Lalit Dec 25 '13 at 05:53

3 Answers3

1

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.

ialexander
  • 898
  • 10
  • 28
  • Thanks for your valuable reply. Now i am going to create a new app on Dropbox. What options should i choose. Like **What type of app do you want to create?** and all. Please Help. ( ',' ) – Lalit Dec 26 '13 at 05:36
  • For All new dropbox users **How to create dropboxApp? here is the answer : **Dropbox api Files and datastores No All file types, Your_App_Name The next page will display your key.** Thank You. – Lalit Dec 27 '13 at 05:02
  • Dear @wormtown, This is **my next issue** please help me to solve. Here is the link : [http://stackoverflow.com/questions/20783535/dropbox-serverexception-in-android?noredirect=1#comment31155666_20783535] – Lalit Dec 27 '13 at 05:05
0

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;
    }
}
Hassaan Rabbani
  • 2,469
  • 5
  • 30
  • 55
  • Its too long and confusing code i just want to send a text file. Tell me what should i dofor that ..??? @Hassaan Rabbani – Lalit Dec 26 '13 at 06:37
  • please don't send such a complicated answers. The whole code confuses a lot. @Hassaan Rabbani – Lalit Dec 27 '13 at 05:12
0

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);
}
henry4343
  • 3,871
  • 5
  • 22
  • 30
  • Thank for your kind attention. I have done this code also but it is working properly upto above mApi.putFile. My logcat Looks like : `12-25 06:07:09.978: W/System.err(1247): com.dropbox.client2.exception.DropboxUnlinkedException ` @henry4343 – Lalit Dec 25 '13 at 06:17
  • Ok.. **But how to do that??** "confirm your dropbox account is link from your dropbox api" ( ',' ) @henry4343 – Lalit Dec 26 '13 at 05:59