RSS

Category Archives: Android

How to Display Current Date in your program

Find it difficult to get the current date and time? Then read on, I this tutorial I demonstrate getting current date and time in different programming languages.

Java

Using Calendar

output: 28/6/2012

  Calendar cal = new GregorianCalendar();
  int month = cal.get(Calendar.MONTH);
  int year = cal.get(Calendar.YEAR);
  int day = cal.get(Calendar.DAY_OF_MONTH);
  System.out.println("Current date : " + day + "/" + (month + 1) + "/" + year);

Using SimpleDateFormat

output: 28/06/2012

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String sDate= sdf.format(date);

C#
Using DateTime format

output: Jun Fri 27 11:41 2012

DateTime time = DateTime.Now;              // Use current time
string format = "MMM ddd d HH:mm yyyy";    // Use this format
Console.WriteLine(time.ToString(format));

Some other patterns for DateTime
MMM : display three-letter month
ddd : display three-letter day of the WEEK
d : display day of the MONTH
HH : display two-digit hours on 24-hour scale
mm : display two-digit minutes
yyyy : display four-digit year

Single-letter format

output :
6/28/2012
Thursday, June 28, 2012
Thursday, June 28, 2012 11:36 AM
Thursday, June 28, 2012 11:36:21 AM
6/28/2012 11:36 AM
6/28/2012 11:36:21 AM
June 28
June 28
2012-06-28T11:36:21.8863219+05:30
2012-06-28T11:36:21.8863219+05:30
2012-06-28T11:36:21
11:36 AM
11:36:21 AM
2012-06-28 11:36:21Z
Thursday, June 28, 2012 6:06:21 AM
June, 2012
June, 2012

DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("d"));
Console.WriteLine(now.ToString("D"));
Console.WriteLine(now.ToString("f"));
Console.WriteLine(now.ToString("F"));
Console.WriteLine(now.ToString("g"));
Console.WriteLine(now.ToString("G"));
Console.WriteLine(now.ToString("m"));
Console.WriteLine(now.ToString("M"));
Console.WriteLine(now.ToString("o"));
Console.WriteLine(now.ToString("O"));
Console.WriteLine(now.ToString("s"));
Console.WriteLine(now.ToString("t"));
Console.WriteLine(now.ToString("T"));
Console.WriteLine(now.ToString("u"));
Console.WriteLine(now.ToString("U"));
Console.WriteLine(now.ToString("y"));
Console.WriteLine(now.ToString("Y"));

Using Date strings to control the output

output:
Thursday, June 28, 2012
12:03:53 PM
6/28/2012
12:03 PM
6/28/2012 12:03:53 PM

DateTime now = DateTime.Now;
Console.WriteLine(now.ToLongDateString());
Console.WriteLine(now.ToLongTimeString());
Console.WriteLine(now.ToShortDateString());
Console.WriteLine(now.ToShortTimeString());
Console.WriteLine(now.ToString());

PHP

output : 2012-06-28 17:33:07

$date = date('Y-m-d H:i:s');
echo $date;

output : 2012/06/28 17:33:07

$date = date('Y/m/d H:i:s');
echo $date;

This time is based on the default server time zone. To get the time in a different time zone it should be set first.

date_default_timezone_set('Australia/Sydney');
$date = date('Y/m/d H:i:s');
echo $date;

JavaScript

output : Thursday, June 28, 2012

<script type="text/javascript"><!--
var now = new Date();
var Weekday = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var Month = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
document.write(Weekday[now.getDay()]+", "+Month[now.getMonth()]+" "+now.getDate()+", "+now.getFullYear());
//--></script>

output : 6/28/2012

<script type="text/javascript"><!--
var now = new Date();
document.write((now.getMonth()+1)+"/"+now.getDate()+"/"+now.getFullYear());
//--></script>

output : 06/28/2012

<script type="text/javascript"><!--
var now = new Date();
var month = now.getMonth()+1;
if( month < 9 ) { month = "0"+month; }
var day = now.getDate();
if( day < 9 ) { day = "0"+day; }
document.write(month+"/"+day+"/"+now.getFullYear());
//--></script>

ios

 NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
 [dateFormatter setDateFormat:@"hh:mm a"];   
 NSString *str_date = [dateFormatter stringFromDate:[NSDate date]];
 NSLog(@"str_date:%@",str_date);
 
 

