0

Я решил в Android Studio сделать приложение-календарь и добавить туда заметки, но при нажатии кнопки "ОК" в диалоге сохранения заметки, приложение вылетает со следующей ошибкой: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

Код activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
&lt;Button
    android:id=&quot;@+id/notes&quot;
    android:layout_width=&quot;92dp&quot;
    android:layout_height=&quot;57dp&quot;
    android:layout_marginStart=&quot;149dp&quot;
    android:layout_marginLeft=&quot;149dp&quot;
    android:layout_marginTop=&quot;376dp&quot;
    android:layout_marginEnd=&quot;150dp&quot;
    android:layout_marginRight=&quot;150dp&quot;
    android:layout_marginBottom=&quot;162dp&quot;
    android:text=&quot;@string/Notes&quot;

    app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
    app:layout_constraintEnd_toEndOf=&quot;parent&quot;
    app:layout_constraintStart_toStartOf=&quot;parent&quot;
    app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;

&lt;RelativeLayout
    android:layout_width=&quot;409dp&quot;
    android:layout_height=&quot;729dp&quot;
    android:layout_marginStart=&quot;1dp&quot;
    android:layout_marginLeft=&quot;1dp&quot;
    android:layout_marginTop=&quot;1dp&quot;
    android:layout_marginEnd=&quot;1dp&quot;
    android:layout_marginRight=&quot;1dp&quot;
    android:layout_marginBottom=&quot;1dp&quot;
    app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
    app:layout_constraintEnd_toEndOf=&quot;parent&quot;
    app:layout_constraintHorizontal_bias=&quot;0.0&quot;
    app:layout_constraintStart_toStartOf=&quot;parent&quot;
    app:layout_constraintTop_toTopOf=&quot;parent&quot;&gt;

    &lt;com.google.android.gms.ads.AdView
        android:id=&quot;@+id/adView&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_alignParentBottom=&quot;true&quot;
        android:layout_centerHorizontal=&quot;true&quot;
        android:layout_marginBottom=&quot;106dp&quot;
        app:adSize=&quot;BANNER&quot;
        app:adUnitId=&quot;ca-app-pub-3940256099942544/6300978111&quot;&gt;

    &lt;/com.google.android.gms.ads.AdView&gt;


&lt;/RelativeLayout&gt;

&lt;CalendarView
    android:id=&quot;@+id/calendarView2&quot;
    android:layout_width=&quot;296dp&quot;
    android:layout_height=&quot;298dp&quot;
    android:layout_marginStart=&quot;54dp&quot;
    android:layout_marginLeft=&quot;54dp&quot;
    android:layout_marginTop=&quot;20dp&quot;
    android:layout_marginEnd=&quot;61dp&quot;
    android:layout_marginRight=&quot;61dp&quot;
    android:layout_marginBottom=&quot;275dp&quot;
    app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
    app:layout_constraintEnd_toEndOf=&quot;parent&quot;
    app:layout_constraintStart_toStartOf=&quot;parent&quot;
    app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;

</androidx.constraintlayout.widget.ConstraintLayout>

Код MainActivity.java:

public class MainActivity extends AppCompatActivity implements OnClickListener {
    Button notes;
public AdView mAdView;


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    notes = (Button) findViewById(R.id.notes);
    notes.setOnClickListener(this);

    MobileAds.initialize(this, new OnInitializationCompleteListener() {
        @Override
        public void onInitializationComplete(InitializationStatus initializationStatus) {
        }
    });
    mAdView = findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);
}


public void onClick(View v) {
    switch (v.getId()) {
        case R.id.notes:
            Intent intent = new Intent(this, Notes.class);
            startActivity(intent);

            break;
        default:
            break;
    }
}

}

