1

В приложении я использую FloatingActionButton и после его нажатия открывается диалоговое окно, куда я буду вводить данные. Обработчик нажатия для FloatingActionButton работает нормально, но обработчик для другой кнопки в диалоговом окне выбрасывает NullPointerException. Само диалоговое окно открывается нормально с полями для ввода, но еще до нажатия кнопки в диалоговом окне обрабатывается catch блок. Почему у меня возникает это исключение? Для ясности дела привожу код MainActivity и Subjects, а также разметку для главного окна и диалогового.

UPD #1 Переместил обработчик для addSubjectDialogButton просто в метод onCreate, запустил без блоков try-catch. Приложение даже не открылось нормально и получил такие ошибки:

 07-29 13:10:02.713  21457-21457/com.kostyabakay.scholarship E/AndroidRuntime﹕ FATAL EXCEPTION: main
            java.lang.RuntimeException: Unable to start activity ComponentInfo{com.kostyabakay.scholarship/com.kostyabakay.scholarship.MainActivity}: java.lang.NullPointerException
                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
                    at android.app.ActivityThread.access$600(ActivityThread.java:162)
                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
                    at android.os.Handler.dispatchMessage(Handler.java:107)
                    at android.os.Looper.loop(Looper.java:194)
                    at android.app.ActivityThread.main(ActivityThread.java:5371)
                    at java.lang.reflect.Method.invokeNative(Native Method)
                    at java.lang.reflect.Method.invoke(Method.java:525)
                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                    at dalvik.system.NativeStart.main(Native Method)
             Caused by: java.lang.NullPointerException
                    at com.kostyabakay.scholarship.MainActivity.onCreate(MainActivity.java:108)
                    at android.app.Activity.performCreate(Activity.java:5122)
                    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
                    at android.app.ActivityThread.access$600(ActivityThread.java:162)
                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
                    at android.os.Handler.dispatchMessage(Handler.java:107)
                    at android.os.Looper.loop(Looper.java:194)
                    at android.app.ActivityThread.main(ActivityThread.java:5371)
                    at java.lang.reflect.Method.invokeNative(Native Method)
                    at java.lang.reflect.Method.invoke(Method.java:525)
                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                    at dalvik.system.NativeStart.main(Native Method)

Код MainActivity.class

package com.kostyabakay.scholarship;

import android.app.Dialog;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.getbase.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class MainActivity extends ActionBarActivity {

    private ListView listView;
    ArrayList<Subjects> subjectsList; //LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
    ArrayAdapter<Subjects> adapter; //DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LIST VIEW
    FloatingActionButton addSubjectButton;
    Button addSubjectDialogButton;
    Dialog dialog;
    TextView averageTextView; // временное

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        averageTextView = (TextView) findViewById(R.id.averageTextView); // временное

        subjectsList = new ArrayList<Subjects>();
        listView = (ListView) findViewById(R.id.listView);
        adapter = new ArrayAdapter<Subjects>(this, android.R.layout.simple_list_item_1, subjectsList);
        listView.setAdapter(adapter);

        // Создание диалога для ввода данных про предмет
        dialog = new Dialog(MainActivity.this);
        dialog.setTitle("Додавання предмету"); // Установите заголовок
        dialog.setContentView(R.layout.subject_dialog); // Передайте ссылку на разметку

        addSubjectButton = (FloatingActionButton) findViewById(R.id.addSubjectButton);

        TextView enterSubjectInfo = (TextView) dialog.findViewById(R.id.enterSubjectInfoView);
        enterSubjectInfo.setText("Назва предмету");

        final EditText enterSubject = (EditText) dialog.findViewById(R.id.enterSubjectView);

        TextView enterCoefficientInfo = (TextView) dialog.findViewById(R.id.enterCoefficientInfoView);
        enterCoefficientInfo.setText("Коефіцієнт");

        final EditText enterCoefficient = (EditText) dialog.findViewById(R.id.enterCoefficientView);

        TextView enterGradeInfo = (TextView) dialog.findViewById(R.id.enterGradeInfoView);
        enterGradeInfo.setText("Оцінка");

        final EditText enterGrade = (EditText) dialog.findViewById(R.id.enterGradeView);

        addSubjectDialogButton = (Button) findViewById(R.id.addSubjectDialogButton);

        addSubjectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                   
                dialog.show(); // Выводим диалоговое окно на экран
            }
        });

        // NULL POINTER EXCEPTION!!!!!!
        try {
            addSubjectDialogButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    enterSubject.setText("good");
                }
            });
        } catch (NullPointerException ex) {
            enterSubject.setText("bad");
        }

    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                Toast.makeText(getApplicationContext(),
                        "А нет никаких еще настроек :Р", Toast.LENGTH_LONG).show();
                return true;

            case R.id.author:
                Toast.makeText(getApplicationContext(),
                        "Костя Бакай", Toast.LENGTH_LONG).show();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Код Subjects.class

