【问题标题】:Android: SQLite error in adding dataAndroid:添加数据时的 SQLite 错误
【发布时间】:2017-04-13 04:51:22
【问题描述】:

我正在开发一个类似于 PiggyBank 的应用程序,用户可以在其中创建他们想要的物品的愿望清单,并帮助他们为该物品进行储蓄。我的应用还处于原型阶段,因为我还在学习 android。

我现在遇到的问题是每次添加新数据时,它总是返回 false。这是我的代码:

DatabaseHelper.java

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class DatabaseHelper extends SQLiteOpenHelper {

private static final String TAG = "DatabaseHelper";

private static final String TABLE_NAME = "people_table";
private static final String COL1 = "ID";
private static final String COL2 = "name";
private static final String COL3 = "price";
private static final String COL4 = "totalsavings";
private static final String COL5 = "duedate";


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

@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COL2 +" TEXT, " + COL3 + "TEXT, " + COL4 +"INTEGER)";
    db.execSQL(createTable);
}

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

public boolean addData(String item) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL2, item);
    contentValues.put(COL3, item);
    contentValues.put(COL4, item);

    Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);

    long result = db.insert(TABLE_NAME, null, contentValues);

    //if date as inserted incorrectly it will return -1
    if (result == -1) {
        return false;
    } else {
        return true;
    }
}

/**
 * Returns all the data from database
 * @return
 */
public Cursor getData(){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_NAME;
    Cursor data = db.rawQuery(query, null);
    return data;
}

/**
 * Returns only the ID that matches the name passed in
 * @param name
 * @return
 */
public Cursor getItemID(String name){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT " + COL1 + " FROM " + TABLE_NAME +
            " WHERE " + COL2 + " = '" + name + "'";
    Cursor data = db.rawQuery(query, null);
    return data;
}

/**
 * Updates the name field
 * @param newName
 * @param id
 * @param oldName
 */
public void updateName(String newName, int id, String oldName){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "UPDATE " + TABLE_NAME + " SET " + COL2 +
            " = '" + newName + "' WHERE " + COL1 + " = '" + id + "'" +
            " AND " + COL2 + " = '" + oldName + "'";
    Log.d(TAG, "updateName: query: " + query);
    Log.d(TAG, "updateName: Setting name to " + newName);
    db.execSQL(query);
}

/**
 * Delete from database
 * @param id
 * @param name
 */
public void deleteName(int id, String name){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "DELETE FROM " + TABLE_NAME + " WHERE "
            + COL1 + " = '" + id + "'" +
            " AND " + COL2 + " = '" + name + "'";
    Log.d(TAG, "deleteName: query: " + query);
    Log.d(TAG, "deleteName: Deleting " + name + " from database.");
    db.execSQL(query);
}

}

MainActivity.java

    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";

DatabaseHelper mDatabaseHelper;
private Button btnAdd, btnViewData;
private EditText editText, editText2;

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

    //for inputs
    editText = (EditText) findViewById(R.id.editText);
    editText2 =(EditText) findViewById(R.id.editText2);

    //buttons
    btnAdd = (Button) findViewById(R.id.btnAdd);
    btnViewData = (Button) findViewById(R.id.btnView);

    //call database
    mDatabaseHelper = new DatabaseHelper(this);

    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String newEntry = editText.getText().toString();
            if (editText.length() != 0) {
                AddData(newEntry);
                editText.setText("");
            } else {
                toastMessage("You must put something in the text field!");
            }

            String newPriceEntry = editText2.getText().toString();
            if (editText2.length() != 0) {
                AddData(newPriceEntry);
                editText2.setText("");
            } else {
                toastMessage("You must put something in the text field!");
            }

        }
    });

    btnViewData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
            startActivity(intent);
        }
    });

}

public void AddData(String newEntry) {
    boolean insertData = mDatabaseHelper.addData(newEntry);

    if (insertData) {
        toastMessage("Data Successfully Inserted!");
    } else {
        toastMessage("Something went wrong");
    }
}

