2

I want to send text file to dropbox but it is showing DropboxUnlinkedException.

Solution ::

First, let your program get fully authenticated. Just after mDBApi.getSession.startAuthentication() method, onResume method will get called automatically. Let the full authentication get completed and then do what do you want to do.

MainActivity

public class MainActivity extends Activity implements LocationListener{

TextView date;
TextView lati;
TextView longi;
Button b1;
private DropboxAPI<AndroidAuthSession> mDBApi;
private LocationManager locationManager;
private String provider;

final static public String ACCOUNT_PREFS_NAME = "GPS_File";
final static public String APP_KEY = "5qiq4z06ikagxfb";
final static public String APP_SECRET = "f6mbf1hnn0re2ni";
final static public AccessType ACCESS_TYPE = AccessType.APP_FOLDER;

boolean mIsLoggedIn = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
    AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
    mDBApi = new DropboxAPI<AndroidAuthSession>(session);

 //this is start authentication     
   mDBApi.getSession().startAuthentication(MainActivity.this);
 //after this it will call onResume 

    date = (TextView)findViewById(R.id.textView2);
    lati = (TextView)findViewById(R.id.textView4);
    longi = (TextView)findViewById(R.id.textView6);
    b1 = (Button)findViewById(R.id.button1);

    createFile("abcd", "12345", "54321");
    toDropbox();

    setLoggedIn(mDBApi.getSession().isLinked());
}

void createFile(String str1,String str2,String str3)
{
    String data = str1+"\t"+str2+"\t"+str3;
    try{
        File myFile = new File("/sdcard/DropboxFile1.txt");
        myFile.createNewFile();
        FileOutputStream fOut = new FileOutputStream(myFile);
        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
      myOutWriter.append(data);
      myOutWriter.close();
      fOut.close();
        }
        catch(Exception e)
        {e.printStackTrace();}
}


void toDropbox()
{
    b1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            String filePath = Environment.getExternalStorageDirectory().getAbsolutePath().toString() + "/DropboxFile1.txt";
            File file = new File(filePath);

            mDBApi.getSession().startAuthentication(MainActivity.this);

            try {

                mDBApi.putFileOverwrite(filePath, new FileInputStream(file), file.length(), null);

            } catch (DropboxException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    });
}

private void clearKeys() {
    SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
    Editor edit = prefs.edit();
    edit.clear();
    edit.commit();
}

//This get call after StartAuthentication..
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) {
//Keep this toast.. It will show you the completed authentication..
            Toast.makeText(getBaseContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            Log.i("Dropbox", "Error authenticating", e);
        }
    }
}    

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(APP_KEY, key);
    edit.putString(APP_SECRET, secret);
    edit.commit();
}
public void setLoggedIn(boolean loggedIn) {
    mIsLoggedIn = loggedIn;
}
public boolean isLoggedIn() {
    return mIsLoggedIn;
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
@Override
public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub
}
}//MainActivity Ends..`

` After authentication get completed do your another stuff.

Siddharth
  • 9,349
  • 16
  • 86
  • 148
Lalit
  • 1,713
  • 1
  • 11
  • 19
  • `newFile` seems to have an extra curly brace in it, so presumably this code won't even compile. And why won't you give us the full stack trace of the exception? You haven't even told us what line of your code is triggering the exception. You also haven't told me what you did in the app to cause the exception. (My guess is that there was at least one button click involved, and *maybe* you logged in first...) – user94559 Dec 26 '13 at 07:20
  • Sorry for that sir, Now i have made all changes kindly check this out. and that newFile '{' was done mistakenly. thank you. ( ',' ) @smarx – Lalit Dec 26 '13 at 07:35
  • And sir, also tell me the **Create App** process on Dropbox. Like What **type of app do you want to create?** and the next steps. thanx. ( ',' ) @smarx – Lalit Dec 26 '13 at 07:37
  • As far as I can tell, you still haven't told us what you actually did in the app to cause this exception. We can now see that it's from a call in your button handler, so I'm guessing you pressed that button. What did you do before that? What worked? What didn't? What have you tried as you debugged this? Can you reproduce the error with a smaller program? Does the example in the SDK work for you? Does this always fail, or does it sometimes work? Have you searched for the error message... maybe in the SDK code? – user94559 Dec 26 '13 at 07:42
  • Sir, See the MainAcivity i made it simple now. At the first **one file get created automatically** which has some stuff. and **there is one button** so **after click to that button file should be send** that is my motto. It works till **mDBApi.getSession().startAuthentication(MainActivity.this)** after this **it goes to the dropbox log in page** and then **DropboxUnlinkedException** comes out in Logcat. I hope you will get what i mean to say. – Lalit Dec 26 '13 at 07:58
  • Also, where you are using "mDBApi.putFileOverwrite(filePath" Here I think should just be the name of the file. It's the file you want to replace with the new one (on dropbox). So maybe instead of using the complete file path from your android phone, just use "DropboxFile1.txt". – ialexander Dec 27 '13 at 11:59

2 Answers2

4

You're calling startAuthentication but then immediately trying to call API methods (before authentication has actually happened). You can only use the API once the user has authenticated. In your code, here's the part that runs after the user has authenticated and returns to your app:

protected void onResume() {
    ...
    if (session.authenticationSuccessful()) {
        ...
user94559
  • 59,196
  • 6
  • 103
  • 103
  • Okokk.. Then i'll do one thing, i will **call onResume()** method after **startAuthentication** Is it right sir? @smarx – Lalit Dec 26 '13 at 08:23
  • No, that's not right. `onResume` is automatically called when your app resumes. So the user authenticates in the Dropbox app, and when they come back to your app, `onResume` is called. This is just an Android concept and has nothing to do with Dropbox. – user94559 Dec 26 '13 at 09:02
  • Thank you sir. Now I am with the full understanding of how authentication works. But now my app has a different problem. `12-26 09:32:16.423: E/AndroidRuntime(1116): FATAL EXCEPTION: main 12-26 09:32:16.423: E/AndroidRuntime(1116): android.os.NetworkOnMainThreadException ` What it means. What should i do now for it? @smarx – Lalit Dec 26 '13 at 09:33
  • That's an unrelated question, and any search engine should pretty quickly tell you what the error means. – user94559 Dec 26 '13 at 09:50
  • check out http://stackoverflow.com/questions/28428719/dropboxunlinkedexception-if-you-have-not-set-an-access-token-pair-on-the-sessi/28668863#28668863 – Siddharth Feb 23 '15 at 07:40
  • @Siddharth If my answer is incomplete or unclear, please explain why. – user94559 Feb 23 '15 at 16:29
0

This error might also come when you miss calling this in onResume() of your activity :

                mDBApi.getSession().finishAuthentication();
user2903200
  • 708
  • 2
  • 7
  • 19