Lists, Views, Cursors, Exceptions, Dialogs, SQL in android

From D3xt3r01.tk
Jump to navigationJump to search

WHY

Because now I have 2 smart phones which know java pretty good and I could do stuff with them .. this is just the beginning ! Run the program and look at the logcat to see what calls what in which order and with what params

HOW

src/helloworld.java

package tk.d3xt3r01;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.view.ContextMenu.ContextMenuInfo; 
import android.view.View.OnCreateContextMenuListener; 

public class helloworld extends Activity {

    private static final String TAG = "d3x"; 
    public long selected_id;
    private static final int menu_add_a_number = Menu.FIRST;
    private static final int menu_quit = Menu.FIRST + 2;
    private static final int edit_this_number = Menu.FIRST + 3;
    private static final int delete_this_number = Menu.FIRST + 4;
    
    private DataBaseWork dh;

    public void refresh(){
    	Cursor info = dh.selectAll();
    	startManagingCursor(info);
    	
    	ListView list = (ListView) findViewById(R.id.lista);
        ListAdapter lista = new SimpleCursorAdapter(this, R.layout.lista, info, new String[]{ "name", "number" }, new int[] {R.id.name, R.id.number} );
	    try {
	    	list.setAdapter(lista);
	    }catch(Exception NullPointerExceptionError){
	       	Log.e(TAG, "list.setAdapter(lista) made a boooboo. List: "+list+"; Lista: "+lista);
	    }
	    list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
        	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        		Log.i(TAG, "onCreateContextMenu();");
	            menu.setHeaderTitle("Action");
	            menu.add(0, delete_this_number, 0, R.string.delete_this_number);
	            menu.add(0, edit_this_number, 0, R.string.edit_this_number);
			} 
       });
    }
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "onCreate();");
        this.dh = new DataBaseWork(this);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        refresh();
    }

	@Override
	public void onDestroy(){
		Log.i(TAG, "onDestroy();");
		dh.close();
		super.onDestroy();
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu){
    	Log.i(TAG, "onCreateOptionsMenu();");
        menu.add(0, menu_add_a_number, 0, R.string.menu_add_a_number);
        menu.add(0, menu_quit, 0, R.string.menu_quit);
        return(super.onCreateOptionsMenu(menu));
    }
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item){
    	Log.i(TAG, "onOptionsItemSelected("+item.getItemId()+");");
    	switch(item.getItemId()){
    	case menu_add_a_number:
    		showDialog(item.getItemId());
    		break;
    	case menu_quit:
    		super.finish();
    		break;
    	}
        return super.onOptionsItemSelected(item);
    }
	
	@Override
    public Dialog onCreateDialog(int id){
		Dialog return_dialog = null;
		switch(id){
		case menu_add_a_number:
			Log.i(TAG, "onCreateDialog(add_a_number " + id + ");");
			LayoutInflater factory = LayoutInflater.from(this);
			final View textEntryView = factory.inflate(R.layout.input_user, null);
			
			final EditText name = (EditText) textEntryView.findViewById(R.id.name_edit);
			final EditText number = (EditText) textEntryView.findViewById(R.id.telefon_edit);
		
			final AlertDialog alertdialog = new AlertDialog.Builder(this)
			.setTitle(R.string.menu_add_a_number)
			.setView(textEntryView)
			.setPositiveButton(R.string.ok_button, new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int i){
					Log.i(TAG, "onCreateDialog(add_a_number " + i + "): Clicked on OK");

					name.requestFocus();
					
					dh.insert(name.getText().toString(), number.getText().toString());
					
					Log.i(TAG, "Name: "+ name.getText().toString());
					Log.i(TAG, "Number: "+ number.getText().toString());
					
					name.setText("");
					number.setText("");
					
					refresh();
					
					dialog.dismiss();
				}
			})
			.setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int i){
					Log.i(TAG, "onCreateDialog("+ i +"): Clicked on Cancel");
					((EditText) textEntryView.findViewById(R.id.telefon_edit)).setText("");
					((EditText) textEntryView.findViewById(R.id.name_edit)).setText("");
					dialog.cancel();
				}
			}).create();
			return_dialog = alertdialog;
			break;
		case edit_this_number:
			Log.i(TAG, "onCreateDialog(edit_this_number " + id + ");");
			LayoutInflater factory_edit = LayoutInflater.from(this);
			final View textEntryView_edit = factory_edit.inflate(R.layout.input_user, null);
			final EditText name_edit = (EditText) textEntryView_edit.findViewById(R.id.name_edit);
			final EditText number_edit = (EditText) textEntryView_edit.findViewById(R.id.telefon_edit);
			final AlertDialog alertdialog_edit = new AlertDialog.Builder(this)
			.setTitle(R.string.edit_this_number)
			.setView(textEntryView_edit)
			.setPositiveButton(R.string.ok_button, new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int i){
					Log.i(TAG, "onCreateDialog(edit_this_number " + i + "): Clicked on OK");
					name_edit.requestFocus();
					dh.update(selected_id, name_edit.getText().toString(), number_edit.getText().toString());
					refresh();
					dialog.dismiss();
				}
			})
			.setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int i){
					Log.i(TAG, "onCreateDialog("+ i +"): Clicked on Cancel");
					((EditText) textEntryView_edit.findViewById(R.id.telefon_edit)).setText("");
					((EditText) textEntryView_edit.findViewById(R.id.name_edit)).setText("");
					dialog.cancel();
				}
			}).create();
			return_dialog = alertdialog_edit;
			break;
		}
		
		return return_dialog;
	}
	
	@Override
	public void onPrepareDialog(final int id, Dialog dialog){
		Log.i(TAG, "onPrepareDialog("+id+");");
		switch(id){
		case edit_this_number:
			Log.i(TAG, "onPrepareDialog(edit_this_number + "+id+" + SQL: "+selected_id+");");
			Cursor selected = dh.select(selected_id);
			try{
				((EditText) dialog.findViewById(R.id.name_edit)).setText(selected.getString(1));;
				((EditText) dialog.findViewById(R.id.telefon_edit)).setText(selected.getString(2));;
			}catch(NullPointerException e){
				Log.e(TAG, "Error setting stuff in the dialog: "+selected.getString(1)+", "+selected.getString(2));
			}
			selected.close();
			break;
		}
	}
	
    @Override
    public boolean onContextItemSelected(MenuItem aItem) {
    	Log.i(TAG, "onContextItemSelected();");
    	AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) aItem.getMenuInfo();
    	long id = menuInfo.id;
        switch (aItem.getItemId()){
        	case edit_this_number:
        		Log.i(TAG, "onContextItemSelected(edit_this_number + SQL:" + id + ");");
        		selected_id = id; 
        		showDialog(edit_this_number);
	    		break;
        	case delete_this_number:
        		Log.i(TAG, "onContextItemSelected(delete_this_number + SQL:" + id + ");");
        		dh.delete(menuInfo.id);
        		refresh();
        		break;
        }
        return false;
    }
}


