我想将复选框值添加到数据库中,但它在 logcat 中显示错误,我已将我的值存储在变量“ta”中并且我已经对其进行了烘烤,然后它正在工作,当我将该值插入数据库时它是显示错误
package com.example.hhh;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
CheckBox ct1,ct2,ct3,ct4;
protected DatabaseAdapter helper;
String ta;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper=new DatabaseAdapter(this);
helper.open();
ct1=(CheckBox)findViewById(R.id.checkBox1);
ct2=(CheckBox)findViewById(R.id.checkBox2);
ct3=(CheckBox)findViewById(R.id.checkBox3);
ct4=(CheckBox)findViewById(R.id.checkBox4);
ct1.setOnClickListener(this);
ct2.setOnClickListener(this);
ct3.setOnClickListener(this);
ct4.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox ct=(CheckBox)v;
if(ct.isChecked())
{
ta=ct.getText().toString();
helper.Add(ta);
Toast.makeText(MainActivity.this, ""+ta,
Toast.LENGTH_SHORT).show();
helper.close();
}
}
}
abd 数据库类是包 com.example.hhh;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseAdapter {
SQLiteDatabase db;
DatabaseHelper helper;
public static final String DATABASE="Hotel";
public static final int VERSION=2;
public static final String query="create table hhh(id integer primary key,room text
not null)";
private Context ctx;
public DatabaseAdapter(Context ctx) {
super();
this.ctx=ctx;
}
public class DatabaseHelper extends SQLiteOpenHelper
{
public DatabaseHelper(Context context
) {
super(context, DATABASE, null, VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
public DatabaseAdapter open() {
helper=new DatabaseHelper(ctx);
db=helper.getWritableDatabase();
return this;
// TODO Auto-generated method stub
}
public void close() {
// TODO Auto-generated method stub
helper.close();
}
public long Add(String ta)
{
ContentValues vals=new ContentValues();
vals.put("room", ta);
long a=db.insert("Hotel", null, vals);
return a;
}
}
我通过在 open() 方法中初始化“db”来解决它。