Saturday, April 27, 2013

How to use multiple databases dynamically for one model in CakePHP

I put in the app/Controller/AppModel.php

class AppModel extends Model
{
  /**
   * Connects to specified database
   *
   * @param String name of different database to connect with.
   * @param String name of existing datasource
   * @return boolean true on success, false on failure
   * @access public
   */
    public function setDatabase($database, $datasource = 'default')
    {
      $nds = $datasource . '_' . $database;      
      $db  = &ConnectionManager::getDataSource($datasource);

      $db->setConfig(array(
        'name'       => $nds,
        'database'   => $database,
        'persistent' => false
      ));

      if ( $ds = ConnectionManager::create($nds, $db->config) ) {
        $this->useDbConfig  = $nds;
        $this->cacheQueries = false;
        return true;
      }

      return false;
    }
}

And here is how I used it in my app/Controller/CarsController.php:
class CarsController extends AppController
{
  public function index()
  {
    $this->Car->setDatabase('cake_sandbox_client3');
 
    or you can directly use:
    $this->Car->setDataSource('test1'); 
    /* data source name from cofig/database.php */

    $cars = $this->Car->find('all');

    $this->set('cars', $cars);
  }

}

http://stackoverflow.com/questions/13223946/how-to-use-multiple-databases-dynamically-for-one-model-in-cakephp

Php making a soap based wsdl server

First create a wsdl file under www/soap/ directory named suppose soap1.wsdl:

<?xml version="1.0"?>
<definitions name="WsdlSoap" targetNamespace="urn:WsdlSoap"
             xmlns:tns="urn:WsdlSoap" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
             xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
             xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
             xmlns="http://schemas.xmlsoap.org/wsdl/">

    <message name="getMyName">
        <part name="name" type="string"/>
    </message>
    <message name="getMyNameResponse">
        <part name="return" type="string"/>
    </message>
    <portType name="WsdlSoapPort">
        <operation name="getMyName">
            <input message="tns:getMyName"/>
            <output message="tns:getMyNameResponse"/>
        </operation>
    </portType>
    <binding name="WsdlSoapBinding" type="tns:WsdlSoapPort">
        <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="getMyName">
            <soap:operation soapAction="urn:WsdlSoapAction"/>
            <input>
                <soap:body use="encoded" namespace="urn:WsdlSoap" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
            </input>
            <output>
                <soap:body use="encoded" namespace="urn:WsdlSoap" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
            </output>
        </operation>
    </binding>
    <service name="WsdlSoapService">
        <port name="WsdlSoapPort" binding="tns:WsdlSoapBinding">
            <soap:address location="http://localhost/soap/server1.php"/>
        </port>
    </service>
</definitions>

/soap/server1.php

<?php
function getMyName($name)
{

    return "Your name: ".$name;

}

$server = new SoapServer("soap1.wsdl");

$server->addFunction("getMyName");

$server->handle();
?>

Call soap:
$soap = new SoapClient("http://localhost/soap/soap1.wsdl");
echo $soap-> getMyName ("Pritom Kumar");
And it prints: "Your name: Pritom Kumar".

Friday, April 26, 2013

Android, show list of items and bind click on list items

Call list item intent from your application class:
Intent intent = new Intent(MyFirstAppActivity.this, LentList.class);
startActivity(intent);

Here, MyFirstAppActivity is the main class and LentList is the class where list items would show.

First, create a layout file under layout folder, such named list.xml and paste the following content:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content" />
</LinearLayout>

Now create LentIist.java class:
public class LentList extends ListActivity

private ArrayList<LentPerson> liLentPerson;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list);
    this.generateLentPersons();
    setListAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1, liLentPerson.toArray()));
}