src/DataBaseWork.java

package tk.d3xt3r01;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

public class DataBaseWork {
	
	private static final String DATABASE_NAME = "d3x";
	private static final String TABLE_NAME = "users";
    private static final int DATABASE_VERSION = 1;
    private Context context;
    private SQLiteDatabase db;
    private SQLiteStatement insertStatemet;
    private SQLiteStatement deleteStatemet;
    private static final String INSERT = "insert into " + TABLE_NAME + "(name,number) values (?,?)";
    private static final String DELETE = "delete from " + TABLE_NAME + " WHERE _id = ?";
    private static final String TAG = "d3x"; 

    public DataBaseWork(Context context) {
        this.context = context;
        OpenHelper openHelper = new OpenHelper(this.context);
        this.db = openHelper.getWritableDatabase();
        Log.i(TAG, "DataBaseWork("+INSERT+");");
        this.insertStatemet = this.db.compileStatement(INSERT);
    	Log.i(TAG, "DataBaseWork("+DELETE+");");
    	this.deleteStatemet = this.db.compileStatement(DELETE);
    }
    
    public long insert(String name, String number){
    	Log.i(TAG, "insert("+name+", "+number+");");
        this.insertStatemet.bindString(1, name);
        this.insertStatemet.bindString(2, number);
        return this.insertStatemet.executeInsert();
    }
    
    public Cursor select(long id){
    	Log.i(TAG, "select("+id+");");
    	Cursor selected = null;
    	try {
    		selected = this.db.query(TABLE_NAME, new String[] { "_id", "name", "number" }, "_id = "+id, null, null, null, null);
    		selected.moveToFirst();
    	}catch(SQLException e){
    		Log.i(TAG, "Error on select query for "+e.toString());
    	}
		return selected;
    }