public class Subjects {
    private String subject;
    private double coefficient;
    private double grade;

    public String toString(){
        return "Предмет: " + subject + ". Коефіцієнт: " + coefficient + " Оцінка: " + grade;
    }

    public Subjects(String subject, double coefficient, double grade) {
        this.subject = subject;
        this.coefficient = coefficient;
        this.grade = grade;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public double getCoefficient() {
        return coefficient;
    }

    public void setCoefficient(double coefficient) {
        this.coefficient = coefficient;
    }

    public double getGrade() {
        return grade;
    }

    public void setGrade(double grade) {
        this.grade = grade;
    }
}

Разметка activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <TextView
        android:id="@+id/averageTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:layout_gravity="bottom|left"
        />

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:drawSelectorOnTop="false"
        />

    <com.getbase.floatingactionbutton.FloatingActionsMenu
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:id="@+id/multiple_actions"
        android:layout_margin="16dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        fab:fab_addButtonColorNormal="#009688"
        fab:fab_addButtonColorPressed="#4DB6AC"
        fab:fab_addButtonPlusIconColor="#FFFFFF"
        fab:fab_labelStyle="@style/menu_labels_style"
        >

        <com.getbase.floatingactionbutton.FloatingActionButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/action_b"
            fab:fab_colorNormal="#009688"
            fab:fab_colorPressed="#4DB6AC"
            fab:fab_icon="@drawable/ic_assessment_white_24dp"
            fab:fab_size="normal"
            fab:fab_title="Порахувати"
            />

        <com.getbase.floatingactionbutton.FloatingActionButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/addSubjectButton"
            fab:fab_colorNormal="#009688"
            fab:fab_colorPressed="#4DB6AC"
            fab:fab_icon="@drawable/ic_create_white_24dp"
            fab:fab_size="normal"
            fab:fab_title="Додати предмет"
            />

    </com.getbase.floatingactionbutton.FloatingActionsMenu>

</FrameLayout>

Разметка диалогового окна subject_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/subjectDialogView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/enterSubjectInfoView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/enterSubjectView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/enterCoefficientInfoView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/enterCoefficientView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/enterGradeInfoView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/enterGradeView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:textStyle="bold" />

    <Button
        android:id="@+id/addSubjectDialogButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Додати" />

    />

</LinearLayout>
12
  • 2
    для начала скопируйте сюда текст ошибки. То что вам выдает ваша IDE. Скажите, а почему событие на клик addSubjectDialogButton вы обворачиваете в блок и помещаете этот блок в другое событие клика? Это не правильно. 29 июл 2015 в 3:40
  • 1
    Для того, чтобы на вопрос можно было ответить, добавьте весь относящийся к проблеме код и сообщения об ошибках в сам вопрос. Как задавать вопросы, как создать краткий, завершенный и достоверный пример.
    – Nick Volynkin
    29 июл 2015 в 5:32
  • 1
    addSubjectDialogButton принадлежит диалогу или он лежит в разметке активити? 29 июл 2015 в 7:58
  • 1
    Тогда вам надо после dialog.setcontentView(), а не до этой строки объявить кнопку addSubjectDialogButton = (Button) dialog.findViewById(R.id.addSubjectDialogButton). По идее должно помочь 29 июл 2015 в 11:57
  • 1
    addSubjectDialogButton = (Button) findViewById(R.id.addSubjectDialogButton); замените на addSubjectDialogButton = (Button) dialog.findViewById(R.id.addSubjectDialogButton); Я же уже писал об этом 29 июл 2015 в 13:08

1 ответ 1

0

Пользователь подсказал в комментариях правильный ответ.

Нужно заменить

addSubjectDialogButton = (Button) findViewById(R.id.addSubjectDialogButton); 

на

addSubjectDialogButton = (Button) dialog.findViewById(R.id.addSubjectDialogButton); 

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.