Studyon Minte9.com
Android




Crud 1.3



* Delete Article

	// Delete article on long click
	// Confirm delete with Alert Dialog


	%--- 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;
	import android.util.Log;

	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;
		}
		
		/*--- LOOK HERE ---*/
		
		public void delete(Article article) {
			db.execSQL("DELETE FROM " + MySQLiteHelper.TB_ARTICLE + 
                                          " WHERE _id=" + article.getId());
				Log.i("catalin", article.getTitle() + " deleted");
		}
		
		public void update(Article article) {
			
		}
	}


	%--- MainActivity.java

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

	import android.app.AlertDialog;
	import android.app.ListActivity;
	import android.content.Context;
	import android.content.DialogInterface;
	import android.os.Bundle;
	import android.view.KeyEvent;
	import android.view.View;
	import android.view.WindowManager;
	import android.view.inputmethod.EditorInfo;
	import android.view.inputmethod.InputMethodManager;
	import android.widget.AdapterView;
	import android.widget.AdapterView.OnItemLongClickListener;
	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;
		List<Article> listValues;
		ArrayAdapter<Article> listAdapter;
		
		@Override
	    protected void onCreate(Bundle state) {
			
			super.onCreate(state);
			
			//DEBUG (screen on automaticaly)
			if (debug) {
				getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|
				WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|
				WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
			}

			setContentView(R.layout.activity_main);
			
			//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;
				}
			});
			
			//DB connection
			dao = new ArticleDataAccess(this);
			dao.open();
			
			showList();
			
			/*--- LOOK HERE ---*/
			
			setLongClickDelete();
		}
		
		/**
		 * Insert article
		 */
		public void addArticle () {
			try {
				mEdit = (EditText) findViewById(R.id.title);
				String title = mEdit.getText().toString();
				
				dao.insert(title);	
				
				mEdit.setText("");
				
				showList();	
				scrollListToBottom();
				
			} catch (Exception e) {}
		}
		
		/**
		 * Show articles list
		 */
		public void showList () {
			
			// add values to list
			listValues = dao.getAll();
			listAdapter = new ArrayAdapter<Article>(this, 
					android.R.layout.simple_list_item_1, listValues);
			setListAdapter(listAdapter);
		}
		
		/*
		 * Delete List Item when user long click
		 */
		public void setLongClickDelete () {
			
			final ListView articleList = (ListView) findViewById(android.R.id.list);
			articleList.setOnItemLongClickListener(new OnItemLongClickListener() {
				public boolean onItemLongClick(
                                              AdapterView<?> addapter, View view, int position, long id) {
					
					/*--- LOOK HERE ---*/
					
					/* 
					// METHOD 1 (without confirmation)
		
					//SQL delete
					Article selectedArticle = (Article) articleList.getItemAtPosition(position);	
						//Log.i("catalin", selectedArticle.getId() + "");
					dao.delete(selectedArticle);
					
					//LIST remove
					listValues.remove(position);
					listAdapter.notifyDataSetChanged();
					*/
					
					// METHOD 2 (with confirmation)
		
					AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
				adb.setTitle("Delete ?").setMessage("Are you sure?");
				
				final int positionToRemove = position;
				
				adb.setNegativeButton("Cancel", null)
				   .setPositiveButton("Ok", new AlertDialog.OnClickListener() {
				    public void onClick(DialogInterface dialog, int which) {
					
					// SQL delete
					Article selectedArticle = (Article) articleList
                                                                                           .getItemAtPosition(positionToRemove);
					dao.delete(selectedArticle);
					
					// LIST remove
					listValues.remove(positionToRemove);
					listAdapter.notifyDataSetChanged();
				    }});
				adb.show();
					
					return true;
				}
			});
			
		}
		
		/**
		 * 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);
			}
		    });
		}
	}


	%--- activity_main.xml (not changed)

	<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"
		    /> 
			    
	    </LinearLayout>
		    
	    <ListView 
		android:id="@android:id/list"
		android:layout_width="match_parent"
		    android:layout_height="wrap_content"
		    />
		
	</LinearLayout>


	%--- Article.java (not changed)

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


	%--- MySQLiteHelper.java (not changed)

	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) {
			
		}
		
	}


http://stackoverflow.com/questions/15630562/simple-listview-multiple-choice-android