我一直在試圖解決這個空指針異常,但我不能。我知道它指向一個空對象,但我不知道如何解決它。我是Java編程的初學者,所以如果這是一個愚蠢的問題,請不要生氣。我如何解決我的空指針異常
這裏是我的代碼:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
public ArrayAdapter<String> itemsAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//EditText
final EditText etTask = (EditText) findViewById(R.id.editText);
final String Task = etTask.getText().toString();
//Button
Button btn = (Button) findViewById(R.id.button);
//Null Fix
//OnClickListeners
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemsAdapter.add(Task);
etTask.setText("");
}
});
}
}
這裏是我的logcat:
09-04 06:58:32.704 16735-16735/com.example.elias.doit E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.elias.doit, PID: 16735
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ArrayAdapter.add(java.lang.Object)' on a null object reference
at com.example.elias.doit.MainActivity$1.onClick(MainActivity.java:38)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-04 06:58:40.564 16735-16735/? I/Process﹕ Sending signal. PID: 16735 SIG: 9
刪除'itemsAdapter.add(任務);' – Blackbelt
是什麼'Task'這裏'itemsAdapter.add(任務);' – Rustam
Initilaize您通過 itemsAdapter =新ArrayAdapter(這一點, 機器人itemsAdapter適配器。 R.layout.simple_list_item_1,values); –