Function: generateLentPersons() is as following:
private ArrayList<Person> getPersons() {
    ArrayList<Person> liPerson = new ArrayList<Person>();
    person = new Person(1, "Pritom Kumar", "Software Engineer", "KU");
    return liPerson;
}
Function MyAdapter is as following:
private class MyAdapter extends ArrayAdapter<Object> {
	public MyAdapter(Context context, int resource, Object[] persons) {
		super(context, resource, persons);
	}
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View row = inflater.inflate(R.layout.list_each, parent, false);	
		LentPerson p = (Person) getItem(position);
		
		TextView textView1 = (TextView) row.findViewById(R.id.textView1);
		TextView textView2 = (TextView) row.findViewById(R.id.textView2);	
		TextView textView3 = (TextView) row.findViewById(R.id.textView3);
		
		textView1.setText(p.getName()); /* Pritom Kumar */
		textView2.setText(p.getDesignation()); /* Software Engineer */
		textView3.setText(p.getUniversity()); /* KU */
                /* Bind event on row click */
		row.setOnClickListener(new OnItemClickListener(p));
		return row;
	}
} 
 

Layout file list_each.xml as following:
<?xml version="1.0" encoding="UTF-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/tableLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Small Text"
            android:textAppearance="?android:attr/textAppearanceSmall" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Small Text"
            android:textAppearance="?android:attr/textAppearanceSmall" />

    </TableLayout>
    
Function OnItemClickListener is as following:
private class OnItemClickListener implements OnClickListener{
	private LentPerson p;
	public OnItemClickListener(LentPerson p) {
		this.p = p;
	}
	public void onClick(View arg0) {
		Toast.makeText(LentList.this, p.getName(), Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(LentList.this, PersonDetails.class);
		intent.putExtra("personId", p.getId());
		intent.putExtra("txtName", p.getName());
		intent.putExtra("txtBorrower", p.getborrower());
		intent.putExtra("txtCategory", p.getCategory());
		startActivity(intent);
	} 
}

Java class  PersonDetails is as following:
package com.pkm.andrd;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class PersonDetails extends Activity {
	private TextView textView2;
	private TextView textView4;
	private TextView textView6;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.persondetails);
		
		textView2 = (TextView) findViewById(R.id.textView2);
		textView4 = (TextView) findViewById(R.id.textView4);
		textView6 = (TextView) findViewById(R.id.textView6);

		textView2.setText(getIntent().getExtras().getString("txtName"));
		textView4.setText(getIntent().getExtras().getString("txtBorrower"));
		textView6.setText(getIntent().getExtras().getString("txtCategory"));
	}
}
Layout  R.layout.persondetails is as following:
<?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/textView7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/s2610132158"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >




            <TextView
                android:id="@+id/textView1"
            android:layout_width="90dp"
                android:layout_height="wrap_content"
                android:text="@string/Name"
                android:textAppearance="?android:attr/textAppearanceMedium" />

        </LinearLayout>



        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

    </TableRow>



    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >



        <TextView
            android:id="@+id/textView3"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:text="@string/borrower"
            android:textAppearance="?android:attr/textAppearanceMedium" />



        <TextView
            android:id="@+id/textView4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >


        <TextView
            android:id="@+id/textView5"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:text="@string/category"
            android:textAppearance="?android:attr/textAppearanceMedium" />



        <TextView
            android:id="@+id/textView6"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

    </LinearLayout>

</LinearLayout>

Make sure you have the following entry in your manifest file under application tag:
<activity android:name=".LentList" />
<activity android:name=".PersonDetails" />

how to make second layout xml file in android with graphical tab

Make sure you open the layout XML in Eclipse using the "Android Layout Editor": right-click (or if on a Mac, ctrl-click) the layout file, then select "Open With..." and "Android Layout Editor".

Pass arguments or data from one activity class to another activity class android

Suppose you are in activity class `First` that take some input such as your name and roll number and type of student.
Now you want to show them in another activity class `Second`.

First get name and roll number and type of student from text box and.

