Android won't save data entered to the SQLite database

问题: I am creating an app which manages ingredients. I want to create an SQLite database which will save all the ingredients which a user enters when they click the save button....

问题:

I am creating an app which manages ingredients. I want to create an SQLite database which will save all the ingredients which a user enters when they click the save button. However, for some reason my data won't save to the SQLite database. I cannot see what is wrong with the code at all.

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper
{
    private static final String tag = "Database Helper";
    private static final String TABLE_NAME = "products_registered";
    private static final String col1 = "Name";
    private static final String col2 = "Weight";
    private static final String col3 = "Price";
    private static final String col4 = "Description";

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        String createTable = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
                             " (_id INTEGER PRIMARY KEY AUTOINCREMENT," +
                             col1 + " TEXT NOT NULL," +
                             col2 + " DOUBLE NOT NULL," +
                             col3 + " DOUBLE NOT NULL," +
                             col4 + " TEXT);";

        db.execSQL(createTable);
    }

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

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

    public boolean addData(String item1, String item2, String item3, String item4)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(col1, item1);
        contentValues.put(col2, item2);
        contentValues.put(col3, item3);
        contentValues.put(col4, item4);

        Log.d(tag,"Adding name " + item1 + " to " + TABLE_NAME);

        long result = db.insert(TABLE_NAME, null, contentValues);
        db.close();
        if(result == -1)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

The Register Product Activity

public class RegisterProduct extends AppCompatActivity
{

    DatabaseHelper databaseHelper;
    private Button saveProductButton;
    private EditText productName;
    private EditText productWeight;
    private EditText productPrice;
    private EditText productDescription;
    DatabaseHelper mDatabaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_product);
        saveProductButton = (Button) findViewById(R.id.saveButton);
        productName = (EditText) findViewById(R.id.enterName);
        productWeight = (EditText) findViewById(R.id.enterWeight);
        productPrice = (EditText) findViewById(R.id.enterPrice);
        productDescription = (EditText) findViewById(R.id.enterDescription);
        mDatabaseHelper = new DatabaseHelper(this);


        try
        {
            saveProductButton.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View view)
                {
                    String nameEntered = productName.getText().toString();
                    String weightEntered = productWeight.getText().toString();
                    String priceEntered = productPrice.getText().toString();
                    String descriptionEntered = productDescription.getText().toString();

                    addData(nameEntered, weightEntered, priceEntered, descriptionEntered);
                    productName.setText("");

                }
            });
        }
        finally
        {
            mDatabaseHelper.close();
        }
    }

    public void addData(String newEntry1, String newEntry2, String newEntry3, String newEntry4)
    {
        mDatabaseHelper.addData(newEntry1, newEntry2, newEntry3, newEntry4);
    }

I created a seperate class to create the database and table itself and then created the activity where I called the methods to save the data input in the activity displayed below.

Image of activity display


回答1:

Your issue is most likely that you have changed the structure/schema of the database probably adding a column since running the App.

Typically you would get an SQLite exception when running the App indicating that the column was not found. However, as you have wrapped the addData in a try/finally construct the exception has been suppressed thus it appears that all is fine as the App doesn't crash or show anything in the log.

Wrapping database code in try constructs and trapping errors, as you have found can be confusing and it is suggested that you don't.

The reason why changing the schema/structure within the code for the onCreate method (the likely root cause of the issue), is that the onCreate method ONLY RUNS automatically when the database is created.

If the schema/structure of the database is changed then you need some way of either forcing the structure change or when developing an App, as the underlying data, should not need to be saved, then the easiest way is to delete the database and then rerun the App.

The database can be deleted by either deleting the App's data or by uninstalling the App (noting that any existing data will be lost).

An alternative, is to DROP the respective table(s) and recreate them. Frequently the onUpgrade method will written to do this. If this is the case (it is in your case) then another way of changing the structure is to trigger the onUpgrage method by increasing the version number pass to the SQLiteOpenHelper constructor (the super call). In your case you could change super(context, TABLE_NAME, null, 1); to be super(context, TABLE_NAME, null, 2);

After deleting the database or increasing the version number (preferably removing the try/finally construct from around the call to addData) and reunning the App, it may well just work. If not then the log should show any exceptions and problems can then be pinpointed.

  • 发表于 2019-03-27 20:27
  • 阅读 ( 193 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除