0

Имеется код:

package asus.example.com.fitnessapp;



import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Date;


/**
 * A simple {@link Fragment} subclass.
 */
public class IndicationsFragment extends Fragment {
    private EditText pulse;
    private Button save;
    private final String LOG_TAG = "myLogs";
    private DBHelper dbHelper;
    private int iPulse, iDate, iMonth, iYear;
    public IndicationsFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_indications, container, false);
        pulse = view.findViewById(R.id.pulse);
        save = view.findViewById(R.id.save);
        final Date date = new Date();
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    iPulse = Integer.parseInt(pulse.getText().toString());
                    iDate = date.getDate();
                    iMonth = date.getMonth()+1;
                    iYear = date.getYear()+1900;
                    ContentValues cv = new ContentValues();
                    SQLiteDatabase db = dbHelper.getWritableDatabase();
                    cv.put("pulse", iPulse);
                    cv.put("date", iDate);
                    cv.put("month", iMonth);
                    cv.put("year", iYear);
                    long rowID = db.insert("myTable", null,cv);
                    Log.d(LOG_TAG, "Row inserted, ID = "+rowID);
                    Toast.makeText(getContext(), "Information saved", Toast.LENGTH_LONG).show();
                }catch (NumberFormatException e){
                    Toast.makeText(getContext(),"Wrong input!", Toast.LENGTH_SHORT).show();
                }


            }
        });
        return view;
    }

    public class DBHelper extends SQLiteOpenHelper {

        public DBHelper(Context context){
            super(context,"myDB", null, 1);

        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.d(LOG_TAG, "onCreate Database");
            db.execSQL("Create table myTable ("+"id integer primary key autoincrement,"+"integer pulse,"+"integer date,"+"integer month,"+"integer year"+");");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }
    }


}

При выполнении выдает ошибку:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase asus.example.com.fitnessapp.IndicationsFragment$DBHelper.getWritableDatabase()' on a null object reference at asus.example.com.fitnessapp.IndicationsFragment$1.onClick(IndicationsFragment.java:53) at android.view.View.performClick(View.java:5340) at android.view.View$PerformClick.run(View.java:21610) at android.os.Handler.handleCallback(Handler.java:815) at android.os.Handler.dispatchMessage(Handler.java:104) at android.os.Looper.loop(Looper.java:207) at android.app.ActivityThread.main(ActivityThread.java:5763) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

Не понимаю, в чем ошибка. Вроде и названия столбцов правильно прописаны, и переменные не нулевые

1 ответ 1

4

У вас не создан экземпляр DBHelper. Создайте его:

 dbHelper = new DBHelper(getActivity());

до вызова SQLiteDatabase db = dbHelper.getWritableDatabase();

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.