将数据写入DB

时间:2014-06-25 16:20:04

标签: android sqlite

我正在尝试使用以下代码向DB中写入内容:(来自here并进行了一些编辑)

 package com.example.db;
    import android.app.Activity;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.TextView;
    public class MainActivity extends Activity {
     String entered;

     public void onClick (View v){
         EditText et = (EditText)findViewById(R.id.et);
          entered = et.getText().toString(); 
     }
     @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
     EditText et = (EditText)findViewById(R.id.et);
      entered = et.getText().toString();
      SQLiteDatabase myDB= null;
      String TableName = "myTable";

      String Data="";


      try {
       myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);


       myDB.execSQL("CREATE TABLE IF NOT EXISTS "
         + TableName
         + " (Field1 STRING, Field2 INT(3));");


       myDB.execSQL("INSERT INTO "
         + TableName
         + " (Field1, Field2)"
         + " VALUES ("+entered+", 22);");


       Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);

       int Column1 = c.getColumnIndex("Field1");
       int Column2 = c.getColumnIndex("Field2");


       c.moveToFirst();
       if (c != null) {

        do {
         String Name = c.getString(Column1);
         int Age = c.getInt(Column2);
         Data =Data +Name+"/"+Age+"\n";
        }while(c.moveToNext());
       }
       TextView tv = (TextView)findViewById(R.id.tv);
       tv.setText(Data);

      }
      catch(Exception e) {
       Log.e("Error", "Error", e);
      } finally {
       if (myDB != null)
        myDB.close();
      }
     }

    }

但它不起作用。当我启动它时,只需关闭程序。 什么是incorect? 我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

您似乎忘记添加setContentView(R.layout.activity_main);,因为在OnCreate edittext 中,et为null。

所以将其添加为

 @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

使用您的xml布局文件更改activity_main