android-NullPointerException而将数据插入sqlite数据库

时间:2018-11-02 15:42:22

标签: java android nullpointerexception

我在尝试将一些数据放入数据库时​​遇到了NullPointerException。我发现我的数据库为空,这就是答案,但是我不知道为什么它为空。

public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "productslist.db";
public static final String TABLE_NAME = "productslist_table";
public static final String COLUMN_1 = "ID";
public static final String COLUMN_2 = "NAME";
public static final String COLUMN_3 = "PRICE";
public static final String COLUMN_4 = "QUANTITY";
public static final String COLUMN_5 = "IS_CHECKED";

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

@Override
public void onCreate(SQLiteDatabase db) {
    String create_string = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, PRICE REAL, QUANTITY STRING, IS_CHECKED INTEGER)";
    db.execSQL(create_string);
}

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

public boolean addData(String name, String price, String quantity) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_2, name);
    contentValues.put(COLUMN_3, price);
    contentValues.put(COLUMN_4, quantity);
    contentValues.put(COLUMN_5, "0");
    long result = db.insert(TABLE_NAME, null, contentValues);
    if(result == -1)
        return false;
    else
        return true;
}
}

我正在尝试进行插入活动:

public class AddActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editName, editPrice, editQuantity;
Button saveButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add);

    editName = findViewById(R.id.editTextName);
    editPrice = findViewById(R.id.editTextPrice);
    editQuantity = findViewById(R.id.editTextQuantity);
    saveButton = findViewById(R.id.save_button);
    addData();
}

public void addData() {
    saveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editName.getText().toString();
            boolean isInserted = myDb.addData(editName.getText().toString(),
                    editPrice.getText().toString(),
                    editQuantity.getText().toString());
            if (isInserted == true)
                Toast.makeText(AddActivity.this, "Product added", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(AddActivity.this, "Failed adding product", Toast.LENGTH_LONG).show();
        }
    });
}
}

因此,在调试过程中,我注意到myDb对象为Null,我不知道为什么。

0 个答案:

没有答案