    public void update(long id, String name, String number){
    	Log.i(TAG, "update("+id+", "+name+", "+number+");");
    	ContentValues update_entry = new ContentValues();
    	update_entry.put("name", name);
    	update_entry.put("number", number);
    	this.db.update(TABLE_NAME, update_entry, "_id = "+id, null);
    }
    
    public void delete(long id){
    	Log.i(TAG, "delete("+id+");");
    	this.deleteStatemet.bindString(1, Long.toString(id));
    	this.deleteStatemet.execute();
    }
    
    public void deleteAll() {
	    Log.i(TAG, "deleteAll();");
        this.db.delete(TABLE_NAME, null, null);
    }
    
    public Cursor selectAll() {
    	Log.i(TAG, "selectAll();");
        return(this.db.query(TABLE_NAME, new String[] { "name", "number", "_id" }, null, null, null, null, "name asc"));
    }
    
    public void close(){
    	db.close();
    }

    private static class OpenHelper extends SQLiteOpenHelper {
        OpenHelper(Context context) {
        	super(context, DATABASE_NAME, null, DATABASE_VERSION);
        	Log.i(TAG, "OpenHelper();");
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
        	String create_query = "CREATE TABLE " + TABLE_NAME + " (_id INTEGER PRIMARY KEY autoincrement, name TEXT, number TEXT)";
        	Log.i(TAG, "onCreate("+create_query+")");
        	db.execSQL(create_query);
        	db.setVersion(DATABASE_VERSION);
        }
        
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        	Log.i(TAG, "Upgrading database, this will drop tables and recreate.");
        	db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        	onCreate(db);
        }
    }
}

res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Hello World</string>

    <!--
    	Menu options
    -->
    <string name="menu_add_a_number">Add a number</string>
    <string name="menu_quit">Quit</string>
    
    
    <!--
    	Input user layout texts
    -->
    	<string name="name_edit">Name:</string>
    	<string name="telefon_edit">Phone:</string>
    	
    <!--
    	Context Menu texts
    -->
    	<string name="edit_this_number">Edit this number</string>
    	<string name="delete_this_number">Delete this number</string>
    	
    <!--
    	Various Texts
    -->
    <string name="cancel_button">Cancel</string>
    <string name="ok_button">Ok</string>
</resources>


res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <ListView android:id="@+id/lista"  
        android:layout_width="fill_parent"  
        android:layout_height="0px"  
        android:layout_weight="1"  
        android:cacheColorHint="#00000000">  
     </ListView>  
</LinearLayout>


res/layout/input_user.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical">
	<LinearLayout
  		xmlns:android="http://schemas.android.com/apk/res/android"
  		android:layout_width="wrap_content"
  		android:layout_height="wrap_content"
  		android:orientation="horizontal">
        <TextView xmlns:android="http://schemas.android.com/apk/res/android"
			android:layout_width="fill_parent"
  			android:layout_height="fill_parent"
  			android:textSize="24px"
  			android:text="@string/name_edit"/>
        <EditText android:id="@+id/name_edit"  
            android:textColor="#020905"  
            android:textSize="18sp"  
            android:layout_marginTop="6px"  
            android:layout_marginBottom="8px"  
            android:layout_marginLeft="12px"  
            android:layout_marginRight="12px"  
            android:layout_width="210px"  
            android:layout_height="wrap_content"
            android:text=""
            android:layout_weight="1"/>  
	</LinearLayout>  

	<LinearLayout
  		xmlns:android="http://schemas.android.com/apk/res/android"
  		android:layout_width="wrap_content"
  		android:layout_height="wrap_content"
  		android:orientation="horizontal">
        <TextView xmlns:android="http://schemas.android.com/apk/res/android"
			android:layout_width="wrap_content"
  			android:layout_height="wrap_content"
  			android:textSize="24px"
  			android:text="@string/telefon_edit"/>
        <EditText android:id="@+id/telefon_edit"  
            android:textColor="#020905"  
            android:textSize="18sp"  
            android:layout_marginTop="6px"  
            android:layout_marginBottom="8px"  
            android:layout_marginLeft="12px"  
            android:layout_marginRight="12px"  
            android:layout_width="210px"  
            android:layout_height="wrap_content"
            android:text=""
            android:phoneNumber="true"
            android:layout_weight="1"/>  
	</LinearLayout>
</LinearLayout>


res/layout/lista.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<TextView android:id="@+id/name"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:textSize="22px" />
	<TextView android:id="@+id/number"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content" />
</LinearLayout>