0

Код фрагмента пустой. Есть только 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" >

&lt;TextView
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_margin=&quot;10dp&quot;
    android:gravity=&quot;center&quot;
    android:textSize=&quot;24sp&quot;
    android:text=&quot;@string/creating_a_new_file&quot; /&gt;

&lt;EditText
    android:id=&quot;@+id/editText&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_margin=&quot;10dp&quot;
    android:gravity=&quot;center&quot;
    android:hint=&quot;@string/enter_the_title&quot;
    android:importantForAutofill=&quot;no&quot;
    android:inputType=&quot;text&quot;
    android:minHeight=&quot;48dp&quot;
    android:textColorHint=&quot;#546E7A&quot; /&gt;

&lt;ImageView
    android:id=&quot;@+id/image0&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;150dp&quot;
    android:layout_margin=&quot;10dp&quot;
    android:scaleType=&quot;centerCrop&quot;
    android:adjustViewBounds=&quot;true&quot;
    android:contentDescription=&quot;@string/picture&quot;
    android:clickable=&quot;true&quot;
    android:focusable=&quot;true&quot;
    android:textAlignment=&quot;center&quot;
    android:src=&quot;@drawable/z&quot; /&gt;

&lt;Button
    android:id=&quot;@+id/button_creation&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_margin=&quot;10dp&quot;
    android:background=&quot;@color/colorPrimary&quot;
    android:text=&quot;@string/creation&quot;
    android:textColor=&quot;#5D4037&quot;
    android:visibility=&quot;visible&quot;/&gt;

</LinearLayout> </ScrollView>

Alice Magic
  • 1,066
  • Нужно уточнение в ваш вопрос, что означает "код не хочет работать"? Приложение падает? В логах ошибки есть? Приложите логи в вопрос. – Vadik Sirekanyan Aug 01 '22 at 17:17
  • Приложите в вопрос разметку XML, интересует та view, на которую вы кликаете. – Vadik Sirekanyan Aug 01 '22 at 17:34
  • view это кнопка Button, внутри нее нет никакого EditText, поэтому view.findViewById(R.id.editText) вернет null и далее происходит NPE – Vadik Sirekanyan Aug 01 '22 at 17:47
  • Теперь метод создает но с нулем. Не видит что в editText забито слово – Alice Magic Aug 01 '22 at 18:10
  • Задайте лучше новый вопрос. – Eugene Krivenja Aug 01 '22 at 20:12

1 Answers1

0

У вас в коде NullPointerException:

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

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

view.findViewById(R.id.editText)

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

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