草庐IT

android - Android 上的 Google Drive 错误 : java. lang.IllegalArgumentException:名称不能为空:null

coder 2023-12-01 原文

我在 Google Drive Android 应用程序上遇到了“java.lang.IllegalArgumentException:名称不能为空:null”异常。

我在谷歌上搜索了几天,但没有得到任何线索。 这是我在 Google 云端硬盘上获取文件列表的代码(一个简单的示例): (取自这里:Google Drive SDK Exception)

import java.io.IOException;
import java.util.ArrayList;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.AccountPicker;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.android.http.AndroidHttp;
import     com.google.api.client.googleapis.extensions.android.accounts.GoogleAccountManager;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.DriveRequest;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import com.maiko.xscanpet.R;
import com.maiko.xscanpet.cloud.GDriveHelper;

public class Fool_5 extends Activity {
private static final int CHOOSE_ACCOUNT=0;
private static String accountName;
private static int REQUEST_TOKEN=0;
private Button btn_drive;
private Context ctx = this;
private Activity a = this;

GoogleAccountCredential mCredential= null;

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    // set up the GUI layout
    setContentView(R.layout.fool_5);
    // set the variables to access the GUI controls
    btn_drive = (Button) findViewById(R.id.btn_drive);
        btn_drive.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            chooseAccount();
        }
        });
}

public void chooseAccount() {
    Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);
    startActivityForResult(intent, CHOOSE_ACCOUNT);
}

// Fetch the access token asynchronously.
void getAndUseAuthTokenInAsyncTask(Account account) {
    AsyncTask<Account, String, String> task = new AsyncTask<Account, String, String>() {
        ProgressDialog progressDlg;
        AsyncTask<Account, String, String> me = this;

        @Override
        protected void onPreExecute() {
            progressDlg = new ProgressDialog(ctx, ProgressDialog.STYLE_SPINNER);
            progressDlg.setMax(100);
            progressDlg.setTitle("Validating...");
            progressDlg.setMessage("Verifying the login data you entered...\n\nThis action will time out after 10 seconds.");
            progressDlg.setCancelable(false);
            progressDlg.setIndeterminate(false);
            progressDlg.setOnCancelListener(new android.content.DialogInterface.OnCancelListener() {
                public void onCancel(DialogInterface d) {
                    progressDlg.dismiss();
                    me.cancel(true);
                }
            });
            progressDlg.show();
        }

        @Override
        protected String doInBackground(Account... params) {
            return getAccessToken(params[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null) {
                // Wait for the extra intent
            } else {
                accountName = s;
                getDriveFiles();
            }
            progressDlg.dismiss();
        }
    };
    task.execute(account);
}

/**
 * Fetches the token from a particular Google account chosen by the user.  DO NOT RUN THIS DIRECTLY.  It must be run asynchronously inside an AsyncTask.
 * @param activity
 * @param account
 * @return
 */
private String getAccessToken(Account account) {
    try {
        return GoogleAuthUtil.getToken(ctx, account.name, "oauth2:" + DriveScopes.DRIVE);  // IMPORTANT: DriveScopes must be changed depending on what level of access you want
    } catch (UserRecoverableAuthException e) {
        // Start the Approval Screen intent, if not run from an Activity, add the Intent.FLAG_ACTIVITY_NEW_TASK flag.
        a.startActivityForResult(e.getIntent(), REQUEST_TOKEN);
        e.printStackTrace();
        return null;
    } catch (GoogleAuthException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

private Drive getDriveService() {
    mCredential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
    mCredential.setSelectedAccountName(accountName);
    return GDriveHelper.getDriveService(mCredential,getResources().getString(R.string.app_name));

}

/**
 * Obtains a list of all files on the signed-in user's Google Drive account.
 */
private void getDriveFiles() {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            Drive service = getDriveService();
            Log.d("SiteTrack", "FUNCTION getDriveFiles()");
            Files.List request;
            try {
                request = service.files().list(); // .setQ("mimeType=\"text/plain\"");
            } catch (IOException e) {


                e.printStackTrace();
                return;
            }
            do {
                FileList files;
                try {
                    System.out.println("got here");
                    Log.d("SiteTrack", request.toString());
                    //mCredential.setSelectedAccountName(accountName);
                    files = request.execute();

                } catch (IOException e) {
                    e.printStackTrace();
                    Log.d("SiteTrack", "Exception");
                    return;
                }
                ArrayList<File> fileList = (ArrayList<File>) files.getItems();
                Log.d("SiteTrack", "Files found: " + files.getItems().size());
                for (File f : fileList) {
                    String fileId = f.getId();
                    String title = f.getTitle();
                    Log.d("SiteTrack", "File " + fileId + ": " + title);
                }
                request.setPageToken(files.getNextPageToken());
            } while (request.getPageToken() != null && request.getPageToken().length() >= 0);
        }
    });
    t.start();

}

protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    if (requestCode == CHOOSE_ACCOUNT && resultCode == RESULT_OK) {
        accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
        GoogleAccountManager gam = new GoogleAccountManager(this);
        getAndUseAuthTokenInAsyncTask(gam.getAccountByName(accountName));
        Log.d("SiteTrack", "CHOOSE_ACCOUNT");
    } else if (requestCode == REQUEST_TOKEN && resultCode == RESULT_OK) {
        accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
        Log.d("SiteTrack", "REQUEST_TOKEN");
    }
}   
}

这会在 files = request.execute(); 上生成此跟踪;或任何 request.execute():

04-20 01:40:26.105: E/AndroidRuntime(27203): FATAL EXCEPTION: Thread-39033
04-20 01:40:26.105: E/AndroidRuntime(27203): java.lang.IllegalArgumentException: the name must not be empty: null
04-20 01:40:26.105: E/AndroidRuntime(27203):    at android.os.Parcel.readException(Parcel.java:1429)
04-20 01:40:26.105: E/AndroidRuntime(27203):    at android.os.Parcel.readException(Parcel.java:1379)
04-20 01:40:26.105: E/AndroidRuntime(27203):    at com.google.android.gms.internal.x$a$a.a(Unknown Source)
04-20 01:40:26.105: E/AndroidRuntime(27203):    at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
04-20 01:40:26.105: E/AndroidRuntime(27203):    at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
04-20 01:40:26.105: E/AndroidRuntime(27203):    at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential.getToken(GoogleAccountCredential.java:192)
04-20 01:40:26.105: E/AndroidRuntime(27203):    at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:217)
04-20 01:40:26.105: E/AndroidRuntime(27203):    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:888)
04-20 01:40:26.105: E/AndroidRuntime(27203):    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:407)
04-20 01:40:26.105: E/AndroidRuntime(27203):    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:340)
04-20 01:40:26.105: E/AndroidRuntime(27203):    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:458)
04-20 01:40:26.105: E/AndroidRuntime(27203):    at com.maiko.fool.Fool_5$3.run(Fool_5.java:184)
04-20 01:40:26.105: E/AndroidRuntime(27203):    at java.lang.Thread.run(Thread.java:856)

我对此感到迷茫,不知道可能出了什么问题。我已经按照本教程学习如何配置 Google API 服务:https://plus.google.com/u/0/114042449736049687152/posts/CD3L8zcJg5Z

感谢您的帮助。

最佳答案

验证您传递给“mCredential”对象的 var“accountName”。通常这就是这些错误的原因。 问候。

关于android - Android 上的 Google Drive 错误 : java. lang.IllegalArgumentException:名称不能为空:null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16115109/

有关android - Android 上的 Google Drive 错误 : java. lang.IllegalArgumentException:名称不能为空:null的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  3. ruby-on-rails - date_field_tag,如何设置默认日期? [ rails 上的 ruby ] - 2

    我想设置一个默认日期,例如实际日期,我该如何设置?还有如何在组合框中设置默认值顺便问一下,date_field_tag和date_field之间有什么区别? 最佳答案 试试这个:将默认日期作为第二个参数传递。youcorrectlysetthedefaultvalueofcomboboxasshowninyourquestion. 关于ruby-on-rails-date_field_tag,如何设置默认日期?[rails上的ruby],我们在StackOverflow上找到一个类似的问

  4. ruby-on-rails - openshift 上的 rails 控制台 - 2

    我将我的Rails应用程序部署到OpenShift,它运行良好,但我无法在生产服务器上运行“Rails控制台”。它给了我这个错误。我该如何解决这个问题?我尝试更新ruby​​gems,但它也给出了权限被拒绝的错误,我也无法做到。railsc错误:Warning:You'reusingRubygems1.8.24withSpring.UpgradetoatleastRubygems2.1.0andrun`gempristine--all`forbetterstartupperformance./opt/rh/ruby193/root/usr/share/rubygems/rubygems

  5. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  6. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  7. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  8. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  9. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  10. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

随机推荐