Tags:

Android To Do List

The To Do List application described in this tutorial  supports add new tasks, update and delete them. User can add new tasks using Options menu and delete them using Context menu

Download the complete project

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ListView
android:id="@+id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>

</LinearLayout>

new_task.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="@string/task"
android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
android:id="@+id/txtTask"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp" >

<requestFocus />
</EditText>

<TextView
android:id="@+id/textView3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="@string/task"
android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
android:id="@+id/txtDesc"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_marginBottom="10dp"
android:layout_weight="0.40" >
</EditText>

<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="@string/add" />

</LinearLayout>

row.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/row"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

</TextView>

Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ToDo List</string>
<string name="add">Add</string>
<string name="delete">Delete</string>
<string name="task">Task</string>
<string name="desc">Description</string>

</resources>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.biz"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".ToDo"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NewTask"></activity>
</application>

</manifest>

DBHelper.java

package com.my.biz;

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

public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "tasks";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "CREATE TABLE task_data (_id integer primary key autoincrement,task text not null,description text not null );";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);

}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.execSQL("DROP TABLE IF EXISTS task_data");
onCreate(db);

}

}

DBAdapter.java

package com.my.biz;

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

public class DBAdapter
{
private static final String DATABASE_TABLE = "task_data";
public static final String KEY_ROW_ID = "_id";
public static final String KEY_TASK = "task";
public static final String KEY_DESCRIPTION = "description";

SQLiteDatabase mDb;
Context mCtx;
DBHelper mDbHelper;

public DBAdapter(Context context)
{
this.mCtx = context;
}

public DBAdapter open() throws SQLException
{
mDbHelper = new DBHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}

public void close()
{
mDbHelper.close();
}

public long createTask(String task,String desciption)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TASK, task);
initialValues.put(KEY_DESCRIPTION, desciption);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}

public boolean deleteTask(long id)
{
return mDb.delete(DATABASE_TABLE, KEY_ROW_ID + " = " + id, null) > 0;
}

public boolean updateTask(long id,String task,String desciption)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TASK, task);
initialValues.put(KEY_DESCRIPTION, desciption);
return mDb.update(DATABASE_TABLE, initialValues, KEY_ROW_ID + " = " + id, null) > 0;
}

public Cursor fetchAllTasks()
{
return mDb.query(DATABASE_TABLE, new String[]{KEY_ROW_ID,KEY_TASK,KEY_DESCRIPTION}, null, null, null, null, null);
}

public Cursor fetchTask(long id)
{
Cursor c = mDb.query(DATABASE_TABLE, new String[]{KEY_ROW_ID,KEY_TASK,KEY_DESCRIPTION}, KEY_ROW_ID + " = " + id, null, null, null, null);
if(c != null)
{
c.moveToFirst();
}
return c;
}
}

NewTask.java

package com.my.biz;

import com.my.biz.DBAdapter;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;

public class NewTask extends Activity {
DBAdapter mDbAdapter;
Long mRowId;
EditText mTask;
EditText mDesc;
DatePicker mDate;
Spinner mCategorry;
Button mAdd;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbAdapter = new DBAdapter(this);
mDbAdapter.open();
setContentView(R.layout.new_task);

mTask = (EditText)findViewById(R.id.txtTask);
mDesc = (EditText)findViewById(R.id.txtDesc);
mAdd = (Button)findViewById(R.id.btnAdd);

mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(DBAdapter.KEY_ROW_ID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(DBAdapter.KEY_ROW_ID)
: null;
}

populateFields();

mAdd.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
setResult(RESULT_OK);
finish();

}
});
}

private void populateFields() {
if (mRowId != null) {
Cursor c = mDbAdapter.fetchTask(mRowId);
startManagingCursor(c);
mTask.setText(c.getString(
c.getColumnIndexOrThrow(DBAdapter.KEY_TASK)));
mDesc.setText(c.getString(
c.getColumnIndexOrThrow(DBAdapter.KEY_DESCRIPTION)));

}
}

@Override
protected void onPause() {
super.onPause();
saveState();
}

@Override
protected void onResume() {
super.onResume();
populateFields();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(DBAdapter.KEY_ROW_ID, mRowId);
}

