我在android中使用DBhelper制作了一个简单的数据库应用程序,我已经放了2个Edittexts和2个按钮,现在我想要的是当我按下“保存”时,2个edittexts的值应该保存在数据库中。我试过下面的代码但它不起作用,请帮助我,提前致谢。
Main.java
package com.example.db;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText e1,e2;
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1=(EditText)findViewById(R.id.editText1);
e2=(EditText)findViewById(R.id.editText2);
b1=(Button)findViewById(R.id.button1);
b2=(Button)findViewById(R.id.button2);
final String fname = null;
final String lname = null;
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String f=e1.getText().toString();
String l =e2.getText().toString();
if(checkForNotEmpty(f, l)){
try{
dbclas entry =new dbclas(MainActivity.this);
entry.open();
entry.createEntry(f,l);
entry.close();
}catch (Exception e) {
// TODO: handle exception
showMyDialog("Error", e.toString());
}
}
Toast.makeText(getApplicationContext(),"Saved", 0).show();
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i =new Intent(MainActivity.this,Sqlview.class);
startActivity(i);
}
});
}
private boolean checkForNotEmpty(String fname,String lname) {
// TODO Auto-generated method stub
if(fname.equals("")){
showMyDialog("Error !!","Name Can't be blank");
return false;
}else if(lname.equals("")){
showMyDialog("Error !!","Skill Can't be blank");
return false;
}else{
return true;
}
}
public void showMyDialog(String dialogType,String msg){
Dialog da=new Dialog(this);
da.setTitle(dialogType);
TextView tv=new TextView(this);
tv.setText(msg);
if(dialogType.equals("Error !!")){
tv.setTextColor(Color.RED);
}else{
tv.setTextColor(Color.YELLOW);
}
da.setContentView(tv);
da.show();
}
}
dbhelper.java
package com.example.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class dbclas {
public static final String KEY_ROWID="_id";
public static final String FIRST_NAME="first_name";
public static final String LAST_NAME="last_name";
private static final String DATABASE_NAME="person";
private static final String DATABASE_TABLE="persons_table";
private static final int DATABASE_VERSION=1;
private DBHelper myHelper;
private final Context myContext;
private SQLiteDatabase myDatabase;
private static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String query="CREATE TABLE "+DATABASE_TABLE+" ( "+KEY_ROWID+" INTEGER PRIMARY KEY, "+FIRST_NAME+" TEXT NOT NULL, "+LAST_NAME+" TEXT NOT NULL);";
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS"+DATABASE_TABLE);
onCreate(db);
}
}
public dbclas(Context c){
myContext=c;
}
public dbclas open() throws SQLException{
myHelper=new DBHelper(myContext);
myDatabase=myHelper.getWritableDatabase();
return this;
}
public void close(){
myHelper.close();
}
public long createEntry(String fname, String lname) {
// TODO Auto-generated method stub
ContentValues cv=new ContentValues();
cv.put(FIRST_NAME, fname);
cv.put(LAST_NAME,lname);
return myDatabase.insert(DATABASE_TABLE, null,cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns=new String[]{KEY_ROWID,FIRST_NAME,LAST_NAME};
Cursor c=myDatabase.query(DATABASE_TABLE, columns,null, null, null,null,null);
String result="";
int iRow=c.getColumnIndex(KEY_ROWID);
int iName=c.getColumnIndex(FIRST_NAME);
int iSkill=c.getColumnIndex(LAST_NAME);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
result=result+c.getString(iRow)+" "+c.getString(iName)+" "+c.getString(iSkill)+"\n";
}
return result;
}
public String getFName(Long l) {
// TODO Auto-generated method stub
String[] columns=new String[]{KEY_ROWID,FIRST_NAME,LAST_NAME};
Cursor c=myDatabase.query(DATABASE_TABLE, columns, KEY_ROWID+"="+l, null, null, null, null);
if(c!=null){
c.moveToFirst();
String name=c.getString(1);
return name;
}
return null;
}
public String getLName(Long l) {
// TODO Auto-generated method stub
String[] columns=new String[]{KEY_ROWID,FIRST_NAME,LAST_NAME};
Cursor c=myDatabase.query(DATABASE_TABLE, columns, KEY_ROWID+"="+l, null, null, null, null);
if(c!=null){
c.moveToFirst();
String skill=c.getString(2);
return skill;
}
return null;
}
public void updateEntry(long lRow, String mName, String mSkill) {
// TODO Auto-generated method stub
Log.v("in update method","...");
ContentValues cvUpdate=new ContentValues();
cvUpdate.put(FIRST_NAME, mName);
cvUpdate.put(LAST_NAME,mSkill);
myDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID+"="+lRow,null);
}
public boolean checkID(Long l) {
// TODO Auto-generated method stub
String[] columns=new String[]{KEY_ROWID,FIRST_NAME,LAST_NAME};
Cursor c=myDatabase.query(DATABASE_TABLE, columns,null, null, null,null,null);
int iRow=c.getColumnIndex(KEY_ROWID);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
Long l_id=Long.valueOf(c.getString(iRow));
Log.v("L_id",""+l_id);
if(l==l_id){
return true;
}
}
return false;
}
public void deleteEntry(Long lRow) {
// TODO Auto-generated method stub
myDatabase.delete(DATABASE_TABLE, KEY_ROWID+"="+lRow, null);
}
}
main.xml中
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="28dp"
android:ems="10"
android:hint="Last Name"
android:inputType="textPersonName" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_alignRight="@+id/editText2"
android:layout_marginRight="20dp"
android:text="View" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_marginRight="23dp"
android:layout_marginTop="46dp"
android:layout_toLeftOf="@+id/button2"
android:text="Save" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="36dp"
android:layout_marginTop="48dp"
android:ems="10"
android:hint="First Name"
android:inputType="textPersonName" />
</RelativeLayout>
View.java
package com.example.databaseexample;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SQLView extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
TextView tv=(TextView) findViewById(R.id.tvSQLinfo);
DBOperations info=new DBOperations(this);
info.open();
String data=info.getData();
info.close();
tv.setText(data);
}
}
登录
06-13 10:24:02.851: E/SQLiteLog(21041): (1) table persons_table has no column named last_name
06-13 10:24:02.899: E/SQLiteDatabase(21041): Error inserting last_name=dgsfg first_name=jimg
06-13 10:24:02.899: E/SQLiteDatabase(21041): android.database.sqlite.SQLiteException: table persons_table has no column named last_name (code 1): , while compiling: INSERT INTO persons_table(last_name,first_name) VALUES (?,?)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at com.example.db.dbclas.createEntry(dbclas.java:63)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at com.example.db.MainActivity$1.onClick(MainActivity.java:41)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at android.view.View.performClick(View.java:4204)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at android.view.View$PerformClick.run(View.java:17355)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at android.os.Handler.handleCallback(Handler.java:725)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at android.os.Handler.dispatchMessage(Handler.java:92)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at android.os.Looper.loop(Looper.java:137)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at java.lang.reflect.Method.invokeNative(Native Method)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at java.lang.reflect.Method.invoke(Method.java:511)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-13 10:24:02.899: E/SQLiteDatabase(21041): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
您的数据库助手对我来说很好。您将收到null异常错误,因为fname和lname为null。
b1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String f=e1.getText().toString();
String l =e2.getText().toString();
if(checkForNotEmpty(fname, lname)){ // replace fname and lname with f and l here
try{
dbclas entry =new dbclas(MainActivity.this);
entry.open();
entry.createEntry(fname,lname);
entry.close();
}catch (Exception e) {
// TODO: handle exception
showMyDialog("Error", e.toString());
}
}
Toast.makeText(getApplicationContext(),"Saved", 0).show();
}
});
应该是
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String f=e1.getText().toString();
String l =e2.getText().toString();
String f=e1.getText().toString();
String l =e2.getText().toString();
if(checkForNotEmpty(f, l)){
....
}
答案 1 :(得分:1)
String对象中的小错误请看这个
fname = e1.getText().toString();
lname = e2.getText().toString();
而不是
String f = e1.getText().toString();
String l = e2.getText().toString();