【发布时间】:2018-07-21 22:18:22
【问题描述】:
我对编程非常陌生,因此非常感谢您的帮助,这是我第一次在这里寻求帮助,希望我做得对。
我正在尝试在应用程序中创建一个简单的笔记记录部分,但出现以下错误:
Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
代码如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
et_memo = (EditText) findViewById(R.id.et_memo);
b_clear = (Button) findViewById(R.id.b_clear);
b_save = (Button) findViewById(R.id.b_save);
SharedPreferences preferences = getSharedPreferences("PREFS", 0);
memo = preferences.getString("memo","");
et_memo.setText(memo);
b_clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
memo ="";
et_memo.setText(memo);
}
});
b_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
memo = et_memo.getText().toString();
SharedPreferences preferences = getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("memo", memo);
editor.commit();
Toast.makeText(MainActivity.this, "Note saved!",
Toast.LENGTH_SHORT).show();
这是我的 XML 文件:
<android.support.v7.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
android:inputType="textNoSuggestions"
android:textSize="16sp"
android:textColor="@color/black"
android:id="@+id/et_memo"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="CLEAR"
android:id="@+id/b_clear"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="SAVE"
android:id="@+id/b_save"/>
</LinearLayout>
</android.support.v7.widget.LinearLayoutCompat>`
【问题讨论】:
-
嗨 Rikits。您能否确认帖子中显示的 XML 文件在您的项目中被称为:“activity_main.xml”?谢谢。
-
错误信息应该告诉你它来自哪一行。请指出它在您发布的代码中的哪一行。
-
是的,这是正确的 Elltlar。它被称为 Activity_main。 @TylerV - 错误信息指向以下行 --> et_memo.setText(memo);
标签: java android android-layout android-edittext