如何在Android的列表视图显示Dropbox的文件吗?视图、文件、如何在、列表

2023-09-07 22:40:44 作者:心悦君兮君不知

我一直在浏览上这里一段时间的答案,并在我的code就业问题的答案,但它似乎仍然没有工作。我只是想显示的内容的列表视图中的Dropbox账户,并给用户一个选择下载文件/文件夹。我MainActivity用于崩溃打开它,是围绕我onPostExecute内容有try / catch语句处理NullPointerException异常后立即解决的崩溃。但是,应用程序仍无法显示在Dropbox的内容。在只有一个MainActivity和DLFiles(AsyncTask的)同类产品中最基础阶段,如何使这项工作?我一直在这几天,请大家帮忙! 先谢谢了。

MainActivity.java

 公共类MainActivity延伸活动{

    最终静态私人字符串APP_KEY =app_key_here;
    最终静态私人字符串APP_SECRET =app_secret_here;
    最后的静态专用接入类型ACCESS_TYPE = AccessType.DROPBOX;
    私有静态最终布尔USE_OAUTH1 = FALSE;

    //你不需要改变这些,别管他们。
    最终静态私人字符串ACCOUNT_ preFS_NAME =preFS;
    最终静态私人字符串ACCESS_KEY_NAME =ACCESS_KEY;
    最终静态私人字符串ACCESS_SECRET_NAME =ACCESS_SECRET;

    //在类的声明部分:
    私人DropboxAPI< AndroidAuthSession> mDBApi;

    私人布尔mLoggedIn;
    私人最终字符串FILE_DIR =/;
    私有String [] mfnames;
    私人的ListView mListView;
    私人按钮listEm;



    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);



        //后来在一些初始化函数:
        AppKeyPair appKeys =新AppKeyPair(APP_KEY,APP_SECRET);
        AndroidAuthSession会议=新AndroidAuthSession(appKeys,ACCESS_TYPE);
        mDBApi =新DropboxAPI< AndroidAuthSession>(会议);

        如果(!mLoggedIn){
            如果(USE_OAUTH1){
                。mDBApi.getSession()startAuthentication(MainActivity.this);
            } 其他{
                。mDBApi.getSession()startOAuth2Authentication(MainActivity.this);
            }
        }

        mListView =(ListView控件)findViewById(R.id.list);

        listEm =(按钮)findViewById(R.id.listit);

        listEm.setOnClickListener(新OnClickListener(){
            公共无效的onClick(视图v){
                DLFiles DLF =新DLFiles(MainActivity.this,mDBApi,
                        FILE_DIR,mfnames,mListView);
                dlf.execute();
            }
        });



        checkLoggedIn(mDBApi.getSession()isLinked());


    }

    私人无效checkLoggedIn(布尔的loggedIn){
        mLoggedIn =的loggedIn;
    }



    保护无效onResume(){
        super.onResume();

        如果(mDBApi.getSession()。authenticationSuccessful()){
            尝试 {
                //按要求完成身份验证,设置在会话访问令牌
                。mDBApi.getSession()finishAuthentication();

                字符串accessToken = mDBApi.getSession()getOAuth2AccessToken()。

            }赶上(IllegalStateException异常E){
                Log.i(DbAuthLog,错误认证,E);
            }
        }
    }

    私人无效loadAuth(AndroidAuthSession会话){
        共享preferences preFS = getShared preferences(ACCOUNT_ preFS_NAME,0);
        字符串键= prefs.getString(ACCESS_KEY_NAME,NULL);
        字符串秘密= prefs.getString(ACCESS_SECRET_NAME,NULL);
        如果(关键== NULL ||秘密== NULL || key.length()== 0 || secret.length()== 0)收益;

        如果(key.equals(oauth2:)){
            //如果键设置为oauth2:那么我们可以假设该令牌是OAuth的2。
            session.setOAuth2AccessToken(秘密);
        } 其他 {
            //还支持使用旧的OAuth的1令牌。
            session.setAccessTokenPair(新AccessTokenPair(密钥,密钥));
        }
    }


    / **
     *显示保持访问键从受信任的身份验证在本地恢复
     *存储,而不是存储的用户名和放大器;密码,并重新验证每
     *时间(这是不能做到的,曾经)。
     * /
    私人无效storeAuth(AndroidAuthSession会话){
        //存放的OAuth 2访问令牌,如果存在的话。
        串oauth2AccessToken = session.getOAuth2AccessToken();
        如果(oauth2AccessToken!= NULL){
            共享preferences preFS = getShared preferences(ACCOUNT_ preFS_NAME,0);
            编辑器编辑= prefs.edit();
            edit.putString(ACCESS_KEY_NAMEoauth2:);
            edit.putString(ACCESS_SECRET_NAME,oauth2AccessToken);
            edit.commit();
            返回;
        }
        //存放的OAuth 1访问令牌,如果存在的话。这仅仅是必要的,如果
        //你还在使用OAuth 1。
        AccessTokenPair oauth1AccessToken = session.getAccessTokenPair();
        如果(oauth1AccessToken!= NULL){
            共享preferences preFS = getShared preferences(ACCOUNT_ preFS_NAME,0);
            编辑器编辑= prefs.edit();
            edit.putString(ACCESS_KEY_NAME,oauth1AccessToken.key);
            edit.putString(ACCESS_SECRET_NAME,oauth1AccessToken.secret);
            edit.commit();
            返回;
        }
    }

    私人AndroidAuthSession buildSession(){
        AppKeyPair appKeyPair =新AppKeyPair(MainActivity.APP_KEY,MainActivity.APP_SECRET);

        AndroidAuthSession会议=新AndroidAuthSession(appKeyPair);
        loadAuth(会议);
        返回会议;
    }
}
 

