0

This is my Main Activity:

public class MainActivity extends Activity {

EditText edittext_name, edittext_course;
Button addtodatabase;
String paramname,paramcourse;

Mysql sqlite;

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

    edittext_name = (EditText) findViewById(R.id.editText1);
    edittext_course = (EditText) findViewById(R.id.editText2);

    addtodatabase=(Button) findViewById(R.id.button1);

    addtodatabase.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            paramname=edittext_name.getText().toString();
            paramcourse=edittext_course.getText().toString();

            sqlite.addrecord(paramname, paramcourse);
            Toast.makeText(getApplicationContext(), "data saved succesfully", Toast.LENGTH_SHORT).show();

            edittext_name.setText("");
            edittext_course.setText("");
        }
    });
}

And this is my SQLiteOpenHelper extended class i.e Mysql:

public class Mysql extends SQLiteOpenHelper {

private static int DATABASE_VERSION = 1;
private static String DATABASE_NAME = "demotable";

public Mysql(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase sqdb) {
    // TODO Auto-generated method stub
    String Query = "CREATE TABLE demotable(namecloumn Text,coursecloumn Text)";
    sqdb.execSQL(Query);

}

@Override
public void onUpgrade(SQLiteDatabase sqdb, int arg1, int arg2) {
    // TODO Auto-generated method stub
    sqdb.execSQL("DROP TABLE IF EXISTS demotable");
    onCreate(sqdb);
}

public void addrecord(String name, String course) {
    SQLiteDatabase sqlite = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put("namecloumn", name);
    cv.put("coursecloumn", course);
    sqlite.insert("demotable", null, cv);
    sqlite.close();
}

}

when I am running this program in emulator, on button click it show "unfortunately stop working" instead of "data saved successfully"

1
  • Please post your logcat Commented Nov 26, 2013 at 5:36

1 Answer 1

1

you forget to initialize sqlite object of Mysql class before calling addrecord method on Button click so do it as:

        sqlite=Mysql(MainActivity.this);
        sqlite.addrecord(paramname, paramcourse);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.