我正在编写一个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