Tuesday, February 28, 2012

Database Helper Class for Android



[sourcecode language="java"]
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;
}

}


[/sourcecode]

Create SQLite Database in Android



[sourcecode language="java"]
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);

}
}

[/sourcecode]

Wednesday, February 15, 2012

Asynchronous communication with delegates

Compiler generate a new class for each delegate declaration. Following class is compiler-generated for the above delegate.

[sourcecode language="csharp"]
private sealed class MyDelegate : MulticastDelegate
{
public extern MyDelegate(object object, IntPtr method);
public extern virtual int Invoke(int x,int y);
public extern virtual IAsyncResult BeginInvoke(int x, int y
AsyncCallback callback, object object);
public extern virtual int Endinvoke((IAsyncResult result);
}
[/sourcecode]


This class consists of delegate constructor MyDelegate(..) , Invoke (..) , BeginInvoke(..) and EndInvoke(..)

  • Delegate constructor runs when the delegate is instanciated. MyDelegate is instanciated as follows.


MyDelegate del;
This del reference is used to point a matching method.

  •   Invoke method accepts the same parameter list similar to the original function.



  •   BeginInvoke method requires all the in params , in-out params in the function definition. Furthermore, it needs AsyncCallback object and Object type reference.


calling BeginInvoke() causes to make an asynchronous call to the original method. The result is an IAsyncResult.

  •   After method execution completed, EndInvoke() is called passing all the in-out params , out params in the function definition. EndInvoke() requires the above IasyncResult.


Now let’s turn to asynchronius communication. When a delegate makes an asynchronius call to a method , the execution of the method does ont occur in the same thread. A separate thread is allocated for method execution. Caller thread waits until callie thread returns the result. These facts are justified by following code example.

[sourcecode language="csharp"]
using System;
using System.Threading;
public class Program {
public delegate int TheDelegate( int x, int y);
static int ShowSum( int x, int y ) {
int sum = x + y;
Console.WriteLine("Thread #{0}: ShowSum() Sum = {1}",
Thread.CurrentThread.ManagedThreadId, sum);
return sum;
}
public static void Main() {
TheDelegate d = ShowSum;
IAsyncResult ar = d.BeginInvoke(10, 10, null, null);
int sum = d.EndInvoke(ar);
Console.WriteLine("Thread #{0}: Main() Sum = {1}",
Thread.CurrentThread.ManagedThreadId, sum);
}
}
[/sourcecode]

 

 

Synchronous communication with delegates

Delegates are special types supported by the .NET Framework. It is a pointer to a function. A delegate pointing to a function has the same method signature as the function. Delegates are special classes. Delegates can be instanciated. Therefore we have delegate objects. A delegate object is a reference to one or more methods (static or instance).

In C# , delegate declaration as follows.

public delegate int MyDelegate(int x, int y);

This delegate can be used as reference to any method which accepts two integer parameters and has the return type of int.

An example that uses MyDelegate delegate

[sourcecode language="csharp"]

namespace del
{
public delegate int MyDelegate(int num1,int num2);
class A
{
public int sum(int num1, int num2)
{
return num1 + num2;
}
}

class Program
{
static void Main(string[] args)
{
A a = new A();
MyDelegate del = a.sum;
Console.ReadLine();
}
}
}

[/sourcecode]

Here , delegate makes  a synchronous call to the function. In other words, function call is not asynchronous.
All the work related to calling sum(int a,int b) happens in the main thread.
Synchronous communication is based on single thread concept.
In above example, delegate calls sum(int a,int b)  and then the main thread blocks   until sum() method execution completes.   Therefore this thread can not execute any other code until method  execution is over.
It is obvious that synchronous communication is not preferred for User interfaces. In a user interface, UI responsiveness is highly considered. If all the work is maintained in a single thread, there is a chance for the UI to get stuck.

The following code verifies above function call is synchronous.  The resulting thread ids are similar.

[sourcecode language="csharp"]
namespace del
{
public delegate void MyDelegate();

class A
{
public void sum()
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
}

class Program
{
static void Main(string[] args)
{
A a = new A();
MyDelegate del = a.sum;
del();
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
//IAsyncResult rs = del.BeginInvoke(20, 10, null, null);
//string ans  = del.EndInvoke(rs);
//Console.WriteLine("Answer is {0}", ans);
Console.ReadLine();
}
}
}
[/sourcecode]

Monday, January 23, 2012

Display an Alert Dialog

[sourcecode language="java"]
package com.my.option;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class OptionMenuActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
AlertDialog.Builder builder = new AlertDialog.Builder(OptionMenuActivity.this);
builder.setMessage("Do you really need to exit?");
builder.setCancelable(false);

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface arg0, int arg1) {
OptionMenuActivity.this.finish();

}
});

builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.cancel();

}

});

AlertDialog alert = builder.create();
alert.show();
}
});
}

}

[/sourcecode]

How to add a context menu in Android


  1. Create an Android XML file of Menu type

  2. Add menu options as you preferred. Each menu option should be indicated as <item> XML element.

  3. This is my context_menu.xml file.[sourcecode language="xml"]
    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/item1"   android:title="option1"></item>
    <item android:id="@+id/item2"   android:title="option2"></item>
    </menu>
    [/sourcecode]

  4. Override onCreateContextMenu and onContextItemSelected in your Activity.java file
    Add a button in main.xml to respond our context menu.
    [sourcecode language="java"]
    package com.my.option;

    import java.util.zip.Inflater;
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.ContextMenu;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ContextMenu.ContextMenuInfo;
    import android.widget.Button;

    public class ContextMenuActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button b = (Button) findViewById(R.id.button1);
    registerForContextMenu(b);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
    ContextMenuInfo menuInfo) {

    MenuInflater inflator = getMenuInflater();
    inflator.inflate(R.menu.context_menu, menu);

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
    if(item.getItemId() == R.id.item1)
    Log.d("Edit", "Selected : Edit Option");
    if(item.getItemId() == R.id.item2)
    Log.d("Delete", "Selected : Delete Option");
    return super.onContextItemSelected(item);
    }
    }
    [/sourcecode]

Simple Options Menu in Android


  1. Create an Android XML file of Menu type

  2. Add menu options as you preferred. Each menu option should be indicated as <item> XML element.

  3. This is my options.xml file.[sourcecode language="xml"]
    <!--?xml version=<em--><?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:id="@+id/item1" android:title="Edit" android:icon="@android:drawable/ic_menu_edit"></item>
    <item android:id="@+id/item2" android:title="Delete" android:icon="@android:drawable/ic_menu_delete"></item>
    <item android:id="@+id/item3" android:title="Help" android:icon="@android:drawable/ic_menu_help"></item>
    <item android:id="@+id/item4" android:title="More" android:icon="@android:drawable/ic_menu_more"></item>


    </menu>
    [/sourcecode]

  4. My options menu is not just text-based. Each menu item is displayed with a relevant icon. Here I used the icons found in the Android.jar file of my project. You can find such icons using this path
    <app root > --> Android <Your Android platform>  --> android.jar --> res --> drawable-hdpi(icons for menu prefixed with ic_menu)

  5. Override onCreateOptionsMenu and onOptionsItemSelected in your Activity.java file
    [sourcecode language="java"]
    package com.my.option;

    import java.io.Console;
    import java.util.zip.Inflater;

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;

    public class OptionMenuActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflator = getMenuInflater();
    inflator.inflate(R.menu.options, menu);
    return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId() == R.id.item1)
    Log.d("Edit", "Selected : Edit Option");
    if(item.getItemId() == R.id.item2)
    Log.d("Delete", "Selected : Delete Option");
    return super.onOptionsItemSelected(item);
    }
    }
    [/sourcecode]

Saturday, January 7, 2012

Write Data in XML File Using C#

Sample XML File

[sourcecode language="xml"]
<?xml version="1.0" encoding="utf-8"?>

<DoctorInfo>

&nbsp;

<Doctor>

<id>01</id>

<name>Ranil Jayaweera</name>

<speciality>GI</speciality>

</Doctor>

&nbsp;

<Doctor>

<id>02</id>

<name>Aruna Gunathilaka</name>

<speciality>VP</speciality>

</Doctor>

&nbsp;

<Doctor>

<id>03</id>

<name>Jaya Palipana</name>

<speciality>VOG</speciality>

</Doctor>

&nbsp;

</DoctorInfo>
[/sourcecode]

The Code

[sourcecode language="csharp"]
XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(Application.StartupPath + "\\DoctorsList.xml");

XmlElement subroot = xmlDoc.CreateElement("Doctor");

&nbsp;

XmlElement childElementId = xmlDoc.CreateElement("id");

XmlText xmlTextId = xmlDoc.CreateTextNode(txtid.Text);

childElementId.AppendChild(xmlTextId);

subroot.AppendChild(childElementId);

xmlDoc.DocumentElement.AppendChild(subroot);

&nbsp;

XmlElement childElementName = xmlDoc.CreateElement("name");

XmlText xmlTextName = xmlDoc.CreateTextNode(txtName.Text);

childElementName.AppendChild(xmlTextName);

subroot.AppendChild(childElementName);

xmlDoc.DocumentElement.AppendChild(subroot);

&nbsp;

XmlElement childElementSpeciality = xmlDoc.CreateElement("speciality");