private void saveState() {
String task = mTask.getText().toString();
String desc = mDesc.getText().toString();
if (mRowId == null) {
long id = mDbAdapter.createTask(task, desc);
if (id > 0) {
mRowId = id;
}
} else {
mDbAdapter.updateTask(mRowId, task, desc);
}
}

}

ToDo.java

package com.my.biz;

import com.my.biz.DBAdapter;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class ToDo extends ListActivity {
DBAdapter mDbAdapter;
private static final int ACTIVITY_CREATE = 0;
private static final int ACTIVITY_EDIT = 1;

public static final int INSERT_ID = Menu.FIRST;
public static final int DELETE_ID = Menu.FIRST + 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDbAdapter = new DBAdapter(this);
mDbAdapter.open();
fillData();
registerForContextMenu(getListView());
}

public void create()
{
Intent i = new Intent(this,NewTask.class);
startActivityForResult(i, ACTIVITY_CREATE);
}

public void fillData()
{
Cursor c = mDbAdapter.fetchAllTasks();
startManagingCursor(c);
String []from = new String[]{DBAdapter.KEY_TASK,DBAdapter.KEY_DESCRIPTION};
int [] to = new int[]{R.id.row};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, c, from, to);
setListAdapter(adapter);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
fillData();
}

@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId())
{
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbAdapter.deleteTask(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);


}


@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.delete);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.add);
return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case INSERT_ID:
create();
return true;


}


return super.onOptionsItemSelected(item);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this,NewTask.class);
i.putExtra(DBAdapter.KEY_ROW_ID, id);
startActivityForResult(i, ACTIVITY_EDIT);
}


}

Download the complete project

 
8 Comments

Posted by on May 10, 2012 in Android

 

Tags: ,

Simple Android Database Application

Today we are going to build a simple database application in Android. First see the project resources screenshot indicated below.


This application uses SQLite database which stores data as a file. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements. This is highly recommended for mobile applications as they share little memory compared to general desktop applications. When the application creates a database, it is saved in the directory data/data/APP_NAME/databases/FILENAME. (Find this using DDMS perspective in Eclipse)

We need a DBHelper class that inherits from SQLiteOpenHelper super class. This allows to create database, upgrade database,  get a writable database, get a readable database and many more.

DBAdapter class consists of several user-defined wrapper methods to handle database operations like add,update,delete,fetch data …etc. Inside these methods we call built-in methods in SQLiteDatabase class to accomplish  our tasks.

The Biz2Activity class is bind to main.xml and it creates the only GUI interface in the application. The interface  has a ListView to display business items as a list. User can add, update or delete a business using the options menu. Android DatePicker tool is used to get the date. Business categories are listed using Android  Spinner which uses an ArrayAdapter to get and display data. The data comes from a String array defined in Strings.xml in Resources folder.

This is the final application

Download Complete Project

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

<EditText
android:id="@+id/txtTask"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp">

<requestFocus />
</EditText>

<DatePicker
android:id="@+id/dtpDate"
android:layout_width="wrap_content"
android:layout_height="79dp" android:layout_marginBottom="10dp"/>

<Spinner
android:id="@+id/spCategory"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_marginBottom="10dp"/>

<ListView
android:id="@+id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>

</LinearLayout>

row.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id = "@+id/text1"
android:layout_width="match_parent"
android:layout_height="match_parent" >

</TextView>

Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="hello">Hello World, Biz2Activity!</string>
<string name="app_name">Biz2</string>
<string name="add">Add</string>
<string name="update">Update</string>
<string name="delete">Delete</string>
<string name="add_biz">Add New Business</string>
<string name="update_biz">Update Business</string>
<string name="title">Title</string>
<string name="start_date">Start Date</string>
<string name="category">Category</string>
<string name="save">Save</string>
<string-array name="biz_categories">
<item >Real Estate</item>
<item >Foods</item>
<item >Housing</item>
<item >Health Care</item>
</string-array>
</resources>

DBHelper.java

package com.my.biz2;

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

public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "biz";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "CREATE TABLE biz_data (_id integer primary key autoincrement,title text not null,start_date text,category text not null );";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);

}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.execSQL("DROP TABLE IF EXISTS biz_data");
onCreate(db);

}

}