/**
 * customizable toast
 * @param message
 */
private void toastMessage(String message){
    Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}

ListDataActivity.java

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

/**
* Created by User on 2/28/2017.
*/

public class ListDataActivity extends AppCompatActivity {

private static final String TAG = "ListDataActivity";

DatabaseHelper mDatabaseHelper;

private ListView mListView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_layout);
    mListView = (ListView) findViewById(R.id.listView);
    mDatabaseHelper = new DatabaseHelper(this);

    populateListView();
}

private void populateListView() {
    Log.d(TAG, "populateListView: Displaying data in the ListView.");

    //get the data and append to a list
    Cursor data = mDatabaseHelper.getData();
    ArrayList<String> listData = new ArrayList<>();
    while(data.moveToNext()){
        //get the value from the database in column 1
        //then add it to the ArrayList
        listData.add(data.getString(1));

    }
    //create the list adapter and set the adapter
    ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
    mListView.setAdapter(adapter);

    //set an onItemClickListener to the ListView
    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String name = adapterView.getItemAtPosition(i).toString();
            Log.d(TAG, "onItemClick: You Clicked on " + name);

            Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
            int itemID = -1;
            while(data.moveToNext()){
                itemID = data.getInt(0);
            }
            if(itemID > -1){
                Log.d(TAG, "onItemClick: The ID is: " + itemID);
                Intent editScreenIntent = new Intent(ListDataActivity.this, EditDataActivity.class);
                editScreenIntent.putExtra("id",itemID);
                editScreenIntent.putExtra("name",name);
                startActivity(editScreenIntent);
            }
            else{
                toastMessage("No ID associated with that name");
            }
        }
    });
}

/**
 * customizable toast
 * @param message
 */
private void toastMessage(String message){
    Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
   }
}

EditDataActivity.java 在此活动中,数据将显示在一个 EditText(名称)、储蓄目标(价格)中。 (我仍在研究总储蓄)。

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;



 public class EditDataActivity extends AppCompatActivity {

private static final String TAG = "EditDataActivity";

private TextView myGoal, mySavings;
private Button btnSave,btnDelete, btnDeposit;
private EditText editable_item, depositInput;

DatabaseHelper mDatabaseHelper;

private String selectedName, selectedPrice;
private int selectedID, selectedTotalSavings;

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

    myGoal =  (TextView) findViewById(R.id.displayGoal);
    mySavings = (TextView) findViewById(R.id.displayTotalSavings);

    btnSave = (Button) findViewById(R.id.btnSave);
    btnDelete = (Button) findViewById(R.id.btnDelete);
    btnDeposit = (Button) findViewById(R.id.btnDeposit);

    editable_item = (EditText) findViewById(R.id.editable_item);
    mDatabaseHelper = new DatabaseHelper(this);

    //get the intent extra from the ListDataActivity
    Intent receivedIntent = getIntent();

    //now get the itemID we passed as an extra
    selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value

    //now get the name we passed as an extra
    selectedName = receivedIntent.getStringExtra("name");

    //now get the price we passed as an extra
    selectedPrice = receivedIntent.getStringExtra("price");

    //now we get the totalsavings we passed as an extra
    selectedTotalSavings = receivedIntent.getIntExtra("totalsavings", -1);

    //set the text to show the current selected name
    editable_item.setText(selectedName);

    //set the text to show the user's saving goal
    myGoal.setText(selectedPrice);

    //set text to show the user's total savings so far
    mySavings.setText(selectedTotalSavings);

        //-----------------------------------DIALOG BOX-----------------------------------------
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Enter Deposit");
        builder.setMessage("Enter your deposit!");

        depositInput= new EditText(this);
        builder.setView(depositInput);

            //SET POSITIVE BUTTON
                builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String depositTxt=depositInput.getText().toString();

                        selectedTotalSavings = Integer.parseInt(selectedTotalSavings + depositTxt);
                        mySavings.setText(selectedTotalSavings);
                        Toast.makeText(getApplicationContext(),depositTxt, Toast.LENGTH_LONG).show();
                    }
                });

            //SET NEGATIVE BUTTON
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

            //CREATE THE DIALOG
            final AlertDialog depositPrompt=builder.create();

        //--------------------------------------------------------------------------------------

    //buttons
    btnSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String item = editable_item.getText().toString();
            if(!item.equals("")){
                mDatabaseHelper.updateName(item,selectedID,selectedName);
            }else{
                toastMessage("You must enter a name");
            }
        }
    });

    btnDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mDatabaseHelper.deleteName(selectedID,selectedName);
            editable_item.setText("");
            toastMessage("removed from database");
        }
    });

    btnDeposit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0){
            depositPrompt.show();


        }
    });

}