EditText txtName = (EditText) findViewById(R.id.txtName);
EditText txtRoll = (EditText) findViewById(R.id.txtRoll);

Spinner m_myDynamicSpinner;
ArrayAdapter<CharSequence> m_adapterForSpinner;
m_myDynamicSpinner = (Spinner) findViewById(R.id.dynamicSpinner);
m_adapterForSpinner = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
m_adapterForSpinner.add("Student");
m_adapterForSpinner.add("Ex-student");
m_adapterForSpinner.add("Employee");
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);

Now call `Second` activity by this way:

Intent intent = new Intent(First.this, Second.class);
intent.putExtra("txtName", txtName.getText().toString());
intent.putExtra("txtRoll", txtRoll.getText().toString());
intent.putExtra("txtStudentType", m_myDynamicSpinner.getSelectedItem().toString());
startActivity(intent);

And get the values from `Second`  activity class by:
getIntent().getExtras().getString("txtName");
getIntent().getExtras().getString("txtRoll");
getIntent().getExtras().getString("txtStudentType");

Android Writing your own Content provider

You start by sub-classing ContentProvider. Since ContentProvider is an abstract class you have to implement the five abstract methods. These methods are explained in detail later on, for now simply use the stubs created by Eclipse (or whatever tool you use).
Implementing a content provider involves always the following steps:
  1. Create a class that extends ContentProvider
  2. Define the authority
  3. Define the URI or URIs
  4. Create constants to ease client-development
  5. Implement the getType() method
  6. Implement the CRUD-methods
  7. Add the content provider to your AndroidManifest.xml
The abstract methods you have to implement
Method Usage
getType(Uri) Returns the MIME type for this URI
delete(Uri uri, String selection, String[] selectionArgs) Deletes records
insert(Uri uri, ContentValues values) Adds records
query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) Return records based on selection criteria
update(Uri uri, ContentValues values, String selection, String[] selectionArgs) Modifies data

Notifying listeners of dataset changes

Clients often want to be notified about changes in the underlying datastore of your content provider. So inserting data, as well as deleting or updating data should trigger this notification.
That’s why I used the following line in the code sample above:
getContext().getContentResolver().notifyChange(uri, null); 

Configuring your content provider

As with any component in Android you also have to register your content provider within the AndroidManifest.xml file. The next code sample shows a typical example configuration for a content provider.
<provider
android:name="pritom.kumar.content.provider.LentItemsProvider"
android:authorities="pritom.kumar.content.provider"
android:grantUriPermissions="true"/>


Your own content provider class should look like this:
 
package pritom.kumar.content.provider;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.net.Uri;