DBAdapter.java

package com.my.biz2;

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

public class DBAdapter
{
	private static final String DATABASE_TABLE = "biz_data";
	public static final String KEY_ROW_ID = "_id";
	public static final String KEY_TITLE = "title";
	public static final String KEY_START_DATE = "start_date";
	public static final String KEY_CATEGORY = "category";

	SQLiteDatabase mDb;
	Context mCtx;
	DBHelper mDbHelper;

	public DBAdapter(Context context)
	{
		this.mCtx = context;
	}

	public DBAdapter open() throws SQLException
	{
		mDbHelper = new DBHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close()
	{
		mDbHelper.close();
	}

	public long createBiz(String title,String date,String category)
	{
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_TITLE, title);
		initialValues.put(KEY_START_DATE, date);
		initialValues.put(KEY_CATEGORY, category);
		return mDb.insert(DATABASE_TABLE, null, initialValues);
	}

	public boolean deleteBiz(long id)
	{
		return mDb.delete(DATABASE_TABLE, KEY_ROW_ID + " = " + id, null) > 0;
	}

	public boolean updateBiz(long id,String title,String date,String category)
	{
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_TITLE, title);
		initialValues.put(KEY_START_DATE, date);
		initialValues.put(KEY_CATEGORY, category);
		return mDb.update(DATABASE_TABLE, initialValues, KEY_ROW_ID + " = " + id, null) > 0;
	}

	public Cursor fetchAllBiz()
	{
		return mDb.query(DATABASE_TABLE, new String[]{KEY_ROW_ID,KEY_TITLE,KEY_START_DATE,KEY_CATEGORY}, null, null, null, null, null);
	}

	public Cursor fetchBiz(long id)
	{
		Cursor c = mDb.query(DATABASE_TABLE, new String[]{KEY_ROW_ID,KEY_TITLE,KEY_START_DATE,KEY_CATEGORY}, KEY_ROW_ID + " = " + id, null, null, null, null);
		if(c != null)
		{
			c.moveToFirst();
		}
		return c;
	}
}

Biz2Activity.java

package com.my.biz2;

import java.util.StringTokenizer;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;

public class Biz2Activity extends ListActivity {
    DBAdapter mDbAdapter;
    EditText mTitle;
    DatePicker mDate;
    Spinner mCategory;
    ArrayAdapter<CharSequence>  adapter;
    public static final int INSERT_ID = Menu.FIRST;
    public static final int UPDATE_ID = Menu.FIRST + 1;
    public static final int DELETE_ID = Menu.FIRST + 2;
    private long id;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mDbAdapter = new DBAdapter(this);
        mDbAdapter.open();
        fillData();

        mTitle = (EditText)findViewById(R.id.txtTask);
        mDate = (DatePicker)findViewById(R.id.dtpDate);
        mCategory = (Spinner)findViewById(R.id.spCategory);
        adapter = ArrayAdapter.createFromResource(this, R.array.biz_categories, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mCategory.setAdapter(adapter);
    }

