Studyon Minte9.com
Android




Insert



	%--- MainActivity.java

	package com.example.myapp;
	import android.app.Activity;
	import android.content.ContentValues;
	import android.database.sqlite.SQLiteDatabase;
	import android.os.Bundle;
	import android.widget.Toast;

	public class MainActivity extends Activity {

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

			SQLiteDatabase db = new MySQLiteHelper(this).getWritableDatabase();
			
			/*--- LOOK HERE ---*/

			// Insert comment
			ContentValues values = new ContentValues();
			values.put("comment", "AAA");
			long insertId = db.insert("comments", null, values);
			
			Toast.makeText(getApplicationContext(), "id: " + insertId, Toast.LENGTH_LONG).show();
				// display: 1, 2, ...

			// if database version changes, the insertId will be reset to 1


		}
	}


	%--- MySQLiteHelper.java

	package com.example.myapp;

	import android.content.Context;
	import android.database.sqlite.SQLiteDatabase;
	import android.database.sqlite.SQLiteOpenHelper;

	public class MySQLiteHelper extends SQLiteOpenHelper {
		
		public static final String DB_NAME = "comments.db";
		public static final int DB_VERSION = 1;

		public MySQLiteHelper(Context context) {
			super(context, DB_NAME, null, DB_VERSION);
		}
		
		@Override
		public void onCreate(SQLiteDatabase db) {
					
			String sql = "CREATE TABLE comments (" 
					+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "	
					+ "comment TEXT NOT NULL"
					+ ")";
			db.execSQL(sql);
		}
		
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

			// onUpgrading the database you have to be aware of user not losing data!
			
			db.execSQL("DROP TABLE IF EXISTS comments");
			onCreate(db);
		}
	}


http://www.vogella.com/articles/AndroidSQLite/article.html#databasetutorial_ui
http://stackoverflow.com/questions/5036385/android-update-sqlite-db-schema