Studyon Minte9.com
Android




Crud 1.2



* List Refresh

        // Keyboard Done button (insert in db)
	// Hide Keyboard
	// Scroll list to bottom

	%--- activity_main.xml

	<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	    xmlns:tools="http://schemas.android.com/tools"
	    android:orientation="vertical"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    tools:context=".MainActivity">
	    
	    <LinearLayout
		android:id="@+id/group"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:orientation="vertical">
		
		<EditText 
		    android:id="@+id/title"
				android:layout_width="fill_parent"
				android:layout_height="wrap_content"
				android:hint="Add Title"
				android:inputType="text"
				android:imeOptions="actionDone"
		    /> 
		    
			<!--  LOOK HERE (actionDone) -->
		
	    </LinearLayout>
		    
	    <ListView 
		android:id="@android:id/list"
		android:layout_width="match_parent"
		    android:layout_height="wrap_content"
		    android:text="my list"    
		    />
		
	</LinearLayout>


	%--- MainActivity.java

	package com.example.myapp;
	import java.util.List;

	import android.app.ListActivity;
	import android.content.Context;
	import android.os.Bundle;
	import android.view.KeyEvent;
	import android.view.WindowManager;
	import android.view.inputmethod.EditorInfo;
	import android.view.inputmethod.InputMethodManager;
	import android.widget.ArrayAdapter;
	import android.widget.EditText;
	import android.widget.ListView;
	import android.widget.TextView;
	import android.widget.TextView.OnEditorActionListener;

	public class MainActivity extends ListActivity {
		
		ArticleDataAccess dao;
		Boolean debug = true;
		EditText mEdit;
		ArrayAdapter<Article> listAdapter;
		
		@Override
	        protected void onCreate(Bundle state) {
			
			super.onCreate(state);
			
			//SCREEN ON (degug only)
			if (debug) {
				getWindow().addFlags(
					//WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|
				WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|
				WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|
				WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
			}

			setContentView(R.layout.activity_main);
			
			/*--- LOOK HERE (Done button clicked) ---*/
			
			mEdit = (EditText) findViewById(R.id.title);
			mEdit.setOnEditorActionListener(new OnEditorActionListener() {
				@Override
				public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
					if (actionId == EditorInfo.IME_ACTION_DONE) {
						hideKeyboard();
						addArticle();
						return true;
					}
					return false;
				}
			});
			
			//OPEN (db connection)
			dao = new ArticleDataAccess(this);
			dao.open();
			
			showList();
		}
		
		/**
		 * Insert article
		 */
		public void addArticle () {
			try {
				// get text value
				mEdit = (EditText) findViewById(R.id.title);
				String title = mEdit.getText().toString();
				dao.insert(title);			
				showList();	
				
				/*--- LOOK HERE --*/
				
				scrollListToBottom();
				
			} catch (Exception e) {}
		}
		
		/**
		 * Show articles list
		 */
		public void showList () {
			List<Article> values = dao.getAll();
			listAdapter = new ArrayAdapter<Article>(this, 
					android.R.layout.simple_list_item_1, values);
			setListAdapter(listAdapter);
		}
		
		/**
		 * Hide Keyboard after Done pressed
		 */
		public void hideKeyboard() {
			InputMethodManager imm = (InputMethodManager) getSystemService(
					Context.INPUT_METHOD_SERVICE
					);
			imm.hideSoftInputFromWindow(mEdit.getWindowToken(), 0);
		}
		
		/**
		 * Scroll list to last element
		 */
		public void scrollListToBottom() {
			final ListView articleList = (ListView) findViewById(android.R.id.list);
			articleList.post(new Runnable() {
			@Override
			public void run() {
				articleList.setSelection(listAdapter.getCount() + 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 TB_ARTICLE = "article";
		
		private static final String DB_NAME = "articles.db";
		private 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 " + TB_ARTICLE + " (" +
					"_id integer primary key autoincrement," +
					"title varchar not null" +
					")";
			
			db.execSQL(sql);
		}
		
		@Override
		public void onUpgrade(SQLiteDatabase db, int version_old, int version_new) {
			
		}
		
	}

	%--- Article.java

	package com.example.myapp;

	public class Article {
		
		private long id;
		private String title;
		
		public long getId() {
			return id;
		}
		
		public void setId(long id) {
			this.id = id;
		}
		
		public String getTitle() {
			return title;
		}
		
		public void setTitle(String title) {
			this.title = title;
		}
		
		public String toString() {
			return title;
		}
	}

	%--- ArticleDataAccess.java

	package com.example.myapp;
	import java.util.ArrayList;
	import java.util.List;

	import android.content.ContentValues;
	import android.content.Context;
	import android.database.Cursor;
	import android.database.sqlite.SQLiteDatabase;

	public class ArticleDataAccess {
		
		private MySQLiteHelper dbHelper;
		private SQLiteDatabase db;
		
		public ArticleDataAccess(Context context) {
			dbHelper = new MySQLiteHelper(context);
		}
		
		public void open() {
			db = dbHelper.getWritableDatabase();
		}
		
		public void close() {
			dbHelper.close();
		}
		
		public Article insert(String title) {

			//Insert
			ContentValues values = new ContentValues();
			values.put("title", title);
			long insertId = db.insert(MySQLiteHelper.TB_ARTICLE, null, values);
					
			//Get last inserted
			Cursor cursor = db.rawQuery("SELECT * FROM " + MySQLiteHelper.TB_ARTICLE + 
                                         " WHERE _id = " + insertId, null);
			cursor.moveToFirst();
			Article article = cursorToArticle(cursor);
			
			cursor.close();
			
			return article;
		}
			
		public List<Article> getAll() {
			
			List<Article> articles = new ArrayList<Article>();
			
			Cursor cursor = db.rawQuery("SELECT * FROM " + MySQLiteHelper.TB_ARTICLE, null);
			cursor.moveToFirst();
			while(!cursor.isAfterLast()) {
				Article article = cursorToArticle(cursor);
				articles.add(article);
				cursor.moveToNext();
			}		
			cursor.close();
			
			return articles;
		}
		
		private Article cursorToArticle(Cursor cursor) {
			Article article = new Article();
			article.setId(cursor.getLong(0));
			article.setTitle(cursor.getString(1));
			return article;
		}
		
		public void delete(Article article) {
			
		}
		
		public void update(Article article) {
			
		}
	}