    public void fillData()
	{
		Cursor c = mDbAdapter.fetchAllBiz();
		startManagingCursor(c);
		String []from = new String[]{DBAdapter.KEY_TITLE,DBAdapter.KEY_START_DATE,DBAdapter.KEY_CATEGORY};
		int [] to = new int[]{R.id.text1};
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, c, from, to);
		setListAdapter(adapter);
	}

    public String getDate()
    {
    	int year = mDate.getYear();
		int month = mDate.getMonth();
		int day = mDate.getDayOfMonth();

		String a  = String.valueOf(year);
		String b  = String.valueOf(month);
		String c  = String.valueOf(day);

		return  a + "/" + b + "/" + c;
    }
    public void create()
	{
		String title = mTitle.getText().toString();
		String date = getDate();
		String category = mCategory.getSelectedItem().toString();
		mDbAdapter.createBiz(title, date, category);
		fillData();
	}

	public void update()
	{
		String title = mTitle.getText().toString();
		String date = getDate();
		String category = mCategory.getSelectedItem().toString();
		mDbAdapter.updateBiz(id, title, date, category);
		fillData();
	}

	public void delete()
	{
		mDbAdapter.deleteBiz(id);
		fillData();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, INSERT_ID, 0, R.string.add);
		menu.add(0, UPDATE_ID, 0, R.string.update);
		menu.add(0, DELETE_ID, 0, R.string.delete);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId())
		{
		case INSERT_ID:
			create();
			return true;
		case UPDATE_ID:
			update();
			return true;
		case DELETE_ID:
			delete();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		this.id = id;
		Cursor c = mDbAdapter.fetchBiz(id);
		mTitle.setText(c.getString(
                c.getColumnIndexOrThrow(DBAdapter.KEY_TITLE)));

		String category = c.getString(
                c.getColumnIndexOrThrow(DBAdapter.KEY_CATEGORY));
		ArrayAdapter<CharSequence> myAdap = (ArrayAdapter<CharSequence>) mCategory.getAdapter(); //cast to an ArrayAdapter

		int spinnerPosition = myAdap.getPosition(category);
		mCategory.setSelection(spinnerPosition);

		//display date
		String date = c.getString(c.getColumnIndexOrThrow(DBAdapter.KEY_START_DATE));
        StringTokenizer tokens = new StringTokenizer(date,"/");
        int arr[] = new int[3];
        int i=0;

        while(tokens.hasMoreTokens())
        {
        	arr[i] = Integer.valueOf(tokens.nextToken());
        	i++;
        }

        mDate.updateDate(arr[0], arr[1], arr[2]);
	}

}

 
Leave a comment

Posted by on May 9, 2012 in Android

 

Tags: ,

Database Helper Class for Android

package com.my.first;
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.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Shader.TileMode;
import android.util.Log;

public class DBAdapter {
public static final String KEY_ROWID = "songId";
public static final String KEY_TITLE = "title";
public static final String KEY_TYPE = "type";
public static final String KEY_SIZE = "size";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "music";
private static final String DATABASE_TABLE = "songs";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table songs (songId integer primary key autoincrement, "
+ "title varchar not null, type varchar not null, "
+ "size float not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}

private  static class DatabaseHelper extends SQLiteOpenHelper
{

public DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);

}

@Override
public void onCreate(SQLiteDatabase db) {

db.execSQL(DATABASE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS songs");
onCreate(db);
}



}

//---opens the database---
public DBAdapter open()
{
try
{
db = DBHelper.getWritableDatabase();

}
catch(SQLException ex)
{

}
return this;
}

//---closes the database---
public void close()
{
DBHelper.close();
}

//---insert a song into the database---
public long insertTitle(String title, String type, String size)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_TYPE, type);
initialValues.put(KEY_SIZE, size);
return db.insert(DATABASE_TABLE, null, initialValues);
}

//---deletes a particular title---
public boolean deleteTitle(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID +
"=" + rowId, null) > 0;
}

//---retrieves all the titles---
public Cursor getAllSongTitles()
{
return db.query(DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_TITLE,
KEY_TYPE,
KEY_SIZE},
null,
null,
null,
null,
null);
}

//---retrieves a particular title---
public Cursor getSongTitle(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_TITLE,
KEY_TYPE,
KEY_SIZE
},
KEY_ROWID + "=" + rowId,
null,
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}


//---updates a title---
public boolean updateSongTitle(long rowId, String title,
String type, String size)
{
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_TYPE, type);
args.put(KEY_SIZE, size);
return db.update(DATABASE_TABLE, args,
KEY_ROWID + "=" + rowId, null) > 0;
}

}


 
Leave a comment

Posted by on February 28, 2012 in Android

 

Tags: ,

Create SQLite Database in Android

package com.my.first;

import android.R.string;
 import android.app.Activity;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.os.Bundle;
 import android.util.Log;

public class DatabaseActivity extends Activity {

@Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);

SQLiteDatabase db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
 db.execSQL("CREATE TABLE IF NOT EXISTS MyTable (FirstName VARCHAR,LastName VARCHAR,Age INT(3))");
 db.execSQL("INSERT INTO MyTable VALUES('Josh','Fedric',23)");

Cursor c = db.rawQuery("SELECT * FROM MyTable", null);
 c.moveToFirst();
 String msg = c.getString(c.getColumnIndex("FirstName"));
 Log.d("Fname",msg);

}
 }

 
Leave a comment

Posted by on February 28, 2012 in Android

 

Tags: ,