dirname(Yii::app()->request->scriptFile)
Tuesday, April 30, 2013
CGridView a CLinkColumn with sortable header using yii
I have it working with the latest yii (non-stable but might work with the current stable release). (could do with some improvement but it does what I need)
Try this; create a new component under components/SCLinkColumnWithSort.php
Try this; create a new component under components/SCLinkColumnWithSort.php
<?php class SCLinkColumnWithSort extends CLinkColumn { public $name; public $sortable = true; public $filter; protected function renderFilterCellContent() { $this->linkHtmlOptions['class'] = $this->name; if($this->filter!==false && $this->grid->filter!==null && strpos($this->name,'.')===false) { if(is_array($this->filter)) echo CHtml::activeDropDownList($this->grid->filter, $this->name, $this->filter, array('id'=>false,'prompt'=>'')); else if($this->filter===null) echo CHtml::activeTextField($this->grid->filter, $this->name, array('id'=>false)); else echo $this->filter; } else parent::renderFilterCellContent(); } protected function renderHeaderCellContent() { if($this->grid->enableSorting && $this->sortable && $this->name!==null) echo $this->grid->dataProvider->getSort()->link($this->name,$this->header); else parent::renderHeaderCellContent(); } } ?>
Use this as following:
<?php $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider' => $dataProvider, 'columns' => array( array( 'class' => 'SCLinkColumnWithSort', 'name' => 'column_name_to_sort', ) ) )) ?>
Or you can directly use, but upper one used for more customization:
array( 'name' => 'mobile_number', 'type' => 'raw', 'value' => 'CHtml::link($data->mobile_number,$data->contact_id)' )
Where mobile_number is filed value in name, in value, mobile_number is for sorting
and contact_id is for making link.
Monday, April 29, 2013
Create and download csv file from array using php
Create and download csv file from array using php.
<?php function arrayToCsv( array $fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) { $delimiter_esc = preg_quote($delimiter, '/'); $enclosure_esc = preg_quote($enclosure, '/'); $outputString = ""; foreach($fields as $tempFields) { $output = array(); foreach ( $tempFields as $field ) { if ($field === null && $nullToMysqlNull) { $output[] = "NULL"; continue; } // Enclose fields containing $delimiter, $enclosure or whitespace if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) { $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure; } else { $output[] = $field; } } $outputString .= implode( $delimiter, $output )."\n"; } return $outputString; } ?>
<?php $dataArray = array(); array_push($dataArray, array( "First Name", "Last Name", "Number", "Group" )); foreach($dataList as $index => $data) { array_push($dataArray, array( "".$data["first_name"], "".$data["last_name"], "".$data["mobile_number"], "".$data["group_name"] )); } $csvString = arrayToCsv($dataArray); header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=list.csv"); header("Pragma: no-cache"); header("Expires: 0"); echo $csvString; ?>
Php check a value exists in multi level array and return path
Search in array using php by value if the array is any depth data.
Output:
1. True (Find or not)
2. Path to this value.
<?php function array_value_exists($search = "", $searchArray = array(), $returnKey = false, &$returnKeyArray = array(), $level = 0) { $returnValue = false; $search = trim(strval($search)); if(strlen($search) == 0) { return false; } if(is_null($searchArray)) { return false; } if(!is_array($searchArray)) { return false; } foreach($searchArray as $key => $value) { array_push($returnKeyArray, $key); if(is_string($value)) { if($search == trim($value)) { $returnValue = true; break; } } else if(is_array($value)) { $returnValue = array_value_exists($search, $value, false, $returnKeyArray); if($returnValue == true) { break; } } } if($returnKey == true) { return $returnKeyArray; } return $returnValue; } ?> Use:<?php $ary = array( "bm" => array( "dev" => array( "pritom" => array( "email" => "pritomkucse@yahoo.com" ), "touhid" => array( "email" => "touhid@yahoo.com" ) ), "designer" => array( "dipu" => array( "email" => "dipu@yahoo.com" ) ) ), "gpit" => array( "dev" => array( "sanat" => array( "email" => "sanat@gpit.com" ) ) ) ); $has = array_value_exists("pritomkucse@yahoo.com", $ary); echo $has == true ? "True" : "False"; print_r(array_value_exists("pritomkucse@yahoo.com", $ary, true)); ?>
Output:
1. True (Find or not)
2. Path to this value.
Array ( [0] => bm [1] => dev [2] => pritom [3] => email )
Read and parse csv file using php code
Details http://code.google.com/p/parsecsv-for-php/
Or download from here
Use:
require_once('../parsecsv.lib.php');
# create new parseCSV object.
$csv = new parseCSV();
# Parse '_books.csv' using automatic delimiter detection...
$csv->conditions = 'author does not contain dan brown';
$csv->conditions = 'rating < 4 OR author is John Twelve Hawks';
$csv->conditions = 'rating > 4 AND author is Dan Brown';
$csv->sort_by = 'title';
# offset from the beginning of the file,
# ignoring the first X number of rows.
$csv->offset = 2;
# limit the number of returned rows.
$csv->limit = 3;
$csv->auto('_books.csv');
foreach ($csv->titles as $value);
foreach ($csv->data as $key => $row);
Or download from here
Use:
require_once('../parsecsv.lib.php');
# create new parseCSV object.
$csv = new parseCSV();
# Parse '_books.csv' using automatic delimiter detection...
$csv->conditions = 'author does not contain dan brown';
$csv->conditions = 'rating < 4 OR author is John Twelve Hawks';
$csv->conditions = 'rating > 4 AND author is Dan Brown';
$csv->sort_by = 'title';
# offset from the beginning of the file,
# ignoring the first X number of rows.
$csv->offset = 2;
# limit the number of returned rows.
$csv->limit = 3;
$csv->auto('_books.csv');
foreach ($csv->titles as $value);
foreach ($csv->data as $key => $row);
Saturday, April 27, 2013
Android custom dialog example
In this tutorial, we show you how to create a custom dialog in Android. See following steps :
File : res/layout/main.xml
File : res/layout/login.xml
Read the comment and demo in next step, it should be self-explorary.
- Create a custom dialog layout (XML file).
- Attach the layout to
Dialog
. - Display the
Dialog
. - Done.
1 Android Layout Files
Two XML files, one for main screen, one for custom dialog.File : res/layout/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" > <Button android:id="@+id/btnLogin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Login Dialog" /> </LinearLayout>
<?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="match_parent" android:layout_height="wrap_content" android:text="@string/sldjfsjdflsdf" android:textAppearance="?android:attr/textAppearanceLarge" /> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView1" android:layout_width="45dp" android:layout_height="45dp" android:src="@drawable/user" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" > <requestFocus /> </EditText> </LinearLayout> <LinearLayout android:id="@+id/linearLayout2" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView2" android:layout_width="45dp" android:layout_height="45dp" android:src="@drawable/password" /> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:inputType="textPassword" /> </LinearLayout> <Button android:id="@+id/btnLoginPrompt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/login" /> </TableLayout>
Button btnLogin = (Button)findViewById(R.id.btnLogin); btnLogin.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { final Dialog dialog = new Dialog(ContactspaceandroidActivity.this); dialog.setContentView(R.layout.login); dialog.setTitle("Title..."); dialog.show(); Button azxc = (Button) dialog.findViewById(R.id.btnLoginPrompt); azxc.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { System.out.println("BTN LOGIN CLICKED."); EditText txtUserName = (EditText) dialog.findViewById(R.id.txtUserName); EditText txtPassword = (EditText) dialog.findViewById(R.id.txtPassword); if(txtUserName.getText().length() <= 0) { Toast.makeText(ContactspaceandroidActivity.this, "Enter username.", Toast.LENGTH_LONG).show(); return; } if(txtPassword.getText().length() <= 0) { Toast.makeText(ContactspaceandroidActivity.this, "Enter password.", Toast.LENGTH_LONG).show(); return; } } }); } });
Php making a soap based server with basic authentication
Compared to the standard authentication in the rest of your applications, SOAP authentication isn't too complicated. There are two easy ways of integrating it into your SOAP server: using HTTP Basic authentication or processing a custom SOAP header.
Make sure you have soap enabled in your server machine. Write "phpinfo();" and look for the word "Soap Client" as below:
If you don't find above soap enabled then you have to enable it. Navigate explorer to /c/xampp/php and edit "php.ini" and uncomment the line marked in below image and restart server and check again if your server has soap enabled:
Soap-server:
<?php
function pc_authenticate_user($username, $password)
{
$is_valid = false;
if(strlen(trim($username)) > 0 && trim($username) == "adm" && strlen(trim($password)) > 0 && trim($password) == "pwd") {
$is_valid = true;
}
if ($is_valid) {
return true;
}
else {
return false;
}
}
class pc_SOAP_return_time
{
public function __construct() {
// Throw SOAP fault for invalid username and password combo
if (!pc_authenticate_user($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) ) {
throw new SOAPFault("Incorrect username and password combination.", 401);
}
}
function return_time($name, $lastName) {
return "Time: ".time().", First Name: ".$name.", Last Name: ".$lastName;
}
function accept_xml() {
$postData = file_get_contents("php://input");
return $postData;
}
}
$server = new SOAPServer(null, array('uri' => 'urn:pc_SOAP_return_time'));
$server->setClass('pc_SOAP_return_time');
$server->handle();
Soap-client
<?php $opts = array( 'location' => 'http://localhost/ci/dragon71/soap-check/server.php', 'uri' => 'urn:pc_SOAP_return_time', 'login' => 'adm', 'password' => 'pwd' ); $client = new SOAPClient(null, $opts); $result = $client->__soapCall('return_time', array("Pritom", "Kumar")); print_r($result);
Or
<?php $xml = '<?xml version="1.0" encoding="utf-8"?>'. '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'. ' xmlns:xsd="http://www.w3.org/2001/XMLSchema"'. ' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'. '<soap:Body>'. '<accept_xml xmlns="http://localhost/ci/dragon71/soap-check/server.php/">'. '<ItemId>15</ItemId>'. '</accept_xml>'. '</soap:Body>'. '</soap:Envelope>'; $url = "http://localhost/ci/dragon71/soap-check/server.php"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); $headers = array(); array_push($headers, "Content-Type: text/xml; charset=utf-8"); array_push($headers, "Accept: text/xml"); array_push($headers, "Cache-Control: no-cache"); array_push($headers, "Pragma: no-cache"); if($xml != null) { curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml"); array_push($headers, "Content-Length: " . strlen($xml)); } curl_setopt($ch, CURLOPT_USERPWD, "adm:pwd"); /* If required */ curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); header('Content-Type: text/xml'); print_r($response);
Make sure you have soap enabled in your server machine. Write "phpinfo();" and look for the word "Soap Client" as below:
If you don't find above soap enabled then you have to enable it. Navigate explorer to /c/xampp/php and edit "php.ini" and uncomment the line marked in below image and restart server and check again if your server has soap enabled:
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:
Function MyAdapter is as following:
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; }
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>
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");
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
Implementing a content provider involves always the following steps:
That’s why I used the following line in the code sample above:
<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:
Your DataHandler class should look like this:
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:
- Create a class that extends
ContentProvider
- Define the authority
- Define the URI or URIs
- Create constants to ease client-development
- Implement the
getType()
method - Implement the CRUD-methods
- Add the content provider to your
AndroidManifest.xml
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 theAndroidManifest.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; } }
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); } } ?>
Subscribe to:
Posts (Atom)