XmlText xmlTextSpeciality = xmlDoc.CreateTextNode(cbspecial.Text);

childElementSpeciality.AppendChild(xmlTextSpeciality);

subroot.AppendChild(childElementSpeciality);

xmlDoc.DocumentElement.AppendChild(subroot);

&nbsp;

xmlDoc.Save(Application.StartupPath + "\\DoctorsList.xml");
[/sourcecode]

Read Data from XML File Using C#

Sample XML File

[sourcecode language="xml"]
<?xml version="1.0" encoding="utf-8"?>

<PatientInfo>

<Patient id=”1”>

<app-no>03</app-no>

<fname>Brian</fname>

<lname>Marsh</lname>

<docId>03</docId>

</Patient>

<Patient id=”2”>>

<app-no>02</app-no>

<fname>Bron</fname>

<lname>Marini</lname>

<docId>01</docId>

</Patient>

</PatientInfo>

[/sourcecode]

The Code

[sourcecode language="csharp"]
XmlDocument doc = new XmlDocument();

doc.Load("files/sampleXML.xml");

&nbsp;

XmlNodeList patientList = doc.GetElementsByTagName("Patient ");

&nbsp;

foreach (XmlNode node in patientList)

{

XmlElement patientElement = (XmlElement) node;

&nbsp;

string first_name = patientElement.GetElementsByTagName("fname")[0].InnerText;

string last_name = patientElement.GetElementsByTagName("lname")[0].InnerText;

string patient_id = "";

&nbsp;

if (patientElement.HasAttributes)

{

patient_id  = patientElement.Attributes["id"].InnerText;

}

&nbsp;

Console.WriteLine("{0} ({1})  {2}\n", first_name, last_name, patient_id);

}

[/sourcecode]

Delete Data from XML File Using C#

Sample XML File

[sourcecode language="xml"]
<?xml version="1.0" encoding="utf-8"?>

<DoctorInfo>

<Doctor>

<id>01</id>

<name>Ranil Jayaweera</name>

<speciality>GI</speciality>

</Doctor>

<Doctor>

<id>02</id>

<name>Aruna Gunathilaka</name>

<speciality>VP</speciality>

</Doctor>

<Doctor>

<id>03</id>

<name>Jaya Palipana</name>

<speciality>VOG</speciality>

</Doctor>

</DoctorInfo>
[/sourcecode]


The Code

[sourcecode language="csharp"]
XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(Application.StartupPath + "\\DoctorsList.xml");

XmlNode rootNode = xmlDoc.SelectSingleNode("//DoctorInfo");

XmlNodeList doctorList = rootNode.SelectNodes("Doctor");

for (int i = 0; i < doctorList.Count; i++)

{

if (doctorList[i].SelectSingleNode("id").InnerText.Equals(“03”))

{

rootNode.RemoveChild(doctorList[i]);

xmlDoc.Save(Application.StartupPath + "\\DoctorsList.xml");

}

}
[/sourcecode]

Adding audio with HTML

[sourcecode language="html"]
<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"
codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="200" height="16">

<param name="src" value="fileName.mp3" />
<param name="controller" value="true" />
<param name="autoplay" value="false" />
<param name="autostart" value="0" />
<param name="pluginspage" value="http://www.apple.com/quicktime/download/" />

<!--[if !IE]> <-->

<object type="audio/x-mpeg" data="fileName.mp3" width="200" height="16">
<param name="src" value="fileName.mp3" />
<param name="controller" value="true" />
<param name="autoplay" value="false" />
<param name="autostart" value="0" />
<param name="pluginurl" value="http://www.apple.com/quicktime/download/" />

</object>

<!--> <![endif]-->

</object>

[/sourcecode]

IE and non-IE browsers treat audio objects in a web page two different ways. Therefore <Object> should be used carefully in order to play the audio in all browsers perfectly. In the code, there are two sections for IE and other browsers like FF.

IE looks for class Id before playing audio.  But other browsers do not use this attribute. They rely on the MIME type of the audio object. In the above code commented section is used by non IE  browsers to play audio.

Some Other sound formats

  • au (type="audio/basic")

  • wav (type="audio/wav" or "audio/x-wav")

  • ra (type="audio/x-pn-realaudio")

  • mp3 (type="audio/x-mpeg")

  • wma (type="audio/x-ms-wma")


Alternatives for class Id

  •  Quicktime player: classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab"

  • Windows media Player: classid="clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/ nsmp2inf.cab#Version=6,0,02,902"

  • Real Audio: id=RVOCX classid="clsid:CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA"

  • Flash Shockwave Player : classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
    codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/ swflash.cab#version=8,0,22,0"

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...