将产品保存在数据库中时出错

时间:2017-10-06 04:54:14

标签: android sqlite android-sqlite

在库存应用中保存或添加新产品时,我遇到了保存数据库的错误。我猜这与数量有关,但我不知道如何解决它。它说语法错误我只是无法弄明白。首先,它没有认识到数据库,因为它是错误的,但在更改后,它仍然无效。

EditorActivity.java

package com.example.bahubali.inventoryapp;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.bahubali.inventoryapp.data.ProductContract;
import com.example.bahubali.inventoryapp.data.ProductDbHelper;

import java.util.ArrayList;
import java.util.List;

public class EditorActivity extends AppCompatActivity {

    /*Edit text field to enter the product name*/
    private EditText mNameEditText;

    /*Edit text field to enter the product price*/
    private EditText mPriceEditText;

    /*Edit text field to enter the product quantity*/
    private Spinner mQuantitySpinner;

    /*Edit text field to enter the name of the supplier*/
    private EditText mSupplierText;

    /*Quantity of the product is varying so the default value of the product*/

    private int mQuantity;

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

        //Find all the relevant views that we will need to read the input from
        mNameEditText = (EditText)findViewById(R.id.edit_text_name);
        mPriceEditText = (EditText) findViewById(R.id.edit_text_price);

        mSupplierText = (EditText) findViewById(R.id.edit_text_supplier);
        mQuantitySpinner =(Spinner) findViewById(R.id.spinner_quantity);
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);
        ArrayAdapter<Integer> quantitySpinnnerAdapter = new ArrayAdapter<Integer>(this,
                R.layout.support_simple_spinner_dropdown_item,list);
        mQuantitySpinner.setAdapter(quantitySpinnnerAdapter);


    }

    /**
     * Get user input from editor and save new pet into database.
     */
    private void insertProduct(){
        // Read from input fields
        // Use trim to eliminate leading or trailing white space
        String productNameString = mNameEditText.getText().toString().trim();
        String productPriceString = mPriceEditText.getText().toString().trim();
        String productSupplierString = mSupplierText.getText().toString().trim();
        int price = Integer.parseInt(productPriceString);

        //Create database helper
        ProductDbHelper productDbHelper = new ProductDbHelper(this);

        //Get the database in the write mode
        SQLiteDatabase db = productDbHelper.getWritableDatabase();

        // Create a ContentValues object where column names are the keys,
        // and pet attributes from the editor are the values.
        ContentValues contentValues = new ContentValues();
        contentValues.put(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME,productNameString);
        contentValues.put(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE,price);
        contentValues.put(String.valueOf(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY),mQuantity);
        contentValues.put(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER,productSupplierString);


        //Insert a new row for the product in the database,returning ID of that new row
        long newRowId = db.insert(ProductContract.ProductEntry.TABLE_NAME,null,contentValues);

        // Show a toast message depending on whether or not the insertion was successful
        if (newRowId == -1) {
            // If the row ID is -1, then there was an error with insertion.
            Toast.makeText(this, "Error with saving product", Toast.LENGTH_SHORT).show();
        } else {
            // Otherwise, the insertion was successful and we can display a toast with the row ID.
            Toast.makeText(this, "Product saved with row id: " + newRowId, Toast.LENGTH_SHORT).show();
        }



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu options from the res/menu/menu_editor.xml file.
        // This adds menu items to the app bar.
        getMenuInflater().inflate(R.menu.menu_editor, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // User clicked on a menu option in the app bar overflow menu
        switch (item.getItemId()){
            // Respond to a click on the "Save" menu option
            case R.id.action_save:
                insertProduct();
                finish();
                return true;
            case R.id.action_delete:
                // Do nothing for now
                return true;
            // Respond to a click on the "Up" arrow button in the app bar
            case android.R.id.home:
                // Navigate back to parent activity (CatalogActivity)
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

logcat的:

10-11 11:41:21.256 5125-5125/com.example.bahubali.inventoryapp E/SQLiteDatabase: Error inserting  Product name=Rwf Price=100 Supplier=Fdg Quantity=0
                                                                                 android.database.sqlite.SQLiteException: near "name": syntax error (code 1): , while compiling: INSERT INTO inventory( Product name,Price,Supplier,Quantity) VALUES (?,?,?,?)
                                                                                     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
                                                                                     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
                                                                                     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                     at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
                                                                                     at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
                                                                                     at com.example.bahubali.inventoryapp.EditorActivity.insertProduct(EditorActivity.java:92)
                                                                                     at com.example.bahubali.inventoryapp.EditorActivity.onOptionsItemSelected(EditorActivity.java:121)
                                                                                     at android.app.Activity.onMenuItemSelected(Activity.java:2918)
                                                                                     at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:368)
                                                                                     at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
                                                                                     at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
                                                                                     at android.support.v7.app.AppCompatDelegateImplV9.onMenuItemSelected(AppCompatDelegateImplV9.java:674)
                                                                                     at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                                     at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
                                                                                     at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
                                                                                     at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:963)
                                                                                     at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:624)
                                                                                     at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:150)
                                                                                     at android.view.View.performClick(View.java:5207)
                                                                                     at android.view.View$PerformClick.run(View.java:21168)
                                                                                     at android.os.Handler.handleCallback(Handler.java:746)
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                     at android.os.Looper.loop(Looper.java:148)
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

1 个答案:

答案 0 :(得分:0)

不确定如何将所有字符串变量的数据收集到MODEL CLASS中,这是MVC设计概念的一部分。我将尝试包含一个链接看起来你没有这个设计,我不确定你是否已经创建了一个DBHelper类一旦你这样做,管理一个数据库是如此简单这里的任何方式都是存在于具有SAVE的Activity中的代码按钮和一堆名为etQuestion等的EditText字段,所以如果你想尝试这个伟大的一个奇怪的地方,我必须将字符串变量命名为TABLE,这样才能真正看到MVC设计

MVC Link

    private void addListenerOnButtonSave() {
    btnSave.setOnClickListener( new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            // 1. get reference to writable DB
            db = dbHelper.getWritableDatabase();

            // 2. create ContentValues to add key "column"/value
            ContentValues cv = new ContentValues();

            cv.put(Col_QUESTION,etQuestion.getText().toString().trim());
            cv.put(Col_ANS_ONE,etAnsOne.getText().toString().trim());
            cv.put(Col_COR_ANS_ONE,etCorAnsOne.getText().toString().trim());
            cv.put(Col_ANS_TWO,etAnsTwo.getText().toString().trim());
            cv.put(Col_COR_ANS_TWO,etCorAnsTwo.getText().toString().trim());
            cv.put(Col_ANS_THREE,etAnsThree.getText().toString().trim());
            cv.put(Col_COR_ANS_THREE,etCorAnsThree.getText().toString().trim());

            // 3. insert
            final String QUIZ_INFO = "theBOT";
            db.insert(QUIZ_INFO, null, cv);
            // 4. close
            db.close();

            Toast.makeText(PageTwo.this, "Record Added", Toast.LENGTH_LONG).show();
            //doDrop();
            //dbHelper.iDid(); //Call to method in DBHelper -----<<<< READ
        }
    } );
}