Wednesday, October 9, 2013

Android Listview onListItemClick get Sqlite Id

public List<Emp> AllRecords() 
{
    List<Emp> dataset = new ArrayList<Emp>();
    Cursor cursor = database.query(DatabaseHelper.TABLE_EMPLOYEE,allColumns, null, null,null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Emp obj = cursorToContact(cursor);
        dataset.add(obj);
      cursor.moveToNext();
    }
    cursor.close();
    return dataset;
}

private Emp cursorToContact(Cursor cursor) 
{
    Emp obj = new Emp();
    obj.setId(cursor.getInt(0));
    obj.setName(cursor.getString(1));
    obj.setDesig(cursor.getString(2));
    return obj;
}


//--------------
list_data = (ArrayList<Emp>) qh.AllRecords();
CustomListAdapter adapter = new CustomListAdapter(MainActivity.this,list_data);
//---------
public void onItemClick(AdapterView arg0, View arg1, int arg2,long arg3) 

  int id=list_data.get(arg2); //Type mismatch: cannot convert from Emp to int
  Toast.makeText(MainActivity.this,id,Toast.LENGTH_SHORT).show(); 
} 
 
Plz tell what should i write to get id.

Thursday, July 25, 2013

Generating Excel Having UTF-8 Characters In PHP

This is another important piece of code that i have been looking for a long time.  With this source code we can export data to xls/csv file from mysql.


header('Content-Type: text/html; charset=utf-8');
mysql_connect("localhost","root","");
mysql_select_db("ladli");
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET COLLATION_CONNECTION = 'utf8_unicode_ci'");
//====================================================
$sql = "select * from test";
$result = mysql_query($sql);
$insert = "";
$insert_rows = "";
for ($i = 1; $i < mysql_num_fields($result); $i++)
{
    $insert_rows .= mysql_field_name($result,$i) . "\t";
}
$insert_rows.="\n";
//fwrite($fp, $insert_rows);
while($row = mysql_fetch_row($result))
{
    $insert .= $row[1]. "\t" .$row[2]. "\t".$row[3]. "\t".$row[4]. "\t".$row[5];
    $insert .= "\n";               //       serialize($assoc)
    //fwrite($fp, $insert);
}
$insert_rows.=$insert;
$csv_output=$insert_rows;
//=========================================================
$filename="abcd";
header('Content-Description: File Transfer');
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
header('Content-Transfer-Encoding: binary');
header('Pragma: public');
print "\xEF\xBB\xBF"; // UTF-8 BOM
print $csv_output;
exit;

Tuesday, July 23, 2013

Email with File Attachment in PHP

While working in a project i was stuck with this File Attachment problem. The requirement was to generate an Invoice(PDF) at run-time and email it to user. After hours of searching and testing finally i found the solution. Following is the code :

// array with file names to be sent as attachment
$files = array("abcd.pdf","efgh.pdf");
// email fields: to, from, subject, and so on
$to = "receiver@gmail.com";
$from = "Sender Name "."";
$subject ="Your attached file";
$message = "My message";
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
for($x=0;$x{
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = @mail($to, $subject, $message, $headers);
if ($ok) {
echo "mail sent to $to!
";
} else {
echo "mail could not be sent!
";
}
The above code is tested and working fine. The only changes required are :

1) Add file name to array. With this code you can attach multiple files in mail. Just add file name to array.
$files = array("abcd.pdf","efgh.pdf");

2) Change sender email
$from = "Sender Name "."";

3) Change receiver email
$to = "receiver@gmail.com";

4) Change your message
$message = "My message";

Make sure in your message part you put only text and not html because html tags don't work here as Content-Type is set to  text/plain.

So, this was all about attaching file with email. Feel free to comment or ask using contact form. Stay tuned form more updates.

Monday, July 22, 2013

Making Web Application In PHP Using UTF-8

According to Wikipedia, UTF-8 (UCS Transformation Format—8-bit) is a variable-width encoding that can represent every character in the Unicode character set. It was designed for backward compatibility with ASCII and to avoid the complications of endianness and byte order marks in UTF-16 and UTF-32.

Our Aim is to make a simple web application where we will have a user end form, from which user will enter both normal and Unicode characters. Then, there will be a Database where the data from form will be stored. And finally, we will have a report page for displaying data.

So, creating a form is very simple. Nothings extra needs to be done with form elements in this case. Now, lets move on to the database part. Just one change needs to be done with table fields. The Collation Type of the field that will contain Unicode characters should be set to utf8_bin.

I have created a table named test with 3 fields - id, name and status.

CREATE TABLE IF NOT EXISTS `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `status` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
)

Now, next step is to insert form data into table. This will also be normal as we always do. Just run a insert command and insert the posted values from form.
 
INSERT INTO `test` (`id`, `name`, `status`) VALUES
(1, 'सजल', 1),
(2, 'सूर्या', 1),
(3, 'मनीष', 1),
(4, 'राहुल', 1);
 
In the above sample, in the name field, i am passing Unicode characters. Now the final task is to display the records in webpage. This is also quite very simple. we just need to make two additions. These are :

1) Use Meta Tag

Short tag :
Long Tag:

OR
You can use php header to set it -
header('Content-Type: text/html; charset=utf-8');

2) Sets the Mysql client character set

mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET COLLATION_CONNECTION = 'utf8_unicode_ci'");

Use the above command before firing select command. SET NAMES indicates what character set the client will use to send SQL statements to the server. It is needed whenever you want to send data to the server having characters that cannot be represented in pure ASCII, like 'ñ' or 'ö'.

This is all for it. Following the above, you can make a dynamic website in your native language. Queries and comments are most welcome. I would be happy to help.