Не работает метод по вставке строк в БД

Код фрагмента пустой. Есть только onClick метод который должен вставлять строку в проект. Но он не хочет работать.

@Override
public void onClick(View view) {

    ContentValues xValues = new ContentValues();
    xValues.put("TEXT0", "");

    EditText name = view.findViewById(R.id.editText);

    // Без этой строки все работает нормально
    xValues.put("TEXT0", String.valueOf(name.getText()));

    SQLiteOpenHelper marigoldDatabaseHelper = new ZA_MarigoldDatabaseHelper(getActivity());
    try {
        SQLiteDatabase db = marigoldDatabaseHelper.getWritableDatabase();
        db.insert("MANICURE", null, xValues);
        Toast toast = Toast.makeText(getActivity(),
                "Сохранено",
                Toast.LENGTH_SHORT);
        toast.show();
        db.close();
    } catch(SQLiteException e) {
        Toast toast = Toast.makeText(getActivity(),
                "База данных недоступна",
                Toast.LENGTH_SHORT);
        toast.show();
    }
}

Без 4-ой строки все работает как надо. Но именно она мне и нужна... Подскажите кому не сложно

Есть у меня это:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ZK_CreationFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center"
        android:textSize="24sp"
        android:text="@string/creating_a_new_file" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center"
        android:hint="@string/enter_the_title"
        android:importantForAutofill="no"
        android:inputType="text"
        android:minHeight="48dp"
        android:textColorHint="#546E7A" />

    <ImageView
        android:id="@+id/image0"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_margin="10dp"
        android:scaleType="centerCrop"
        android:adjustViewBounds="true"
        android:contentDescription="@string/picture"
        android:clickable="true"
        android:focusable="true"
        android:textAlignment="center"
        android:src="@drawable/z" />

    <Button
        android:id="@+id/button_creation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="@color/colorPrimary"
        android:text="@string/creation"
        android:textColor="#5D4037"
        android:visibility="visible"/>

</LinearLayout>
</ScrollView>

Ответы (1 шт):

Автор решения: Vadik

У вас в коде NullPointerException:

Attempt to invoke virtual method 'getText()' on a null object reference

Ошибка происходит из-за того, что аргументом метода onClick является view, которая является кнопкой Button. Далее вы вызываете

view.findViewById(R.id.editText)

У кнопки в иерархии нет вложенного EditText, поэтому такой вызов вернет null, из-за чего впоследствии произойдет ошибка NPE.

Попробуйте вынести вызов findViewById() на уровень выше, во фрагмент или активити.

→ Ссылка