/**
 * customizable toast
 * @param message
 */
private void toastMessage(String message){
    Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
  }
}

这是示例语法

  • 用户输入名称和价格的详细信息
  • 用户点击添加数据
  • 用户可以查看数据,数据将显示在 ListView 上
  • 用户可以在 EditDataActivity 中编辑和查看数据

我不确定是什么问题。

更新

所以我在 MainActivity 类上找到了这段代码。我正在尝试从 editText2 添加数据,但我不知道如何。

 btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String newEntry = editText.getText().toString();
            if (editText.length() != 0) {
                AddData(newEntry);
                editText.setText("");
            } else {
                toastMessage("You must put something in the text field!");
            }

            String newPriceEntry = editText2.getText().toString();
            if (editText2.length() != 0) {
                AddData(newPriceEntry);
                editText2.setText("");
            } else {
                toastMessage("You must put something in the text field!");
            }

        }
    });

    btnViewData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
            startActivity(intent);
        }
    });

}

public void AddData(String newEntry) {
    boolean insertData = mDatabaseHelper.addData(newEntry);

    if (insertData) {
        toastMessage("Data Successfully Inserted!");
    } else {
        toastMessage("Something went wrong");
    }
}

我必须创建一个新的 AddData 吗?

【问题讨论】:

  • 使用 ormlite 而不是 sqlite 进行快速操作

标签: java android sql sqlite sqliteopenhelper


【解决方案1】:

您需要插入正确类型的值,如下所述:

public boolean addData(String item) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL2, item);
    contentValues.put(COL3, item);
    contentValues.put(COL4, item); // pass an integer instead of a String as you have mentioned its datatype as INTEGER or parse it using Integer.parseInt()

    Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);

    long result = db.insert(TABLE_NAME, null, contentValues);

    //if date as inserted incorrectly it will return -1
    if (result == -1) {
        return false;
    } else {
        return true;
    }
}

【讨论】:

  • 其实按照this“在 SQLite 中,值的数据类型与值本身相关联,而不是与其容器相关联。”
【解决方案2】:

我认为问题出在CREATE TABLE 查询中。

String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT, " + COL3 + "TEXT, " + COL4 +"INTEGER)";

COL3"TEXT" 之间没有空格(COL4"INTEGER" 相同)。所以只需像这样添加一个空格。

String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT, " + COL3 + " TEXT, " + COL4 +" INTEGER)";

【讨论】:

    【解决方案3】:

    问题出在您的 addData() 方法中。 COL4 持有 INTEGER 值。

    试试这个:

    public boolean addData(String item) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL2, item);
        contentValues.put(COL3, item);
        contentValues.put(COL4, Integer.parseInt(item));
    
        Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
    
        long result = db.insert(TABLE_NAME, null, contentValues);
    
        //if date as inserted incorrectly it will return -1
        if (result == -1) {
            return false;
        } else {
            return true;
        }
    }
    

    【讨论】:

      【解决方案4】:

      db.insert() 的返回值是 long,您将它与 int 进行比较。改变

      if (result == -1) {
          return false;
      } else {
          return true;
      }
      

      return (int)result == -1;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多