startActivityForResult 处的 NullpointerException
NullpointerException at startActivityForResult
我目前正在尝试在 Android 上实施和使用 Google API for Java
。为了进行测试,我一直在关注两个示例 (CalendarSample
, TasksSample
)。调用 AccountManager
和其他内容的代码与两个示例中的相同。但是,以下代码对我不起作用并导致 NullPointerException
:
startActivityForResult(credential.newChooseAccountIntent(),2);
单击按钮后,我从普通 Activity
调用它,onCreate
已被调用。我已经尝试搜索 Google 和其他信息来源几个小时,但似乎没有任何效果。
清单:
<activity
android:name=".ManageAccounts"
android:label="@string/title_activity_manage_accounts"
android:launchMode="singleTop"
android:parentActivityName=".SettingsActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
这里是完整的 activity:
public class ManageAccounts extends Activity implements GoogleLoginFragment.OnSignedIn{
DataHandler dataHandler;
//for testing of google add friend
private static final String PREF_ACCOUNT_NAME = "accountName";
Circles service;
final HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
static final int REQUEST_GOOGLE_PLAY_SERVICES = 0;
static final int REQUEST_AUTHORIZATION = 1;
static final int REQUEST_ACCOUNT_PICKER = 2;
GoogleAccountCredential credential;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_accounts);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
dataHandler = new DataHandler(this);
//Add GoogleLoginFragment
GoogleLoginFragment.attachToActivity(this);
//testing of google add friend code
GoogleAccountCredential credential =
GoogleAccountCredential.usingOAuth2(this, Collections.singleton(CirclesScopes.CIRCLE_ADD +" "+ CirclesScopes.CIRCLES));
SharedPreferences settings = this.getPreferences(Context.MODE_PRIVATE);
credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
service =
new Circles.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("Social Contacts/1.0").build();
Log.i("Activity","onCreateDone");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.manage_accounts, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Request Code for Twitter button: 140
if (requestCode == 140) {
loginButton.onActivityResult(requestCode, resultCode, data);
}
switch (requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode == Activity.RESULT_OK) {
haveGooglePlayServices();
} else {
checkGooglePlayServicesAvailable();
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
// AsyncLoadTasks.run(this);
} else {
chooseAccount();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.commit();
// AsyncLoadTasks.run(this);
}
}
break;
}
}
public void onSignedIn(GoogleApiClient googleApiClient) {
GoogleSocialActions gsa = new GoogleSocialActions(googleApiClient, dataHandler, this);
gsa.saveAuthenticatedUser();
}
/** Check that Google Play services APK is installed and up to date. */
private boolean checkGooglePlayServicesAvailable() {
final int connectionStatusCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
return false;
}
return true;
}
void showGooglePlayServicesAvailabilityErrorDialog(final int connectionStatusCode) {
runOnUiThread(new Runnable() {
public void run() {
Dialog dialog =
GooglePlayServicesUtil.getErrorDialog(connectionStatusCode, ManageAccounts.this,
REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
});
}
private void haveGooglePlayServices() {
// check if there is already an account selected
if (credential.getSelectedAccountName() == null) {
// ask user to choose account
chooseAccount();
} else {
// load calendars
// AsyncLoadTasks.run(this);
}
}
private void chooseAccount() {
startActivityForResult(credential.newChooseAccountIntent(), 2);
}
public void chooser(View view) {
if (view.getId() == R.id.chooser) {
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
}
}
Stacktrace如下。第 204 行的 NullPointer
就是上面显示的那一行。
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View.onClick(View.java:3602)
at android.view.View.performClick(View.java:4095)
at android.view.View$PerformClick.run(View.java:17078)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View.onClick(View.java:3597)
at android.view.View.performClick(View.java:4095)
at android.view.View$PerformClick.run(View.java:17078)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.martin.contacts.ManageAccounts.chooser(ManageAccounts.java:204)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View.onClick(View.java:3597)
at android.view.View.performClick(View.java:4095)
at android.view.View$PerformClick.run(View.java:17078)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
您是否从 credential.newChooseAccountIntent()
那里得到任何意图??您的堆栈跟踪表明您没有获得任何意图,因此无法调用 startActivityForResult()。
更新答案
您有 GoogleAccountCredential credential;
作为实例成员。但是你还没有初始化这个成员。
在你的 onCreate 中,你已经声明了另一个本地 credential
但你的成员 credential
从未正确初始化,这是你有问题的行 -
//testing of google add friend code
GoogleAccountCredential credential =
GoogleAccountCredential.usingOAuth2(this, Collections.singleton(CirclesScopes.CIRCLE_ADD +" "+ CirclesScopes.CIRCLES));
你应该只写
//testing of google add friend code
credential =GoogleAccountCredential.usingOAuth2(this, Collections.singleton(CirclesScopes.CIRCLE_ADD +" "+ CirclesScopes.CIRCLES));
我目前正在尝试在 Android 上实施和使用 Google API for Java
。为了进行测试,我一直在关注两个示例 (CalendarSample
, TasksSample
)。调用 AccountManager
和其他内容的代码与两个示例中的相同。但是,以下代码对我不起作用并导致 NullPointerException
:
startActivityForResult(credential.newChooseAccountIntent(),2);
单击按钮后,我从普通 Activity
调用它,onCreate
已被调用。我已经尝试搜索 Google 和其他信息来源几个小时,但似乎没有任何效果。
清单:
<activity
android:name=".ManageAccounts"
android:label="@string/title_activity_manage_accounts"
android:launchMode="singleTop"
android:parentActivityName=".SettingsActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
这里是完整的 activity:
public class ManageAccounts extends Activity implements GoogleLoginFragment.OnSignedIn{
DataHandler dataHandler;
//for testing of google add friend
private static final String PREF_ACCOUNT_NAME = "accountName";
Circles service;
final HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
static final int REQUEST_GOOGLE_PLAY_SERVICES = 0;
static final int REQUEST_AUTHORIZATION = 1;
static final int REQUEST_ACCOUNT_PICKER = 2;
GoogleAccountCredential credential;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_accounts);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
dataHandler = new DataHandler(this);
//Add GoogleLoginFragment
GoogleLoginFragment.attachToActivity(this);
//testing of google add friend code
GoogleAccountCredential credential =
GoogleAccountCredential.usingOAuth2(this, Collections.singleton(CirclesScopes.CIRCLE_ADD +" "+ CirclesScopes.CIRCLES));
SharedPreferences settings = this.getPreferences(Context.MODE_PRIVATE);
credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
service =
new Circles.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("Social Contacts/1.0").build();
Log.i("Activity","onCreateDone");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.manage_accounts, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Request Code for Twitter button: 140
if (requestCode == 140) {
loginButton.onActivityResult(requestCode, resultCode, data);
}
switch (requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode == Activity.RESULT_OK) {
haveGooglePlayServices();
} else {
checkGooglePlayServicesAvailable();
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
// AsyncLoadTasks.run(this);
} else {
chooseAccount();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.commit();
// AsyncLoadTasks.run(this);
}
}
break;
}
}
public void onSignedIn(GoogleApiClient googleApiClient) {
GoogleSocialActions gsa = new GoogleSocialActions(googleApiClient, dataHandler, this);
gsa.saveAuthenticatedUser();
}
/** Check that Google Play services APK is installed and up to date. */
private boolean checkGooglePlayServicesAvailable() {
final int connectionStatusCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
return false;
}
return true;
}
void showGooglePlayServicesAvailabilityErrorDialog(final int connectionStatusCode) {
runOnUiThread(new Runnable() {
public void run() {
Dialog dialog =
GooglePlayServicesUtil.getErrorDialog(connectionStatusCode, ManageAccounts.this,
REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
});
}
private void haveGooglePlayServices() {
// check if there is already an account selected
if (credential.getSelectedAccountName() == null) {
// ask user to choose account
chooseAccount();
} else {
// load calendars
// AsyncLoadTasks.run(this);
}
}
private void chooseAccount() {
startActivityForResult(credential.newChooseAccountIntent(), 2);
}
public void chooser(View view) {
if (view.getId() == R.id.chooser) {
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
}
}
Stacktrace如下。第 204 行的 NullPointer
就是上面显示的那一行。
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View.onClick(View.java:3602)
at android.view.View.performClick(View.java:4095)
at android.view.View$PerformClick.run(View.java:17078)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View.onClick(View.java:3597)
at android.view.View.performClick(View.java:4095)
at android.view.View$PerformClick.run(View.java:17078)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.martin.contacts.ManageAccounts.chooser(ManageAccounts.java:204)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View.onClick(View.java:3597)
at android.view.View.performClick(View.java:4095)
at android.view.View$PerformClick.run(View.java:17078)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
您是否从 credential.newChooseAccountIntent()
那里得到任何意图??您的堆栈跟踪表明您没有获得任何意图,因此无法调用 startActivityForResult()。
更新答案
您有 GoogleAccountCredential credential;
作为实例成员。但是你还没有初始化这个成员。
在你的 onCreate 中,你已经声明了另一个本地 credential
但你的成员 credential
从未正确初始化,这是你有问题的行 -
//testing of google add friend code
GoogleAccountCredential credential =
GoogleAccountCredential.usingOAuth2(this, Collections.singleton(CirclesScopes.CIRCLE_ADD +" "+ CirclesScopes.CIRCLES));
你应该只写
//testing of google add friend code
credential =GoogleAccountCredential.usingOAuth2(this, Collections.singleton(CirclesScopes.CIRCLE_ADD +" "+ CirclesScopes.CIRCLES));