如何通过API从Dropbox下载多张图片?

时间:2016-01-18 18:47:38

标签: android dropbox-api

我想通过Dropbox API下载图片,所以我按照示例代码@ Android Dropbox API file download但我不明白如何将其集成到我当前的代码中。我尝试将api.getFileStream("dropbox", dbPath, null);更改为dropbox.getFileStream("dropbox", dbPath, null);,从而导致错误:

    'getFileStream(java.lang.String, java.lang.String)' in 'com.dropbox.client2.DropboxAPI' cannot be applied to '(java.lang.String, java.lang.String, null)'

更新1:更改为`dropbox.getFileStream(FILE_DIR,null)

主要代码

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 downloadFile;
    private Button listFiles;
    private LinearLayout container;

    @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);
        downloadFile = (Button) findViewById(download_file);
        downloadFile.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 ,token);
        } else {
            session = new AndroidAuthSession(pair );
        }
        dropbox = new DropboxAPI<>(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);
        downloadFile.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(dropbox, FILE_DIR);
                upload.execute();
                break;
            case R.id.download_file:
                try {
                    downloadDropboxFile(FILE_DIR,(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+"CapturyGallery")));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }
    public class UploadFileToDropbox extends AsyncTask<Void, Long, Boolean> {


        private DropboxAPI<?> dropbox;
        private String mPath;
        private Context mContext;
        private final ProgressDialog mDialog;
        private DropboxAPI.UploadRequest mRequest;
        private String mErrorMsg;

        private File[] listFile;
        private int mFilesUploaded;
        private int mCurrentFileIndex;;

        public UploadFileToDropbox(DropboxAPI<?> dropbox, String path) {
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/CapturyGallery");
            listFile = file.listFiles();
            mContext = Dropbox.this;
            this.dropbox = dropbox;
            this.mPath = path;

            mFilesUploaded = 0 ;
            mCurrentFileIndex = 0 ;


            mDialog = new ProgressDialog(mContext);
            mDialog.setMax(100);
            mDialog.setMessage("Uploading file 1 /" +listFile.length);
            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 {
                    for (int y = 0; y < listFile.length; y++) {
                        mCurrentFileIndex = y;
                        File file = listFile[y];
                        // By creating a request, we get a handle to the putFile operation,
                        // so we can cancel it later if we want to

                        FileInputStream fis = new FileInputStream(file);
                        String path = mPath + file.getName();
                        mRequest = dropbox.putFileOverwriteRequest(path, fis, file.length(),
                                new ProgressListener() {
                                    @Override
                                    public long progressInterval() {
                                        // Update the progress bar every half-second or so
                                        return 5;
                                    }

                                    @Override
                                    public void onProgress(long bytes, long total) {
                                        if (isCancelled()) {
                                            mRequest.abort();
                                        } else {
                                            publishProgress(bytes);
                                        }

                                    }
                                });

                       mRequest.upload();
                        if(!isCancelled()){
                            mFilesUploaded++;
                        }else{
                            return false;
                        }
                    }
                    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;
        }
        @Override
        protected void onProgressUpdate(Long... progress) {
            long totalBytes = 0;
            long bytesUploaded = 0;
            for (int i = 0; i < listFile.length; i++) {
                Long bytes = listFile[i].length();
                totalBytes += bytes;

                if (i < mCurrentFileIndex) {
                    bytesUploaded += bytes;
                }

                bytesUploaded += progress[0];
                int percent = 100;
                int percent1 = (int) (percent * (bytesUploaded/totalBytes));
                mDialog.setMessage("Uploading file " + (mCurrentFileIndex + 1) + " / " + listFile.length);
                mDialog.setProgress(percent1);
            }
        }
        @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(Dropbox.this, msg, Toast.LENGTH_LONG);
            error.show();
        }
    }

public class ListDropboxFiles extends AsyncTask<Void, Void, ArrayList<String>> {

        private DropboxAPI<?> dropbox;
        private String path;
    private Handler handler;

        public ListDropboxFiles(DropboxAPI<?> dropbox, String path, Handler handler) {
            this.dropbox = dropbox;
            this.path = path;
            this.handler = handler;
        }

        @Override
        protected ArrayList<String> doInBackground(Void... params) {
            ArrayList<String> files = new ArrayList<String>();
            try {
                DropboxAPI.Entry directory = dropbox.metadata(path, 1000, null, true, null);
                for (DropboxAPI.Entry entry : directory.contents) {
                    files.add(entry.fileName());
                }
            } catch (DropboxException e) {
                e.printStackTrace();
            }

            return files;
        }

        @Override
        protected void onPostExecute(ArrayList<String> result) {
            Message msgObj = handler.obtainMessage();
            Bundle b = new Bundle();
            b.putStringArrayList("data", result);
            msgObj.setData(b);
            handler.sendMessage(msgObj);

        }
    }

从示例代码中添加

     private boolean downloadDropboxFile(String dbPath, File localFile) throws IOException {

            BufferedInputStream br = null;
            BufferedOutputStream bw = null;

            try {
                if (!localFile.exists()) {
                    localFile.createNewFile(); //otherwise dropbox client will fail silently
                }

                FileDownload fd = dropbox.getFileStream("dropbox", dbPath, null);
                br = new BufferedInputStream(fd.is);
                bw = new BufferedOutputStream(new FileOutputStream(localFile));

                byte[] buffer = new byte[4096];
                int read;
                while (true) {
                    read = br.read(buffer);
                    if (read <= 0) {
                        break;
                    }
                    bw.write(buffer, 0, read);
                }
            } finally {
                //in finally block:
                if (bw != null) {
                    bw.close();
                }
                if (br != null) {
                    br.close();
                }
            }

            return true;
        }

    }

>

1 个答案:

答案 0 :(得分:0)

错误消息表明方法定义是:

getFileStream(java.lang.String, java.lang.String)

这也是the documentation for the getFileStream method in the Dropbox Android Core SDK所显示的内容。

但是,您尝试使用三个参数:

(java.lang.String, java.lang.String, null)

因此,要正确调用该方法,您应该删除最后一个参数(null)。