如何在按钮点击时在数据库中添加数据?

时间:2011-06-20 04:47:45

标签: android database

我是Android新手以下是我的代码我想通过点击按钮在数据库中添加数据但是当我点击按钮我的应用程序崩溃 任何人都可以建议我任何解决方案 这是我的代码:

public class Third extends Activity implements OnClickListener{
Button btn;
SQLiteDatabase db;
EditText edit1;
EditText edit2;
EditText edit3;

@Override
protected void onCreate(Bundle icicle) {
// TODO Auto-generated method stub
super.onCreate(icicle);
setContentView(R.layout.mit);
SQLiteDatabase db;
db = openOrCreateDatabase("doctorinfo.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
final String CREATE_TABLE_COUNTRIES ="CREATE TABLE med_d ("+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"+ "DOC_NAME TEXT,"+ "DOC_NO TEXT,"+ "DOC_EMAIL TEXT);";
//db.execSQL(CREATE_TABLE_COUNTRIES);
btn=(Button)findViewById(R.id.button1);
edit1=(EditText)findViewById(R.id.editText1);
edit2=(EditText)findViewById(R.id.editText2);
edit3=(EditText)findViewById(R.id.editText3);

btn.setOnClickListener(this);


}

@Override
public void onClick(View arg0) {
String d=edit1.getText().toString();
String m=edit2.getText().toString();
String p=edit3.getText().toString();

ContentValues values = new ContentValues();
values.put("DOC_NAME",d );
values.put("DOC_NO",m);
values.put("DOC_EMAIL",p);
//long countryId = db.insert("med_d", null, values);
//try {
db.insertOrThrow("med_d", null,values);
}// catch (Exception e) {
//Log.e("Add Error", e.toString());
//e.printStackTrace();
//}



}

3 个答案:

答案 0 :(得分:4)

SQLITEOPENHELPER CLASS

package com.db.demo;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;

/**
 * Subclass of the {@link SQLiteOpenHelper} that sets up the database for the
 * demo.
 * 
 * @author Kah
 */
public class DatabaseHelper extends SQLiteOpenHelper {

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

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE IF NOT EXISTS names ("
            + BaseColumns._ID
            + " INTEGER PRIMARY KEY AUTOINCREMENT, first VARCHAR, last VARCHAR)");
    db.execSQL("INSERT INTO names (first, last) VALUES ('John', 'Doe')");
    db.execSQL("INSERT INTO names (first, last) VALUES ('James', 'Kirk')");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Steps to upgrade the database for the new version ...
}

}

****活动类****

package com.db.demo;


import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class DataHandlingActivity extends ListActivity{
    private SQLiteDatabase database;
 String fields[] = { "first", "last", BaseColumns._ID };
    private CursorAdapter dataSource;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    DatabaseHelper helper = new DatabaseHelper(this);
    database = helper.getReadableDatabase();
    Cursor data = database.query("names", fields, null, null, null, null,
            null);

    dataSource = new SimpleCursorAdapter(this, R.layout.row, data, fields,
            new int[] { R.id.first, R.id.last });

    ListView view = getListView();
    view.setHeaderDividersEnabled(true);
    view.addHeaderView(getLayoutInflater().inflate(R.layout.row, null));

    setListAdapter(dataSource);
}

}

在按钮点击和更改活动类中使用类似的内容 update sql database with ContentValues and the update-method

答案 1 :(得分:2)

您必须使用SqliteOpenHelper类来执行所有数据库操作。

请仔细阅读此链接,这将为您提供一些好的建议。

http://www.xoriant.com/blog/mobile-application-development/android-sqlite-database.html

答案 2 :(得分:1)

将此方法放在数据库助手类中:

public long InsertRecord(String msg, String msg1,String msg2) {

    long d = 0;
    ContentValues values = new ContentValues();

    values.put(SMS_NO, msg);
    values.put(SMS_BODY, msg1);
            values.put(SMS_BODY, msg2);

    try {
        d = myDataBase.insert(SMS_TBL, null, values);
    } catch (Exception e) {

    }
    return d;

}

在您的活动的onCreate方法之后,您必须使用此代码创建数据库:

SQLiteDatabase sqLiteDatabase;
DataBaseHelper dbHelper;

dbHelper = new DataBaseHelper(getActivity().getApplicationContext());


            try {
                dbHelper.createDataBase();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            dbHelper.openDataBase();
                dbHelper.onCreate(sqLiteDatabase);

最后点击了btn点击

btnBlock.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String edittext = edittext.getText().toString();
            String edittext1 = edittext1.getText().toString();
                            String edittext2 = edittext2.getText().toString();

            dbHelper.InsertRecord(edittext,edittext1,edittext2);

        }
    });