我想选择一个联系人,并使用onActivityResult将该号码显示为Toast Message。 我的问题是在我选择了一个联系人并希望显示我的程序崩溃的数字之后。
以下是代码:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACT) {
if (resultCode == RESULT_OK) {
Uri contactUri = data.getData();
String[] projection = { Phone.NUMBER };
Cursor cursor = getContentResolver().query(contactUri,
projection, null, null, null);
cursor.moveToFirst();
int column = cursor.getColumnIndex(Phone.NUMBER);
String number = cursor.getString(column);
// Should Display the number as Toast
Toast.makeText(null, number, Toast.LENGTH_SHORT).show();
}
}
}
和StackTrace
05-20 16:48:31.990: E/AndroidRuntime(9222): FATAL EXCEPTION: main
05-20 16:48:31.990: E/AndroidRuntime(9222): Process: com.alphabuddy.test, PID: 9222
05-20 16:48:31.990: E/AndroidRuntime(9222): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content: (has extras) }} to activity {com.alphabuddy.test/com.alphabuddy.test.Satabase}: java.lang.NullPointerException
05-20 16:48:31.990: E/AndroidRuntime(9222): at android.app.ActivityThread.deliverResults(ActivityThread.java)
05-20 16:48:31.990: E/AndroidRuntime(9222): at android.app.ActivityThread.handleSendResult(ActivityThread.java)
05-20 16:48:31.990: E/AndroidRuntime(9222): at android.app.ActivityThread.access$1300(ActivityThread.java)
05-20 16:48:31.990: E/AndroidRuntime(9222): at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
05-20 16:48:31.990: E/AndroidRuntime(9222): at android.os.Handler.dispatchMessage(Handler.java)
05-20 16:48:31.990: E/AndroidRuntime(9222): at android.os.Looper.loop(Looper.java)
05-20 16:48:31.990: E/AndroidRuntime(9222): at android.app.ActivityThread.main(ActivityThread.java)
05-20 16:48:31.990: E/AndroidRuntime(9222): at java.lang.reflect.Method.invokeNative(Native Method)
05-20 16:48:31.990: E/AndroidRuntime(9222): at java.lang.reflect.Method.invoke(Method.java)
05-20 16:48:31.990: E/AndroidRuntime(9222): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
05-20 16:48:31.990: E/AndroidRuntime(9222): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
05-20 16:48:31.990: E/AndroidRuntime(9222): at dalvik.system.NativeStart.main(Native Method)
05-20 16:48:31.990: E/AndroidRuntime(9222): Caused by: java.lang.NullPointerException
05-20 16:48:31.990: E/AndroidRuntime(9222): at android.widget.Toast.<init>(Toast.java)
05-20 16:48:31.990: E/AndroidRuntime(9222): at android.widget.Toast.makeText(Toast.java)
05-20 16:48:31.990: E/AndroidRuntime(9222): at com.alphabuddy.test.Satabase.onActivityResult(Satabase.java:72)
05-20 16:48:31.990: E/AndroidRuntime(9222): at android.app.Activity.dispatchActivityResult(Activity.java)
05-20 16:48:31.990: E/AndroidRuntime(9222): ... 12 more
答案 0 :(得分:1)
而不是
Toast.makeText(null, number, Toast.LENGTH_SHORT).show();
使用
Toast.makeText(getApplicationContext(), ""+number, Toast.LENGTH_SHORT).show();