在Android中插入数据时在Fragment中使用Sqlite数据库帮助程序时出错

时间:2016-01-24 15:38:12

标签: android sqlite android-fragments android-sqlite

我绝对是Android的初学者。现在我在Fragment中使用Sqlite数据库时遇到错误。我的代码出了什么问题?

我的数据库助手类:

OnCreate

这是我的片段类:

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "todo.db";
    private static final String TABLE_NAME = "task";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_DESCRIPTION = "description";
    private static final String COLUMN_DATE ="date";
    private static final String COLUMN_DONE = "done";
    private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+" ("+COLUMN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+COLUMN_DESCRIPTION+" TEXT,"+
    COLUMN_DATE+" DATE,"+COLUMN_DONE+" BOOLEAN)";
    SQLiteDatabase db;

    public DatabaseHelper(Context context)
    {
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db)
    {
        this.db = db;
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String query = "DROP TABLE IF EXISTS "+TABLE_NAME;
        db.execSQL(query);
        this.onCreate(db);
    }

    public  void insertTask(Task task)
    {
        db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_DESCRIPTION,task.getDescription());
        values.put(COLUMN_DATE,task.getDate().toString());
        values.put(COLUMN_DONE,Boolean.FALSE.toString());
        db.insert(TABLE_NAME, null, values);
        db.close();
    }
}

单击“保存”按钮时。这是投掷错误。

单击保存按钮后,这是logcat:

public class CreateTaskFragment extends Fragment{
    private DatabaseHelper dbHelper = new DatabaseHelper(getActivity());
    private Button saveBtn;
    private EditText tfDescription,tfDate;
    private int yy,mm,dd;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.create_task,container,false);

        tfDescription = (EditText)view.findViewById(R.id.tf_task_description);
        tfDate = (EditText)view.findViewById(R.id.tf_task_date);
        tfDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setPickerDate(v);
            }
        });

        saveBtn = (Button)view.findViewById(R.id.btn_save_task);
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveTask();
            }
        });

        return view;
    }

    public void setPickerDate(View v)
    {
        final Calendar calendar = Calendar.getInstance();
        int yy = calendar.get(Calendar.YEAR);
        int mm = calendar.get(Calendar.MONTH);
        int dd = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePicker = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String date = String.valueOf(monthOfYear+1)+"/"+String.valueOf(dayOfMonth)+"/"+String.valueOf(year);
                tfDate.setText(date);
            }
        }, yy, mm, dd);
        datePicker.show();
    }

    public void saveTask()
    {
        String description = tfDescription.getText().toString();
        String date = tfDate.getText().toString();

        if(description.isEmpty())
        {
            Toast.makeText(getActivity().getBaseContext(),"Description is required",Toast.LENGTH_SHORT).show();
        }
        else if(date.isEmpty())
        {
            Toast.makeText(getActivity().getBaseContext(),"Date is required",Toast.LENGTH_SHORT).show();
        }
        else if(description.length()<getResources().getInteger(R.integer.min_description_length))
        {
            String minChar = String.valueOf(getResources().getInteger(R.integer.min_description_length));
            Toast.makeText(getActivity().getBaseContext(),"Description should be minium "+minChar+" characters",Toast.LENGTH_SHORT).show();
        }
        else{
            //check date
            SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
            boolean parseOk = false;
            Date taskDate = new Date();
            try{
                taskDate = format.parse(date);
                Task task = new Task();
                task.setDescription(description);
                task.setDate(taskDate);
                dbHelper.insertTask(task);
                parseOk = true;
            }
            catch(ParseException e)
            {
                parseOk = false;
            }

            if(parseOk)
            {
                //insert task to database
                Toast.makeText(getActivity().getBaseContext(),"Task saved",Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(getActivity().getBaseContext(),"Invalid date format",Toast.LENGTH_SHORT).show();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您获得的错误是片段第101行的空指针异常。很难从你的帖子中看出101代表的是什么,但我假设这是一行:

dbHelper.insertTask(task);

您将dbHelper声明为类顶部的成员变量,但您从未实例化它。相反,您只需致电:

new DatabaseHelper(getActivity());

没有将它附加到dbHelper。将该行更改为:

dbHelper = new DatabaseHelper(getActivity());

希望能解决您的错误。