2013-06-13 104 views
0

我已經做了一個簡單的數據庫應用程序在android使用DBhelper,我已經把2 Edittexts和2按鈕,現在我想要的是當我按「保存」2 edittexts的值應保存在數據庫中。我試過下面的代碼,但它不工作,請幫助我,在此先感謝。數據庫沒有在android中創建

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

不工作意味着什麼?什麼錯誤你獲得後logcat。 –

+0

我已經把日誌貓,其實我想要的是,當我點擊「保存」編輯文本中輸入的數據應保存在DB.But當我按下「保存」按鈕應用程序停止運行..不幸的是。 – jigar

+0

(MainActivity.java:67)哪條語句指向? –

回答

1

你的數據庫幫助看起來好像沒什麼問題。由於fname和lname爲空,您將得到一個空的異常錯誤。

b1.setOnClickListener(新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)){ 
.... 
} 
+0

現在沒有生成錯誤,但..我的條目不保存在數據庫表中。 .my表格仍然是空白的。 – jigar

+0

你需要改變entry.createEntry(fname,lname); entry.createEntry(f,l);太。可能是你的桌子爲空的原因。 –

+0

我已編輯按照你告訴...仍然問題仍然是一樣的..我已經編輯我的logcat..please chek它,.. bro – jigar

1

小錯誤在你的String對象看這個使用這種

fname = e1.getText().toString(); 
lname = e2.getText().toString(); 

代替的

String f = e1.getText().toString(); 
String l = e2.getText().toString(); 
+0

現在沒有生成錯誤,但..我的條目不保存在數據庫表..我的表仍然是空白。 – jigar

+0

現在你的錯誤解決了?這將是你的代碼中的另一個問題。你必須清楚地告訴我什麼是問題,以及你如何編碼.. –

+0

我編輯了我的問題...代碼.. – jigar