public class LentItemsProvider extends ContentProvider {
	private SQLiteDatabase db;
	private DataHandler dataHandler;
	// public constants for client development
	public static final String AUTHORITY = "pritom.kumar.content.provider";
	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + LentItems.CONTENT_PATH);

	// helper constants for use with the UriMatcher
	private static final int LENTITEM_LIST = 1;
	private static final int LENTITEM_ID = 2;
	private static final UriMatcher URI_MATCHER;
	
	public static interface LentItems extends BaseColumns {
		public static final String DATABASE_NAME = "reminders.db";
		public static final String DATABASE_TABLE_NAME = "reminders";
		public static final int DATABASE_VERSION = 1;
		public static final Uri CONTENT_URI = LentItemsProvider.CONTENT_URI;
		public static final String NAME = "name";
		public static final String CATEGORY = "category";
		public static final String BORROWER = "borrower";
		public static final String CONTENT_PATH = "items";
		public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/LentItemsProvider";
		public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/LentItemsProvider";
		public static final String[] PROJECTION_ALL = {_ID, NAME, CATEGORY, BORROWER};
		public static final String SORT_ORDER_DEFAULT = NAME + " ASC";
	}

	// prepare the UriMatcher
	static {
	   URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
	   URI_MATCHER.addURI(AUTHORITY, LentItems.CONTENT_PATH, LENTITEM_LIST);
	   URI_MATCHER.addURI(AUTHORITY, LentItems.CONTENT_PATH + "/#", LENTITEM_ID);
	}
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		int delCount = 0;
		   switch (URI_MATCHER.match(uri)) {
		      case LENTITEM_LIST:
		         delCount = db.delete(DataHandler.TBL_ITEMS, selection, selectionArgs);
		         break;
		      case LENTITEM_ID:
		         String idStr = uri.getLastPathSegment();
		         String where = LentItems._ID + " = " + idStr;
		         if (!TextUtils.isEmpty(selection)) {
		            where += " AND " + selection;
		         }
		         delCount = db.delete(DataHandler.TBL_ITEMS, where, selectionArgs);
		         break;
		      default:
		         throw new IllegalArgumentException("Unsupported URI: " + uri);
		   }
		   // notify all listeners of changes:
		   if (delCount > 0) {
		      getContext().getContentResolver().notifyChange(uri, null);
		   }
		   return delCount;
	}

	@Override
	public String getType(Uri uri) {
		switch (URI_MATCHER.match(uri)) {
	      case LENTITEM_LIST:
	         return LentItems.CONTENT_TYPE;
	      case LENTITEM_ID:
	         return LentItems.CONTENT_ITEM_TYPE;
	      default:
	         throw new IllegalArgumentException("Unsupported URI: " + uri);
	   }
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		if (URI_MATCHER.match(uri) != LENTITEM_LIST) { 
		      throw new IllegalArgumentException("Unsupported URI for insertion: " + uri); 
		   } 
		if(db == null) {
			System.out.println(" DB NULL ");
		}
		System.out.println(values.size());
		   long id = db.insert(DataHandler.TBL_ITEMS, null, values); 
		   if (id > 0) { 
		      // notify all listeners of changes and return itemUri: 
		      Uri itemUri = ContentUris.withAppendedId(uri, id); 
		      getContext().getContentResolver().notifyChange(itemUri, null); 
		      return itemUri; 
		   } 
		   // s.th. went wrong: 
		   throw new SQLException("Problem while inserting into " + DataHandler.TBL_ITEMS + ", uri: " + uri); // use another exception here!!!
	}

	@Override
	public boolean onCreate() {
		dataHandler = new DataHandler(getContext());
		db = dataHandler.getWritableDatabase();
		System.out.println("LentItemsProivider onCreate done. Data base is "+(db==null?"null":"not null")+".");
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { 
		SQLiteQueryBuilder builder = new SQLiteQueryBuilder(); 
		builder.setTables(DataHandler.TBL_ITEMS); 
		if (TextUtils.isEmpty(sortOrder)) { 
		   sortOrder = LentItems.SORT_ORDER_DEFAULT; 
		} 
		System.out.println("HERE IN query matcher: "+URI_MATCHER.match(uri));
		switch (URI_MATCHER.match(uri)) { 
		   case LENTITEM_LIST: 
		      // all nice and well 
		      break; 
		   case LENTITEM_ID: 
		      // limit query to one row at most: 
		      builder.appendWhere(LentItems._ID + " = " + uri.getLastPathSegment()); 
		      break; 
		   default: 
		      throw new IllegalArgumentException("Unsupported URI: " + uri); 
		}
		Cursor cursor = builder.query(db, projection, selection, selectionArgs, null, null, sortOrder); 
		// if we want to be notified of any changes: 
		cursor.setNotificationUri(getContext().getContentResolver(), uri); 
		return cursor; 
} 


	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		int updateCount = 0; 
		   switch (URI_MATCHER.match(uri)) { 
		      case LENTITEM_LIST: 
		         updateCount = db.update(DataHandler.TBL_ITEMS, values, selection, selectionArgs); 
		         break; 
		      case LENTITEM_ID: 
		         String idStr = uri.getLastPathSegment(); 
		         String where = LentItems._ID + " = " + idStr; 
		         if (!TextUtils.isEmpty(selection)) { 
		         where += " AND " + selection; 
		         } 
		         updateCount = db.update(DataHandler.TBL_ITEMS, values, where, selectionArgs); 
		         break; 
		      default: 
		         throw new IllegalArgumentException("Unsupported URI: " + uri); 
		   } 
		   // notify all listeners of changes: 
		   if (updateCount > 0) {
		      getContext().getContentResolver().notifyChange(uri, null); 
		   }
		   return updateCount; 
	}

}
Your DataHandler class should look like this:
package pritom.kumar.content.provider;

