如何避免使用android在sqlite中存储空值

时间:2014-08-09 09:46:05

标签: android database sqlite insert null

如果单击添加按钮,则必须将值存储在sqLite数据库中。 我的问题是它也存储了空值 怎么避免那一个? 帮帮我的朋友

//creating database and table

    public class Database extends SQLiteOpenHelper {
            static int dbversion=1;
            static String dbname="expense.db";

            public Database(Context context)
                     {
                super(context, dbname, null, dbversion);
                // TODO Auto-generated constructor stub
            }

            @Override
            public void onCreate(SQLiteDatabase db) {
                db.execSQL("create table addsource(source text)");


//inserting values in database

    add.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub

                        Database db=new Database(Sett.this);
                        SQLiteDatabase sb=db.getReadableDatabase(); 

                        sb.execSQL("insert into addsource(source)values('"+sources.getText()+"')");
                        Toast.makeText(getApplicationContext(), "Registered Successfully",Toast.LENGTH_SHORT).show();

                    }
                });

            }

3 个答案:

答案 0 :(得分:0)

为什么不测试这个值?

if(sources != null){
    sb.execSQL("insert into addsource(source)values('"+sources.getText()+"')");
}
else{ 
    //insert what you want
}

此外,我认为您不能插入空值,您可能只插入一个空字符串:

sources.getText()

因此,您可以测试sources != null而不是sources.getText().length > 0,并插入您想要的内容,以防万一。

答案 1 :(得分:0)

你可以在插入数据库之前检查值。将值输入字符串并检查字符串在单击添加按钮时不为空,然后插入表格。

你也可以在表创建中使用'not null'

Creating table in sqlite android

答案 2 :(得分:0)

您有3种方式:

1-在create table中添加NOT NULL:

CREATE TABLE your_table ( column_name INT NOT NULL, ....)

2-使用SELECT时选择非空值:

SELECT column_name FROM your_table WHERE column_name IS NOT NULL

3-检查变量值以查看它是否为空:

if ( String.ValueOf(source) != null){   // for string example
      // add the source to the database
}