DLFiles.java

 公共类DLFiles延伸的AsyncTask<虚空,龙的String []> {

    私人语境mContext;
    私人最终ProgressDialog mDialog;
    私人DropboxAPI<> MAPI;
    私人字符串的mpath;

    私人的FileOutputStream mFos;

    私人布尔mCanceled;
    私人龙mFileLen;
    私人字符串mErrorMsg;
    私有String [] fnames;

    公共DLFiles(上下文的背景下,DropboxAPI<> API,
            字符串dropboxPath,字符串[] efnames,ListView控件的ListView){
        //我们设置的背景下这种方式使我们不小心泄露活动
        mContext = context.getApplicationContext();
        fnames = efnames;
        MAPI = API;
        的mpath = dropboxPath;

        mDialog =新ProgressDialog(上下文);
        mDialog.setMessage(打开目录);
        mDialog.show();
    }

    @覆盖
    受保护的String [] doInBackground(虚空...... PARAMS){
        //获取元数据目录


        尝试{
            ArrayList的<字符串>文件名=新的ArrayList<字符串>();
            项的dirent = mApi.metadata(的mpath,1000,空,真,空);
            对于(输入ENT:dirent.contents){
                如果(ent.isDir){
                    //将它添加到大拇指,我们可以选择列表
                    filenames.add(&其中;目录>中+ ent.path);}
                其他{
                    filenames.add(ent.fileName());
                }


            }
            fnames = filenames.toArray(新的String [filenames.size());


        }赶上(DropboxUnlinkedException E){
            //该AuthSession未正确验证或用户未链接。
        }赶上(DropboxPartialFileException E){
            //我们取消了操作
            mErrorMsg =下载已取消;
        }赶上(DropboxServerException E){
            //服务器端异常。这些都是会发生什么的例子,
            //但是我们不与他们在这里做什么特别的。
            如果(e.error == DropboxServerException._304_NOT_MODIFIED){
                //不会发生,因为我们不通过修订中的元数据
            }否则,如果(e.error == DropboxServerException._401_UNAUTHORIZED){
                //未经授权的,所以我们应该取消它们的链接。您可能要
                //自动注销用户在这种情况下。
            }否则,如果(e.error == DropboxServerException._403_FORBIDDEN){
                //不允许访问此
            }否则,如果(e.error == DropboxServerException._404_NOT_FOUND){
                //路径未找到(或如果它是缩略图,不能
                //缩略图)
            }否则,如果(e.error == DropboxServerException._406_NOT_ACCEPTABLE){
                //太多的条目返回
            }否则,如果(e.error == DropboxServerException._415_UNSUPPORTED_MEDIA){
                //不能缩略
            }否则,如果(e.error == DropboxServerException._507_INSUFFICIENT_STORAG​​E){
                // 用户超出配额
            } 其他 {
                //别的东西
            }
            //这得到了Dropbox的错误,翻译成用户的语言
            mErrorMsg = e.body.userError;
            如果(mErrorMsg == NULL){
                mErrorMsg = e.body.error;
            }
        }赶上(DropboxIOException E){
            //发生的时间,可能要自动重试。
            mErrorMsg =网络错误重试。;
        }赶上(DropboxParseException E){
            //可能是由于Dropbox的服务器重新启动后,应重试
            mErrorMsg =。Dropbox的错误重试。;
        }赶上(DropboxException E){
            // 未知错误
            mErrorMsg =未知错误重试。;
        }
        返回fnames;
    }

    @覆盖
    保护无效onProgressUpdate(长...进度){
        INT百分比=(INT)(100.0 *(双)进展[0] / mFileLen + 0.5);
        mDialog.setProgress(百分比);
    }

    @覆盖
    保护无效onPostExecute(的String []的结果){
        尝试{
            如果(结果!= NULL){
                ArrayAdapter<字符串>阵列=新的ArrayAdapter<字符串>(mContext,
                        android.R.layout.simple_list_item_1,结果);

                Log.d(Dropbox的,结果[1]);
            }
            其他
                showToast(结果==空);
        }
        赶上(NullPointerException异常E){
            e.printStackTrace();
        }


    }
 

activity_main.xml

 < XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:方向=垂直
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT
    >


    <按钮
      机器人:ID =@ + ID / listit
      机器人:文本=列出目录的内容
      机器人:layout_width =FILL_PARENT
      机器人:layout_height =WRAP_CONTENT
      />

    <的LinearLayout
        机器人:ID =@ + ID /上市
        机器人:方向=垂直
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =FILL_PARENT
        机器人:layout_weight =1
        >

    <的ListView
        机器人:ID =@ + ID /列表
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =FILL_PARENT>

    < / ListView控件>

    < / LinearLayout中>

< / LinearLayout中>
 
Android 无法预览xml布局视图的解决办法

解决方案

我现在看到你的code是像DownloadRandomPicture.java。

字符串fnames [] = NULL;

在doOnBackGround():

 的ArrayList<字符串>文件名=新的ArrayList<字符串>();

        对于(输入ENT:dirent.contents){
            如果(ent.thumbExists){
                  filenames.add(ent.path);
             }
        }

     fnames = filenames.toArray(新的String [filenames.size());
 

在onPostExecute():

 如果(fnames!= NULL)
        {
            ArrayAdapter<字符串>阵列=新的ArrayAdapter<字符串>(mContext,android.R.layout.simple_list_item_1,fnames);

            listView1.setAdapter(阵列);
        }
       其他
            showToast(fnames ==空);
 

I've been browsing answers on here for a while and have employed most of the answers in my code but it still doesn't seem to work. I just want to display a listview of the content in a dropbox account and also give the user an option to download a file/folder. My MainActivity used to crash right after opening it, surrounding my onPostExecute content with a try/catch statement handling NullPointerException solved the crashing. But the app still fails to display the contents in Dropbox. At the most basic stage with just a MainActivity and a DLFiles (AsyncTask) class, how do I make this work? I've been at this for days, please help! Thanks in advance.

MainActivity.java

public class MainActivity extends Activity {

    final static private String APP_KEY = "app_key_here";
    final static private String APP_SECRET = "app_secret_here";
    final static private AccessType ACCESS_TYPE = AccessType.DROPBOX;
    private static final boolean USE_OAUTH1 = false;

    // You don't need to change these, leave them alone.
    final static private String ACCOUNT_PREFS_NAME = "prefs";
    final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
    final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";

    // In the class declaration section:
    private DropboxAPI<AndroidAuthSession> mDBApi;

    private boolean mLoggedIn;
    private final String FILE_DIR = "/";
    private String[] mfnames;
    private ListView mListView;
    private Button listEm;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        // And later in some initialization function:
        AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
        AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
        mDBApi = new DropboxAPI<AndroidAuthSession>(session);

        if (!mLoggedIn){
            if (USE_OAUTH1){
                mDBApi.getSession().startAuthentication(MainActivity.this);
            } else{
                mDBApi.getSession().startOAuth2Authentication(MainActivity.this);
            }
        }

        mListView = (ListView) findViewById(R.id.list);

        listEm = (Button) findViewById(R.id.listit);

        listEm.setOnClickListener(new OnClickListener(){
            public void onClick(View v){
                DLFiles dlf = new DLFiles(MainActivity.this,mDBApi,
                        FILE_DIR, mfnames,mListView );
                dlf.execute();
            }
        });



        checkLoggedIn(mDBApi.getSession().isLinked());


    }

    private void checkLoggedIn(boolean loggedIn){
        mLoggedIn = loggedIn;
    }



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

    private void loadAuth(AndroidAuthSession session) {
        SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
        String key = prefs.getString(ACCESS_KEY_NAME, null);
        String secret = prefs.getString(ACCESS_SECRET_NAME, null);
        if (key == null || secret == null || key.length() == 0 || secret.length() == 0) return;

        if (key.equals("oauth2:")) {
            // If the key is set to "oauth2:", then we can assume the token is for OAuth 2.
            session.setOAuth2AccessToken(secret);
        } else {
            // Still support using old OAuth 1 tokens.
            session.setAccessTokenPair(new AccessTokenPair(key, secret));
        }
    }


    /**
     * Shows keeping the access keys returned from Trusted Authenticator in a local
     * store, rather than storing user name & password, and re-authenticating each
     * time (which is not to be done, ever).
     */
    private void storeAuth(AndroidAuthSession session) {
        // Store the OAuth 2 access token, if there is one.
        String oauth2AccessToken = session.getOAuth2AccessToken();
        if (oauth2AccessToken != null) {
            SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
            Editor edit = prefs.edit();
            edit.putString(ACCESS_KEY_NAME, "oauth2:");
            edit.putString(ACCESS_SECRET_NAME, oauth2AccessToken);
            edit.commit();
            return;
        }
        // Store the OAuth 1 access token, if there is one.  This is only necessary if
        // you're still using OAuth 1.
        AccessTokenPair oauth1AccessToken = session.getAccessTokenPair();
        if (oauth1AccessToken != null) {
            SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
            Editor edit = prefs.edit();
            edit.putString(ACCESS_KEY_NAME, oauth1AccessToken.key);
            edit.putString(ACCESS_SECRET_NAME, oauth1AccessToken.secret);
            edit.commit();
            return;
        }
    }

    private AndroidAuthSession buildSession() {
        AppKeyPair appKeyPair = new AppKeyPair(MainActivity.APP_KEY, MainActivity.APP_SECRET);

        AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
        loadAuth(session);
        return session;
    }
}

DLFiles.java

public class DLFiles extends AsyncTask<Void, Long, String[]> {

    private Context mContext;
    private final ProgressDialog mDialog;
    private DropboxAPI<?> mApi;
    private String mPath;

    private FileOutputStream mFos;

    private boolean mCanceled;
    private Long mFileLen;
    private String mErrorMsg;
    private String[] fnames;

    public DLFiles( Context context, DropboxAPI<?> api,
            String dropboxPath,String[] efnames, ListView listView){
        // We set the context this way so we don't accidentally leak activities
        mContext = context.getApplicationContext();
        fnames = efnames;
        mApi = api;
        mPath = dropboxPath;

        mDialog = new ProgressDialog(context);
        mDialog.setMessage("Opening Directory");
        mDialog.show();
    }

    @Override
    protected String[] doInBackground(Void... params){
        // Get the metadata for a directory


        try{
            ArrayList<String> filenames = new ArrayList<String>();
            Entry dirent = mApi.metadata(mPath, 1000, null, true, null);
            for (Entry ent: dirent.contents){
                if(ent.isDir){
                    //Add it to the list of thumbs we can choose from
                    filenames.add("<dir>" + ent.path);}
                else{
                    filenames.add(ent.fileName());
                }


            }
            fnames = filenames.toArray(new String[filenames.size()]);


        } catch (DropboxUnlinkedException e) {
            // The AuthSession wasn't properly authenticated or user unlinked.
        } catch (DropboxPartialFileException e) {
            // We canceled the operation
            mErrorMsg = "Download 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._304_NOT_MODIFIED) {
                // won't happen since we don't pass in revision with metadata
            } else 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._406_NOT_ACCEPTABLE) {
                // too many entries to return
            } else if (e.error == DropboxServerException._415_UNSUPPORTED_MEDIA) {
                // 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.";
        }
        return fnames;  
    }

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

    @Override
    protected void onPostExecute(String[] result){
        try{
            if (result != null){
                ArrayAdapter<String> array = new ArrayAdapter<String>(mContext,
                        android.R.layout.simple_list_item_1, result);

                Log.d("dropbox", result[1]);
            }
            else
                showToast("result==null");
        }
        catch (NullPointerException e){
            e.printStackTrace();
        }


    }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >


    <Button 
      android:id="@+id/listit" 
      android:text="List directory content" 
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      />

    <LinearLayout
        android:id="@+id/listing" 
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        >

    <ListView 
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

    </ListView>

    </LinearLayout>

</LinearLayout>

解决方案

I now see that your code is like in DownloadRandomPicture.java.

String fnames [] = null;

In doOnBackGround():

     ArrayList<String> filenames = new ArrayList<String>();

        for (Entry ent: dirent.contents) {
            if (ent.thumbExists) {
                  filenames.add(ent.path);
             }
        }

     fnames = filenames.toArray(new String[filenames.size()]);

in onPostExecute():

       if ( fnames != null )
        {
            ArrayAdapter<String> array = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, fnames);

            listView1.setAdapter(array);
        }
       else
            showToast ( "fnames==null" );