我正在編寫一個android應用程序,並且出現此錯誤。我評論的我的代碼幾乎每一個部分,並且仍然未發表意見的只有部分有以下幾種:嘗試調用空對象引用的方法
public class MainActivity extends AppCompatActivity {
int digi=0;
public PointCalculator pointCalculator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
digi = pointCalculator.digicalculator();
Toast.makeText(getApplicationContext(), digi, Toast.LENGTH_LONG).show();
}
和PointCalculator:
public int digicalculator()
{
int digipoints=0;
digipoints = digipoints + 30;
return digipoints;
}
,這是logcat的:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.neshat.test/com.example.neshat.test.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int com.example.neshat.test.PointCalculator.digicalculator()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int com.example.neshat.test.PointCalculator.digicalculator()' on a null object reference
at com.example.neshat.test.MainActivity.onCreate(MainActivity.java:18)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
我不明白是什麼原因造成的問題。
你在哪裏分配pointCalculator? – ajantha