0

I'm trying to write something into DB using this code:(got from here and edited a little)

 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();
      }
     }

    }

But it dont works. Just shutting down the program , when I start it. Where is something incorect? How can I do this?

Community
  • 1
  • 1
Roki20121
  • 105
  • 1
  • 12
  • 1
    Logcat, please. http://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – laalto Jun 25 '14 at 16:27

1 Answers1

0

It seems that you have forgot to add setContentView(R.layout.activity_main); because in OnCreate edittext et is null.

So add this as

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

Change activity_main with your xml layout file.

Giru Bhai
  • 14,370
  • 5
  • 46
  • 74