import pritom.kumar.content.provider.LentItemsProvider.LentItems;

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

public class DataHandler extends SQLiteOpenHelper {
	private String DATABASE_CREATE_SCHEMA = "create table "
		+ LentItems.DATABASE_TABLE_NAME + " (" + LentItems._ID
		+ " integer primary key autoincrement, " + LentItems.NAME
		+ " text not null, " + LentItems.CATEGORY + " text not null, " + LentItems.BORROWER+" text not null );";
	
	public DataHandler(Context context) {
		super(context, LentItems.DATABASE_NAME, null, LentItems.DATABASE_VERSION);
	}

	public static final String DEFAULT_TBL_ITEMS_SORT_ORDER = "ASC";
	private SQLiteDatabase db;
	public static final String TBL_ITEMS = LentItems.DATABASE_TABLE_NAME;

	@Override
	public void onCreate(SQLiteDatabase arg0) {
		if(arg0 == null) {
			System.out.println("Database is null on create.");
		} else {
			System.out.println("Database is not null on create.");
		}
		db = arg0;
		db.execSQL(DATABASE_CREATE_SCHEMA);
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}	
}

Use your own custom provider by this code follow:

<?php 
Bind your content provider on create, update and delete mode.
Follow the link for details. 
getContentResolver().registerContentObserver(LentItems.CONTENT_URI, true, new MyObserver(null)); 
 
/* Get your ContentResolver class */ 
ContentResolver resolver = getContentResolver(); 
 
/* Create content values to insert */ 
ContentValues values = new ContentValues();
values.put(LentItems.NAME, "Software Engineer Basic");
values.put(LentItems.BORROWER, "Pritom Kumar");
values.put(LentItems.CATEGORY, "Computer Science And Engineering");
System.out.println("Row insert id: "+resolver.insert(LentItems.CONTENT_URI, values));

/* Get All data from content provider */
String[] PROJECTION=new String[] {
		LentItems.BORROWER,
		LentItems.NAME,
		LentItems.CATEGORY,
		LentItems._ID
    };
Cursor c = resolver.query(LentItemsProvider.CONTENT_URI, PROJECTION, null, null, null);
if (c == null){
	System.out.println("NULL");
}
else{
	while (c.moveToNext()) 
    {      
        String s1 = c.getString(c.getColumnIndex(LentItems._ID));
        String s2 = c.getString(c.getColumnIndex(LentItems.NAME));
        String s3 = c.getString(c.getColumnIndex(LentItems.CATEGORY));
        String s4 = c.getString(c.getColumnIndex(LentItems.BORROWER));
        System.out.println(s1+", "+s2+", "+s3+", "+s4);	
    }
}
?>

Thursday, April 25, 2013

Listing all the folders subfolders and files in a directory using php

List of all files under directory and also its subdirectories recursively.

function listFolderFiles($dir){
    $ffs = scandir($dir);
    echo '<ol>';
    foreach($ffs as $ff){
        if($ff != '.' && $ff != '..'){
            echo '<li>'.$ff;
            if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
            echo '</li>';
        }
    }
    echo '</ol>';
}

listFolderFiles(dirname(__FILE__)'/Main Dir');


dirname(__FILE__) gives you the file name where you are.