Код activity_notes.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="Notes">
    &lt;ImageButton
        android:id=&quot;@+id/imageButton3&quot;
        android:layout_width=&quot;83dp&quot;
        android:layout_height=&quot;73dp&quot;
        android:layout_marginStart=&quot;1dp&quot;
        android:layout_marginLeft=&quot;1dp&quot;
        android:layout_marginBottom=&quot;5dp&quot;
        android:contentDescription=&quot;@string/addnote&quot;

        android:onClick=&quot;addnote&quot;
        android:src=&quot;@android:drawable/ic_input_add&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        tools:ignore=&quot;ImageContrastCheck&quot; /&gt;

    &lt;LinearLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_marginTop=&quot;279dp&quot;
        android:layout_marginBottom=&quot;324dp&quot;
        android:orientation=&quot;vertical&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot;&gt;

        &lt;TextView
            android:id=&quot;@+id/final_text&quot;
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;wrap_content&quot; /&gt;
    &lt;/LinearLayout&gt;

    &lt;TextView
        android:id=&quot;@+id/notesView&quot;
        android:layout_width=&quot;410dp&quot;
        android:layout_height=&quot;468dp&quot;
        android:text=&quot;&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;

    &lt;Button
        android:id=&quot;@+id/readnotes&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_marginStart=&quot;158dp&quot;
        android:layout_marginLeft=&quot;158dp&quot;
        android:layout_marginTop=&quot;476dp&quot;
        android:layout_marginEnd=&quot;124dp&quot;
        android:layout_marginRight=&quot;124dp&quot;
        android:layout_marginBottom=&quot;79dp&quot;
        android:onClick=&quot;onClickGet&quot;
        android:text=&quot;@string/Open_notes&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;

&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

Код Notes.java:

public class Notes extends AppCompatActivity {
final Context context = this;
public ImageButton button;
public TextView final_text;
public SharedPreferences pref;
public EditText input_text;
public TextView notesView;
public final String save_key = &quot;save note&quot;;





public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_notes);
    notesView = (TextView)findViewById(R.id.notesView);
    button = findViewById(R.id.imageButton3);
    final_text =  findViewById(R.id.final_text);

    init();}

public void init(){
    pref = getSharedPreferences( &quot;note&quot;,MODE_PRIVATE);
    input_text = findViewById (R.id.input_text);
    notesView.setText(pref.getString(save_key,&quot;You haven`t got any note&quot;));

}





    public void addnote(View arg0) {

        LayoutInflater li = LayoutInflater.from(context);
        View promptsView = li.inflate(R.layout.prompt, null);

        //Создаем AlertDialog
        AlertDialog.Builder mDialogBuilder = new AlertDialog.Builder(context);

        //Настраиваем prompt.xml для нашего AlertDialog:
        mDialogBuilder.setView(promptsView);

        //Настраиваем отображение поля для ввода текста в открытом диалоге:
        final EditText userInput = promptsView.findViewById(R.id.input_text);

        //Настраиваем сообщение в диалоговом окне:
        mDialogBuilder
                .setCancelable(false)
                .setPositiveButton(&quot;OK&quot;,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {

                                final_text.setText(userInput.getText());
                                SharedPreferences.Editor edit = pref.edit();
                                edit.putString(save_key,input_text.getText().toString());
                                edit.apply();
                            }
                        })
                .setNegativeButton(&quot;Cancel&quot;,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                dialog.cancel();
                            }
                        });

        //Создаем AlertDialog:
        AlertDialog alertDialog = mDialogBuilder.create();

        //и отображаем его:
        alertDialog.show();
        }

public void onClickGet (View view){
    notesView.setText(pref.getString(save_key, defValue: &quot;You haven`t got any note&quot;));
}

}

Код promt.xml:

?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dp" >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/write_the_note"
        android:textAppearance="?android:attr/textAppearanceLarge" />
&lt;EditText
    android:id=&quot;@+id/input_text&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;wrap_content&quot;
    &gt;

    &lt;requestFocus /&gt;
&lt;/EditText&gt;

</LinearLayout>

Помогите мне пожалуйста с этой ошибкой.

Andrew
  • 17,943
  • А вы посмотрите внимательно: к какому EditText вы обращаетесь в обработчике кнопки "ОК" и какое значение присвоено этой ссылке. – woesss Oct 08 '21 at 07:03
  • вы в активности Notes ставите разметку R.layout.activity_notes а пытаетесь найти элементы с другой разметки – Style-7 Oct 08 '21 at 11:37

0 Answers0