Uploading file to Dropbox in android, putFile method throws Exception

时光毁灭记忆、已成空白 提交于 2019-12-24 03:34:09

问题


I'm trying to upload a file to Dropbox using the Dropbox API tutorial. I logged in when creating the Activity and I add some code to the onResume() method as said in the tutorial. Then, after clicking a button, startService() method is called.

When it reaches the line "com.dropbox.client2.DropboxAPI.Entry response = mDBApi.putFile("/working-draft.txt", inputStream, file.length(), null, null);", the app throws an Exception (not a DropboxException, nor DropboxUnlinkedException, .... It just enters the catch Exception block).

Any idea what might be wrong?

Here is my code:

private final static String APP_KEY = "xxxxxxxxxxxxx";
private final static String APP_SECRET = "xxxxxxxxxxxxx";
private DropboxAPI<AndroidAuthSession> mDBApi;

@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);   
    mDBApi = new DropboxAPI<AndroidAuthSession>(session);
    AndroidAuthSession s = mDBApi.getSession();
    s.startOAuth2Authentication(MainActivity.this);
}

@Override
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);
        }
    }

}

public void startService(View v) {    

    String text = "Hello world";
    String filePath = Environment.getExternalStorageDirectory() + "/working-draft.txt";
    Log.i("SERVICE", filePath);
    File file = new File(filePath);
    try {
        if(!file.exists()){
            file.createNewFile();
        }
        BufferedWriter output = new BufferedWriter(new FileWriter(file));
        output.write(text);
        output.close();
        FileInputStream inputStream = new FileInputStream(file);
        com.dropbox.client2.DropboxAPI.Entry response = mDBApi.putFile("/working-draft.txt", inputStream, file.length(), null, null);
        Log.i("DbExampleLog", "The uploaded file's rev is: " + response.rev);
    }
    catch(DropboxUnlinkedException e){
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        Log.i("Exception", errors.toString());
    }
    catch(DropboxFileSizeException e){
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        Log.i("Exception", errors.toString());
    }
    catch(DropboxServerException e){
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        Log.i("Exception", errors.toString());
    }
    catch(DropboxIOException e){
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        Log.i("Exception", errors.toString());
    }
    catch (DropboxException e){
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        Log.i("Exception", errors.toString());
    }
    catch (Exception e) {
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        Log.i("Exception", errors.toString());
    }
}

This is the stackTrace I got:

10-23 22:42:34.254: I/Exception(28082): android.os.NetworkOnMainThreadException
10-23 22:42:34.254: I/Exception(28082):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
10-23 22:42:34.254: I/Exception(28082):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
10-23 22:42:34.254: I/Exception(28082):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
10-23 22:42:34.254: I/Exception(28082):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
10-23 22:42:34.254: I/Exception(28082):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
10-23 22:42:34.254: I/Exception(28082):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
10-23 22:42:34.254: I/Exception(28082):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
10-23 22:42:34.254: I/Exception(28082):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
10-23 22:42:34.254: I/Exception(28082):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
10-23 22:42:34.254: I/Exception(28082):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-23 22:42:34.254: I/Exception(28082):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-23 22:42:34.254: I/Exception(28082):     at com.dropbox.client2.RESTUtility.execute(RESTUtility.java:387)
10-23 22:42:34.254: I/Exception(28082):     at com.dropbox.client2.DropboxAPI$BasicUploadRequest.upload(DropboxAPI.java:1119)
10-23 22:42:34.254: I/Exception(28082):     at com.dropbox.client2.DropboxAPI.putFile(DropboxAPI.java:1460)
10-23 22:42:34.254: I/Exception(28082):     at com.example.example.MainActivity.startService(MainActivity.java:81)
10-23 22:42:34.254: I/Exception(28082):     at java.lang.reflect.Method.invokeNative(Native Method)
10-23 22:42:34.254: I/Exception(28082):     at java.lang.reflect.Method.invoke(Method.java:525)
10-23 22:42:34.254: I/Exception(28082):     at android.view.View$1.onClick(View.java:3628)
10-23 22:42:34.254: I/Exception(28082):     at android.view.View.performClick(View.java:4240)
10-23 22:42:34.254: I/Exception(28082):     at android.view.View$PerformClick.run(View.java:17721)
10-23 22:42:34.254: I/Exception(28082):     at android.os.Handler.handleCallback(Handler.java:730)
10-23 22:42:34.254: I/Exception(28082):     at android.os.Handler.dispatchMessage(Handler.java:92)
10-23 22:42:34.254: I/Exception(28082):     at android.os.Looper.loop(Looper.java:137)
10-23 22:42:34.254: I/Exception(28082):     at android.app.ActivityThread.main(ActivityThread.java:5103)
10-23 22:42:34.254: I/Exception(28082):     at java.lang.reflect.Method.invokeNative(Native Method)
10-23 22:42:34.254: I/Exception(28082):     at java.lang.reflect.Method.invoke(Method.java:525)
10-23 22:42:34.254: I/Exception(28082):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-23 22:42:34.254: I/Exception(28082):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-23 22:42:34.254: I/Exception(28082):     at dalvik.system.NativeStart.main(Native Method)

Thanks in advance.


回答1:


You're getting a NetworkOnMainThreadException, which means you're trying to make a network call on the main thread, which isn't allowed on Android. (The putFile method makes a network call to the Dropbox API servers to send up the file content.) You should make this call on a background thread instead. There are other answers about how to do this, e.g.: How to fix android.os.NetworkOnMainThreadException?




回答2:


Ok, thanks a lot Greg. It worked perfectly following the indications in the link you shared. I used another class extending AsyncTask, just like it's done in this post, the "Upload File to Dropbox using Android SDK" section.



来源:https://stackoverflow.com/questions/26537338/uploading-file-to-dropbox-in-android-putfile-method-throws-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!