无法添加窗口 - 令牌null不适用于应用程序

时间:2016-01-18 10:20:37

标签: android dropbox-api

我有一个按钮,可以将列出的目录中的所有文件上传到dropbox,但只要我点击它,应用就会一直崩溃。我尝试按照此Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context并更改

mDialog = new ProgressDialog(mContext);

mDialog = new ProgressDialog(Dropbox.this);

主要活动

    public class Dropbox extends AppCompatActivity implements View.OnClickListener {
private DropboxAPI<AndroidAuthSession> dropbox;
private final static String FILE_DIR = "/DropboxSample/";
private final static String DROPBOX_NAME = "dropbox_prefs";
private final static String ACCESS_KEY = "INSERT KEY HERE";
private final static String ACCESS_SECRET = "INSERT KEY HERE";
private boolean isLoggedIn;
private Button logIn;
private Button uploadFile;
private Button listFiles;
private LinearLayout container;
private static final int SELECT_PHOTO = 100;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dropbox);

    logIn = (Button) findViewById(R.id.dropbox_login);
    logIn.setOnClickListener(this);
    uploadFile = (Button) findViewById(R.id.upload_file);
    uploadFile.setOnClickListener(this);
    //listFiles = (Button) findViewById(R.id.list_files);
    //listFiles.setOnClickListener(this);
    container = (LinearLayout) findViewById(R.id.container_files);

    loggedIn(false);
    AndroidAuthSession session;
    AppKeyPair pair = new AppKeyPair(ACCESS_KEY, ACCESS_SECRET);

    SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
    String key = prefs.getString(ACCESS_KEY, null);
    String secret = prefs.getString(ACCESS_SECRET, null);

    if (key != null && secret != null) {
        AccessTokenPair token = new AccessTokenPair(key, secret);
        session = new AndroidAuthSession(pair, Session.AccessType.APP_FOLDER, token);
    } else {
        session = new AndroidAuthSession(pair, Session.AccessType.APP_FOLDER);
    }
    dropbox = new DropboxAPI<AndroidAuthSession>(session);
}

