0

I've been struggling to get Dropbox V2 to work with my app for a while now and I'm not sure what else I can do. I've basically followed the online tutorial and other sources, but I keep getting errors keeping me from progressing further. The weird thing is when I first put in the new code it worked fine. Once I started adding alerts confirming success of upload or anything else it started bugging out when trying to log in. I have a feeling the app was still logged in via the old code but I have no way to confirm this because I didn't save a copy of the project at that point. I've tried putting the code in a separate Thread but I still get errors. It's like it's not connecting to the API like it should be, but I don't know what I'm doing wrong here. I'm putting the app key for the token, is that meant to be something different? Here's my code:

try {
        DbxRequestConfig config = new DbxRequestConfig("dropbox/java-tutorial");
        client = new DbxClientV2(config, "token");

        // Get current account info
        FullAccount account = client.users().getCurrentAccount();
        System.out.println(account.getName().getDisplayName());

        // Get files and folder metadata from Dropbox root directory
        ListFolderResult result = client.files().listFolder("");
        while (true) {
            for (Metadata metadata : result.getEntries()) {
                System.out.println(metadata.getPathLower());
            }

            if (!result.getHasMore()) {
                break;
            }

            result = client.files().listFolderContinue(result.getCursor());
        }
    } catch(DbxException e){}

And the file upload code:

Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    Exception mException=null;
                    FileMetadata metadata=null;
                    try {
                        // Upload "test.txt" to Dropbox
                        //dialog.dismiss();
                        metadata = client.files().uploadBuilder("/"+title+".sheet").uploadAndFinish(fis);

                    }  catch(DbxException e){
                        mException = e;
                    }
                    catch(IOException e){
                        mException = e;
                    }

                    if (mException != null) {
                        //dialog.dismiss();
                        final Exception finalE = mException;
                        Handler h = new Handler(Looper.getMainLooper());
                        h.post(new Runnable() {
                            public void run() {
                                Log.e(TAG, "Failed to upload file.", finalE);
                                Toast.makeText(MainActivity.this,
                                        "An error has occurred",
                                        Toast.LENGTH_SHORT)
                                        .show();
                            }
                        });
                    } else if (metadata == null) {
                        //dialog.dismiss();
                        final Exception finalE = mException;
                        Handler h = new Handler(Looper.getMainLooper());
                        h.post(new Runnable() {
                            public void run() {
                                Log.e(TAG, "Failed to upload file.", finalE);
                                Toast.makeText(MainActivity.this,
                                        "An error has occurred",
                                        Toast.LENGTH_SHORT)
                                        .show();
                            }
                        });
                    } else {
                        //dialog.dismiss();
                        final String message = metadata.getName() + " size " + metadata.getSize() + " modified " +
                                DateFormat.getDateTimeInstance().format(metadata.getClientModified());
                        Handler h = new Handler(Looper.getMainLooper());
                        h.post(new Runnable() {
                            public void run() {
                                Toast.makeText(MainActivity.this,
                                        message,
                                        Toast.LENGTH_SHORT)
                                        .show();
                            }
                        });

                    }
                }
            });
            t.start();

Any ideas or tips would be greatly appreciated.

Dominic
  • 31
  • 1
  • 5
  • Possible duplicate of [Trying To Upload To Dropbox: NetworkOnMainThreadException?](http://stackoverflow.com/questions/10892858/trying-to-upload-to-dropbox-networkonmainthreadexception) – Greg Mar 30 '17 at 21:43

1 Answers1

0

Ended up solving it with with an async task. I was also failing to get the Auth token and was stupidly using my key instead.

Async Task:

import android.content.Context;
import android.os.AsyncTask;
import com.dropbox.core.DbxException;
import com.dropbox.core.v2.DbxClientV2;
import com.dropbox.core.DbxRequestConfig;
import com.dropbox.core.v2.users.FullAccount;

public class ConnectToDB extends AsyncTask<String, Void, FullAccount> {
    private final Context mContext;
    private DbxClientV2 mDbxClient;
    private Exception mException;
    private String token;
    private Callback mCallback;

    public interface Callback {
        void onLoginComplete(FullAccount result, DbxClientV2 client);
        void onError(Exception e);
    }

    ConnectToDB(Context context, String token, Callback callback) {
        mContext = context;
        this.token=token;
        mCallback=callback;
    }

    @Override
    protected void onPostExecute(FullAccount result) {
        super.onPostExecute(result);
        if (mException != null) {
            mCallback.onError(mException);
        } else if (result == null) {
            mCallback.onError(null);
        } else {
            mCallback.onLoginComplete(result, mDbxClient);
        }
    }

    @Override
    protected FullAccount doInBackground(String... params) {
        DbxRequestConfig config = new DbxRequestConfig("appName");
        mDbxClient = new DbxClientV2(config, this.token);

        try {
            // Get current account info
            return mDbxClient.users().getCurrentAccount();
        }catch (DbxException e){
            mException = e;
        }
        return null;
    }
}

The correct way to get the token

public void initDropBox(){
    if (prefs.getString("dbKey", "").equals("")) {
        Auth.startOAuth2Authentication(this,"appKey");
        prefs.edit().putString("dbKey", Auth.getOAuth2Token()).commit();
    }else{
        initAndLoadData(prefs.getString("dbKey", ""));
    }
}
@Override
protected void onResume()
{
    super.onResume();
    try{
        String accessToken = prefs.getString("dbKey",null);
        if (accessToken == null) {
            accessToken = Auth.getOAuth2Token();
            if (accessToken != null) {
                prefs.edit().putString("dbKey", accessToken).apply();
                initAndLoadData(accessToken);
            }
        }else{
            initAndLoadData(accessToken);
        }
    }catch(Exception e){}
}
private void initAndLoadData(String accessToken) {
    final MainActivity context = this;
    new ConnectToDB(this, accessToken, new ConnectToDB.Callback() {
        @Override
        public void onLoginComplete(FullAccount result, DbxClientV2 client) {
            context.client = client;
            Log.e(TAG, "Success.", null);
        }

        @Override
        public void onError(Exception e) {
            Log.e(TAG, "Failed to login.", e);
            Toast.makeText(MainActivity.this,
                    "An error has occurred",
                    Toast.LENGTH_SHORT)
                    .show();
        }
    }).execute();
}
Dominic
  • 31
  • 1
  • 5