0

Имеется код:

package asus.example.com.fitnessapp;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
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.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


/**
 * A simple {@link Fragment} subclass.
 */
public class IndicationsFragment extends Fragment {
    private EditText pulse;
    private Button save;
    private TextView textView;
    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();
        dbHelper = new DBHelper(getActivity());
        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();

                    Log.d(LOG_TAG, "--- Rows in myTable: ---");
                    Cursor cursor = db.query("myTable",null,null,null,null,null,null);

                    if (cursor.moveToFirst()){
                        int idColIndex = cursor.getColumnIndex("id");
                        int idColPulse = cursor.getColumnIndex("pulse");
                        int dateColIndex = cursor.getColumnIndex("date");
                        int monthColIndex = cursor.getColumnIndex("month");
                        int yearColIndex = cursor.getColumnIndex("year");
                        ArrayList<Integer> pulses = new ArrayList<>();
                        ArrayList<Calendar> dates = new ArrayList<>();
                        do{
                            pulses.add(cursor.getInt(idColPulse));
                            dates.add(new GregorianCalendar(cursor.getInt(yearColIndex), cursor.getInt(monthColIndex), cursor.getInt(dateColIndex)));
                        }while (cursor.moveToNext());
                        cursor.close();
                        dbHelper.close();
                        for (int i = 0;i<pulses.size();i++){
                            textView.append(pulses.get(i) +"\n");
                        }
                    }

                }catch (NumberFormatException e){
                    Toast.makeText(getContext(),"Wrong input!", Toast.LENGTH_SHORT).show();
                }


            }
        });
        return view;
    }

    public class DBHelper extends SQLiteOpenHelper {

        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,"+
                    "pulse integer,"+"date integer,"+"month integer,"+"year integer"+");");
        }

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

        }
    }


}

При считывании данных из бд и добавлении в textView выдает ошибку:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.append(java.lang.CharSequence)' on a null object reference at asus.example.com.fitnessapp.IndicationsFragment$1.onClick(IndicationsFragment.java:87) at android.view.View.performClick(View.java:6597) at android.view.View.performClickInternal(View.java:6574) at android.view.View.access$3100(View.java:778) at android.view.View$PerformClick.run(View.java:25885) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Хотя бд не пуста и содержит данные

1 ответ 1

2

У вас textView нигде не инициализируется.

Ваш ответ

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

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