@Override
protected void onResume() {
    super.onResume();

    AndroidAuthSession session = dropbox.getSession();
    if (session.authenticationSuccessful()) {
        try {
            session.finishAuthentication();
            TokenPair tokens = session.getAccessTokenPair();
            SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(ACCESS_KEY, tokens.key);
            editor.putString(ACCESS_SECRET, tokens.secret);
            editor.commit();
            loggedIn(true);
        } catch (IllegalStateException e) {
            Toast.makeText(this, "Error during Dropbox authentication",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

public void loggedIn(boolean isLogged) {
    isLoggedIn = isLogged;
    uploadFile.setEnabled(isLogged);
    listFiles.setEnabled(isLogged);
    logIn.setText(isLogged ? "Log out" : "Log in");
}

private final Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        ArrayList<String> result = msg.getData().getStringArrayList("data");
        for (String fileName : result) {
            Log.i("ListFiles", fileName);
            TextView tv = new TextView(Dropbox.this);
            tv.setText(fileName);
            container.addView(tv);
        }
    }
};

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.dropbox_login:
            if (isLoggedIn) {
                dropbox.getSession().unlink();
                loggedIn(false);
            } else {
                dropbox.getSession().startAuthentication(Dropbox.this);
            }

            break;
        // case R.id.list_files:
        //   ListDropboxFiles list = new ListDropboxFiles(dropbox, FILE_DIR,
        //         handler);
        //list.execute();
        //break;
        case R.id.upload_file:
            UploadFileToDropbox upload = new UploadFileToDropbox(this, dropbox, FILE_DIR);
            upload.execute();
            break;
        default:
            break;
    }
}







      public class UploadFileToDropbox extends AsyncTask<Void, Void, Boolean> {


        private DropboxAPI<?> dropbox;
        private String mPath;
        private long mFileLen;
        private final ProgressDialog mDialog;
        private DropboxAPI.UploadRequest mRequest;
        private Context mContext;
        private String mErrorMsg;
        private File[] listFile;

        public UploadFileToDropbox(Context context, DropboxAPI<?> dropbox, String path) {
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/ImageLocationforApp");
            listFile = file.listFiles();

            mContext = context.getApplicationContext();
            this.dropbox = dropbox;
            this.mPath = path;
            for(int y=0 ; y<listFile.length ; y++){
                mFileLen = listFile[y].length() + mFileLen;
            }

            mDialog = new ProgressDialog(mContext);
            mDialog.setMax(100);
            mDialog.setMessage("Uploading " + file);
            mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mDialog.setProgress(0);
            mDialog.setButton(ProgressDialog.BUTTON_POSITIVE, "Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // This will cancel the putFile operation
                    try {
                        mRequest.abort();
                    } catch (Exception e) {

                    }

                }
            });
            mDialog.show();
            mDialog.setCanceledOnTouchOutside(false);
        }
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                // By creating a request, we get a handle to the putFile operation,
                // so we can cancel it later if we want to
                for(int y=0 ; y<listFile.length;y++) {
                    FileInputStream fis = new FileInputStream(listFile[y]);
                    String path = mPath + listFile[y].getName();
                    mRequest = dropbox.putFileOverwriteRequest(path, fis, listFile[y].length(),
                            new ProgressListener() {
                                @Override
                                public long progressInterval() {
                                    // Update the progress bar every half-second or so
                                    return 500;
                                }

                                @Override
                                public void onProgress(long bytes, long total) {
                                    publishProgress(bytes);
                                }
                            });
                }
                if (mRequest != null) {
                    mRequest.upload();
                    return true;
                }

            } catch (DropboxUnlinkedException e) {
                // This session wasn't authenticated properly or user unlinked
                mErrorMsg = "This app wasn't authenticated properly.";
            } catch (DropboxFileSizeException e) {
                // File size too big to upload via the API
                mErrorMsg = "This file is too big to upload";
            } catch (DropboxPartialFileException e) {
                // We canceled the operation
                mErrorMsg = "Upload canceled";
            } catch (DropboxServerException e) {
                // Server-side exception.  These are examples of what could happen,
                // but we don't do anything special with them here.
                if (e.error == DropboxServerException._401_UNAUTHORIZED) {
                    // Unauthorized, so we should unlink them.  You may want to
                    // automatically log the user out in this case.
                } else if (e.error == DropboxServerException._403_FORBIDDEN) {
                    // Not allowed to access this
                } else if (e.error == DropboxServerException._404_NOT_FOUND) {
                    // path not found (or if it was the thumbnail, can't be
                    // thumbnailed)
                } else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
                    // user is over quota
                } else {
                    // Something else
                }
                // This gets the Dropbox error, translated into the user's language
                mErrorMsg = e.body.userError;
                if (mErrorMsg == null) {
                    mErrorMsg = e.body.error;
                }
            } catch (DropboxIOException e) {
                // Happens all the time, probably want to retry automatically.
                mErrorMsg = "Network error.  Try again.";
            } catch (DropboxParseException e) {
                // Probably due to Dropbox server restarting, should retry
                mErrorMsg = "Dropbox error.  Try again.";
            } catch (DropboxException e) {
                // Unknown error
                mErrorMsg = "Unknown error.  Try again.";
            } catch (FileNotFoundException e) {
            }
            return false;
        }

        protected void onProgressUpdate(Long... progress) {
            int percent = (int) (100.0 * (double) progress[0] / mFileLen + 0.5);
            mDialog.setProgress(percent);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            mDialog.dismiss();
            if (result) {
                showToast("Successfully uploaded");
            } else {
                showToast(mErrorMsg);
            }
        }

        private void showToast(String msg) {
            Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
            error.show();
        }
    }

}
  

错误记录

01-18 18:01:45.919  27010-27010/com.sp.fyp.captury E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.sp.fyp.captury, PID: 27010
    android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
            at android.view.ViewRootImpl.setView(ViewRootImpl.java:691)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:288)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:312)
            at com.sp.fyp.captury.Dropbox$UploadFileToDropbox.<init>(Dropbox.java:197)
            at com.sp.fyp.captury.Dropbox.onClick(Dropbox.java:146)
            at android.view.View.performClick(View.java:5184)
            at android.view.View$PerformClick.run(View.java:20910)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5951)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

更改为Dropbox.this后的错误日志

Process: com.sp.fyp.captury, PID: 7414
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sp.fyp.captury/com.sp.fyp.captury.Dropbox}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2702)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
            at android.app.ActivityThread.access$900(ActivityThread.java:177)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5951)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
            at com.sp.fyp.captury.Dropbox.loggedIn(Dropbox.java:112)
            at com.sp.fyp.captury.Dropbox.onCreate(Dropbox.java:70)
            at android.app.Activity.performCreate(Activity.java:6289)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2655)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
            at android.app.ActivityThread.access$900(ActivityThread.java:177)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5951)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

0 个答案:

没有答案