Android Dropbox V2 NetworkOnMainThreadException

时间:2017-03-30 21:32:14

标签: android dropbox-api

我一直在努力让Dropbox V2与我的应用程序一起工作一段时间,而且我不确定我还能做些什么。我基本上都遵循了在线教程和其他来源,但我不断遇到错误让我无法继续前进。奇怪的是,当我第一次使用新代码时,它工作得很好。一旦我开始添加警报确认上传成功或其他任何事情,它在尝试登录时开始出现问题。我感觉应用程序仍然通过旧代码登录但我无法确认这是因为我没有'在那时保存项目的副本。我已经尝试将代码放在一个单独的线程中,但我仍然会遇到错误。它不像它应该的那样连接到API,但我不知道我在这里做错了什么。我把令牌的应用程序密钥放在那里,是不是意味着什么呢? 这是我的代码:

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){}

文件上传代码:

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();

非常感谢任何想法或提示。

1 个答案:

答案 0 :(得分:0)

使用异步任务结束解决它。我也没有获得Auth令牌,而是愚蠢地使用我的密钥。

异步任务:

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;
    }
}

获取令牌的正确方法

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();
}