So you created your Android App with SQLite database, and you are interested to view the database offline. You can do it with the adb command.
1) in command line, issue "adb shell" command, and then you will go to android prompt:
root@android:/ #
2) cd data/data, then ls, and you will see a lot of the App package:
com.android.bluetooth
com.android.browser
com.android.calculator2
com.android.calendar
com.android.certinstaller
com.android.contacts
com.android.defcontainer
....
3) cd to your App package, say for example "com.victor.example"
4) cd databases, and ls to find out the databases name
5) run the command "sqlite3 mydb.s3db"
root@android:/data/data/com.victor.example/databases # sqlite3 mydb.s3db
sqlite3 mydb.s3db
SQLite version 3.7.11 2012-03-20 11:35:50
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
6) check the table name
sqlite> .tables
.tables
android_metadata employees
sqlite> select * from employees;
select * from employees;
1|mitt|01234567|01234567|20
2|mitt|01234567|01234567|20
3|mitt|01234567|01234567|20
4|mitt|01234567|01234567|20
5|mitt|01234567|01234567|20
sqlite>
7) That's it. You successfully view the App database content using the adb shell command.
Monday, 25 November 2013
Sunday, 24 November 2013
Export Excel data to MySQL database
We will show you how to export Excel data to MySQL db.
The steps are:
1) saved the excel data to csv format, such as below
BK001,Introduction to science,976,85.0
BK002,Human Anatomy,985,200.0
BK003,Concepts in Health,765,100.5
2) create a db table that matches the csv format
mysql> create table book_info
-> (book_id varchar(20), book_name varchar(40), isbn_no int(11), book_price, int(10));
3) run the mysql command
mysql> load data infile 'c:\\Book1.csv' into table book_info fields terminated by ',' lines terminated by '\n';
Query OK, 3 rows affected (0.07 sec)
Records: 3 Deleted: 0 Skipped: 0 Warnings: 0
After that, the db contains the Excel data, To verify, issue the command:
mysql> select * from book_info;
+---------+-------------------------+---------+------------+
| book_id | book_name | isbn_no | book_price |
+---------+-------------------------+---------+------------+
| BK001 | Introduction to science | 976 | 85 |
| BK002 | Human Anatomy | 985 | 200 |
| BK003 | Concepts in Health | 765 | 101 |
+---------+-------------------------+---------+------------+
3 rows in set (0.00 sec)
Friday, 25 October 2013
Facebook App Development on Android
On Facebook
Firstly, we talk about the tasks and tools available on Facebook developers.
Now, login to your FB account, go to "Manage Apps"
Choose "Edit App" or "Create New App".
Here are the basic settings of the App:
Then, choose "Use Graph API Explorer".
Enter the POST action path: "me/victory-test-now:gin"
victory-test-now is the namespace, gin is the Action. You may have to add the Action in the "Open Graph" section beforehand.
The food url is from "Open Graph->Types":
After clicking submit button in the Graph API Explorer, go to the Activity Log of the user. You can see the Action in the Activity Log.
You can add a place field to the POST Action.
The place id can be obtained using the following method.
Click on the profile picture, right click, choose "Copy link address"
For example, the link address is below.
https://www.facebook.com/photo.php?fbid=10150753663333147&set=a.438257763146.238406.145768288146&type=1&source=11
The place id is "145768288146".
The Action can be seen in the Activity Log again.
On Android
Secondly, we highlight how the Android App is able to access the data in Facebook through the Facebook App.
Preparation steps:
After that, you can start to create an Android App in Eclipse. The good tutorial from FB is listed below:
https://developers.facebook.com/docs/android/getting-started/facebook-sdk-for-android/
After you have created the Android App, we go back to the App Dashboard on Facebook Developers, and register the Android package and activity name in the "Native Android App" settings. As an example, the detail info is shown below.
To get the Key Hash, add the code to the OnCreate() method of the MainActivity class.
In the Facebook tutorial below,
https://developers.facebook.com/docs/android/scrumptious/publish-open-graph-story/
it talks about publishing to Open Graph story.
You could modify the code to make it publish to Facebook Feed. Sounds interesting, isn't it? The essential changes are:
1) populate the Bundle with the description, link, name, caption
2) change the post action path to "me/feed"
The obvious changes are not difficult. However, you may have to retrieve the user info from List<GraphUser>.
public String announceString;
...
private List<GraphUser> selectedUsers;
...
for (GraphUser user : selectedUsers) {
announceString += user.getName();
}
The changes to AsyncTask:
AsyncTask<Void, Void, Response> task =
new AsyncTask<Void, Void, Response>() {
@Override
protected Response doInBackground(Void... voids) {
// Create an eat action
EatAction eatAction =
GraphObject.Factory.create(EatAction.class);
// Populate the action with the POST parameters:
// the meal, friends, and place info
for (BaseListElement element : listElements) {
element.populateOGAction(eatAction);
}
// Set up a request with the active session, set up
// an HTTP POST to the eat action endpoint
// Request request = new Request(Session.getActiveSession(),
// POST_ACTION_PATH, null, HttpMethod.POST);
Bundle postParams = new Bundle();
postParams.putString("name", "Gin food");
postParams.putString("caption", "Gin food");
postParams.putString("description", announceString);
postParams.putString("link", announceUrl);
Request request = new Request(Session.getActiveSession(),
"me/feed", postParams, HttpMethod.POST);
// Add the post parameter, the eat action
request.setGraphObject(eatAction);
// Execute the request synchronously in the background
// and return the response.
return request.executeAndWait();
}
@Override
protected void onPostExecute(Response response) {
// When the task completes, process
// the response on the main thread
onPostActionResponse(response);
}
};
Firstly, we talk about the tasks and tools available on Facebook developers.
Now, login to your FB account, go to "Manage Apps"
Choose "Edit App" or "Create New App".
Here are the basic settings of the App:
Then, choose "Use Graph API Explorer".
Enter the POST action path: "me/victory-test-now:gin"
victory-test-now is the namespace, gin is the Action. You may have to add the Action in the "Open Graph" section beforehand.
The food url is from "Open Graph->Types":
After clicking submit button in the Graph API Explorer, go to the Activity Log of the user. You can see the Action in the Activity Log.
You can add a place field to the POST Action.
The place id can be obtained using the following method.
Click on the profile picture, right click, choose "Copy link address"
For example, the link address is below.
https://www.facebook.com/photo.php?fbid=10150753663333147&set=a.438257763146.238406.145768288146&type=1&source=11
The place id is "145768288146".
The Action can be seen in the Activity Log again.
On Android
Secondly, we highlight how the Android App is able to access the data in Facebook through the Facebook App.
Preparation steps:
- Download the Facebook SDK for Android
- Import the SDK into Eclipse
- Compile and build it
After that, you can start to create an Android App in Eclipse. The good tutorial from FB is listed below:
https://developers.facebook.com/docs/android/getting-started/facebook-sdk-for-android/
After you have created the Android App, we go back to the App Dashboard on Facebook Developers, and register the Android package and activity name in the "Native Android App" settings. As an example, the detail info is shown below.
To get the Key Hash, add the code to the OnCreate() method of the MainActivity class.
// Add code to print out the key hash
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.facebook.samples.hellofacebook",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
Publish to Facebook FeedIn the Facebook tutorial below,
https://developers.facebook.com/docs/android/scrumptious/publish-open-graph-story/
it talks about publishing to Open Graph story.
You could modify the code to make it publish to Facebook Feed. Sounds interesting, isn't it? The essential changes are:
1) populate the Bundle with the description, link, name, caption
2) change the post action path to "me/feed"
The obvious changes are not difficult. However, you may have to retrieve the user info from List<GraphUser>.
public String announceString;
...
private List<GraphUser> selectedUsers;
...
for (GraphUser user : selectedUsers) {
announceString += user.getName();
}
The changes to AsyncTask:
AsyncTask<Void, Void, Response> task =
new AsyncTask<Void, Void, Response>() {
@Override
protected Response doInBackground(Void... voids) {
// Create an eat action
EatAction eatAction =
GraphObject.Factory.create(EatAction.class);
// Populate the action with the POST parameters:
// the meal, friends, and place info
for (BaseListElement element : listElements) {
element.populateOGAction(eatAction);
}
// Set up a request with the active session, set up
// an HTTP POST to the eat action endpoint
// Request request = new Request(Session.getActiveSession(),
// POST_ACTION_PATH, null, HttpMethod.POST);
Bundle postParams = new Bundle();
postParams.putString("name", "Gin food");
postParams.putString("caption", "Gin food");
postParams.putString("description", announceString);
postParams.putString("link", announceUrl);
Request request = new Request(Session.getActiveSession(),
"me/feed", postParams, HttpMethod.POST);
// Add the post parameter, the eat action
request.setGraphObject(eatAction);
// Execute the request synchronously in the background
// and return the response.
return request.executeAndWait();
}
@Override
protected void onPostExecute(Response response) {
// When the task completes, process
// the response on the main thread
onPostActionResponse(response);
}
};
Tuesday, 22 October 2013
Factory Design Pattern
The factory design pattern is a pattern that has some methods that create objects for you. You don't use new method directly to create the objects.
When you want to change the types of objects created, you just change the factory. All other codes that use the factory change automatically.
For example, in PHP:
<?php
class ClassModelC {
private $ModelC;
public function __construct($c)
{
$this->ModelC = $c;
}
public function getModel()
{ return $this->ModelC; }
}
class ClassModelB {
private $ModelB;
public function __construct($b)
{
$this->ModelB = $b;
}
public function getModel()
{ return $this->ModelB; }
}
class ClassModelA {
private $ModelA;
public function __construct($b, $c)
{
$this->ModelA = $b->getModel().' '.$c->getModel();
}
public function getModel()
{
return $this->ModelA;
}
}
class Factory{
public function build($b, $c)
{
$classc = $this->buildC($c);
$classb = $this->buildB($b);
return $this->buildA($classb, $classc);
}
public function buildA($classb, $classc)
{
return new ClassModelA($classb, $classc);
}
public function buildB($b)
{
return new ClassModelB($b);
}
public function buildC($c)
{
return new ClassModelC($c);
}
}
$factory = new Factory;
$obj = $factory->build('Thunderbird','Jaguar');
print_r($obj->getModel());
print("\n");
?>
If in future, you want to change the object type, you can just change the factory method, as below.
class Factory_New extends Factory{
public function build($b, $c)
{
return DatabaseObject($b, $c);
}
}
When you want to change the types of objects created, you just change the factory. All other codes that use the factory change automatically.
For example, in PHP:
<?php
class ClassModelC {
private $ModelC;
public function __construct($c)
{
$this->ModelC = $c;
}
public function getModel()
{ return $this->ModelC; }
}
class ClassModelB {
private $ModelB;
public function __construct($b)
{
$this->ModelB = $b;
}
public function getModel()
{ return $this->ModelB; }
}
class ClassModelA {
private $ModelA;
public function __construct($b, $c)
{
$this->ModelA = $b->getModel().' '.$c->getModel();
}
public function getModel()
{
return $this->ModelA;
}
}
class Factory{
public function build($b, $c)
{
$classc = $this->buildC($c);
$classb = $this->buildB($b);
return $this->buildA($classb, $classc);
}
public function buildA($classb, $classc)
{
return new ClassModelA($classb, $classc);
}
public function buildB($b)
{
return new ClassModelB($b);
}
public function buildC($c)
{
return new ClassModelC($c);
}
}
$factory = new Factory;
$obj = $factory->build('Thunderbird','Jaguar');
print_r($obj->getModel());
print("\n");
?>
If in future, you want to change the object type, you can just change the factory method, as below.
class Factory_New extends Factory{
public function build($b, $c)
{
return DatabaseObject($b, $c);
}
}
Wednesday, 9 October 2013
Getting Started with the Amazon Web Services
The Amazon Web Services (AWS) is a set of virtual computing and storage services. It is scalable, flexible, and has low start-up cost.
AWS application can be programmed through PHP, Python, Java, and Ruby, etc. Mobile apps can also access AWS through SDK for Android and iOS.
Sign up for AWS products
A credit card is required in order to sign up for AWS. You can use EntroPay, a virtual credit card provider, as the credit card.
Get the Security Credentials from your AWS account
Create a group and user in AWS IAM. The purpose is to get the access key ID and the secret key.
Using AWS SDK for PHP
libeay32.dll
ssleay32.dll
and also, modify php.ini, and enable the curl extension.
cd ./AWSSDKforPHP
EXAMPLE
one example of access the bucket using non composer way, it is heavily commented.
<?php
//non-composer way, you need to download aws.phar separately
require 'aws.phar';
use Aws\S3\S3Client;
// Instantiate the S3 client with your AWS credentials and desired AWS region,
// you must create a user in AWS IAM console
$client = S3Client::factory(array(
'key' => 'AKIAILBKCPBE6I2GEKOA',
'secret' => '2Nbn7LJl/sDz40kviPCFBaOHxZItDelQ1pZzhPyq',
));
//The requested bucket name is not available.
//The bucket namespace is shared by all users of the system.
//Please select a different name and try again.
//If you see this error, it means the bucket name is already used by other people.
//Please choose a bucket name which is not common
$bucket = 'my-bupket1';
$array_bucket = array('Bucket' => $bucket);
//check for existence of bucket
if (($client->doesBucketExist($bucket, true, $array_bucket)) == false)
{
$result = $client->createBucket($array_bucket);
// Wait until the bucket is created
$client->waitUntil('BucketExists', array('Bucket' => $bucket));
echo "bucket created";
}
else
{
echo "bucket exist";
}
// Key is the identifier of the object
// Body is the content of the object
$client->putObject(array(
'Bucket' => $bucket,
'Key' => 'README.md',
'Body' => fopen('README.md', 'r')));
$result = $client->getObject(array(
'Bucket' => $bucket,
'Key' => 'README.md'
));
//the Body value can be cast to a string
echo $result['Body'] . "\n";
?>
Using AWS SDK for Android
AWS application can be programmed through PHP, Python, Java, and Ruby, etc. Mobile apps can also access AWS through SDK for Android and iOS.
A credit card is required in order to sign up for AWS. You can use EntroPay, a virtual credit card provider, as the credit card.
Get the Security Credentials from your AWS account
Create a group and user in AWS IAM. The purpose is to get the access key ID and the secret key.
Using AWS SDK for PHP
- install PHP
libeay32.dll
ssleay32.dll
and also, modify php.ini, and enable the curl extension.
- install the SDK for PHP
cd ./AWSSDKforPHP
- configure the security credentials
config-sample.inc.php
file in the SDK folder, and rename it to config.inc.php,
and change the access key ID and secret key- run the sample php file
in the samples folder, run
php cli-s3_get_urls_for_uploads.phpEXAMPLE
one example of access the bucket using non composer way, it is heavily commented.
<?php
//non-composer way, you need to download aws.phar separately
require 'aws.phar';
use Aws\S3\S3Client;
// Instantiate the S3 client with your AWS credentials and desired AWS region,
// you must create a user in AWS IAM console
$client = S3Client::factory(array(
'key' => 'AKIAILBKCPBE6I2GEKOA',
'secret' => '2Nbn7LJl/sDz40kviPCFBaOHxZItDelQ1pZzhPyq',
));
//The requested bucket name is not available.
//The bucket namespace is shared by all users of the system.
//Please select a different name and try again.
//If you see this error, it means the bucket name is already used by other people.
//Please choose a bucket name which is not common
$bucket = 'my-bupket1';
$array_bucket = array('Bucket' => $bucket);
//check for existence of bucket
if (($client->doesBucketExist($bucket, true, $array_bucket)) == false)
{
$result = $client->createBucket($array_bucket);
// Wait until the bucket is created
$client->waitUntil('BucketExists', array('Bucket' => $bucket));
echo "bucket created";
}
else
{
echo "bucket exist";
}
// Key is the identifier of the object
// Body is the content of the object
$client->putObject(array(
'Bucket' => $bucket,
'Key' => 'README.md',
'Body' => fopen('README.md', 'r')));
$result = $client->getObject(array(
'Bucket' => $bucket,
'Key' => 'README.md'
));
//the Body value can be cast to a string
echo $result['Body'] . "\n";
?>
Using AWS SDK for Android
- install Eclipse for Android
This is necessary to build an Android application.
- install the SDK for Android
After that, go to download the SDK from http://aws.amazon.com/developers/getting-started/android/
- import the sample Android project
Wednesday, 2 October 2013
Install Custom ROM on Samsung Galaxy Tab 2
The Samsung Galaxy Tab 2 (7 inch) has the model number of P-3100.
1) Rooting the phone
Reboot galaxy tab 2 to run in "Download Mode". On the Windows PC, start Odin-v1.85, wait for Odin to recognise the galaxy tab 2 in id:com panel. Then, choose CF-Auto-Root-espressorf-espressorfxx-gtp3100 file in the PDA files download section. Then click the start button. The message pane will show the progress messages. After the update is finished, the Galaxy Tab 2 will reboot by itself.
2) Get the custom ROM image
Choose and download the custom ROM image to PC, and copy it to the SD card on the phone.
3) Setup recovery image
In your Galaxy Tab, go to Google Play Store,
install ROM Manager from ClockworkMod,
run the ROM Manager App,
and choose the recovery image
4) Boot to recovery
In PC, run "adb reboot recovery"
or on the phone, press volume up and power button
to go to ClockworkMod Recovery
Important:
Before you install the custom ROM,
Full wipe, and manual format /system
5) Perform the custom ROM image flashing
In ClockworkMod Recovery:
wipe data/factory reset
wipe cache partition
in mounts and storage, format /system
After you have done the full wipe, choose "install zip from sdcard",
Select the Slim Bean or any custom ROM image, then click YES.
1) Rooting the phone
Reboot galaxy tab 2 to run in "Download Mode". On the Windows PC, start Odin-v1.85, wait for Odin to recognise the galaxy tab 2 in id:com panel. Then, choose CF-Auto-Root-espressorf-espressorfxx-gtp3100 file in the PDA files download section. Then click the start button. The message pane will show the progress messages. After the update is finished, the Galaxy Tab 2 will reboot by itself.
2) Get the custom ROM image
Choose and download the custom ROM image to PC, and copy it to the SD card on the phone.
3) Setup recovery image
In your Galaxy Tab, go to Google Play Store,
install ROM Manager from ClockworkMod,
run the ROM Manager App,
and choose the recovery image
4) Boot to recovery
In PC, run "adb reboot recovery"
or on the phone, press volume up and power button
to go to ClockworkMod Recovery
Important:
Before you install the custom ROM,
Full wipe, and manual format /system
5) Perform the custom ROM image flashing
In ClockworkMod Recovery:
wipe data/factory reset
wipe cache partition
in mounts and storage, format /system
After you have done the full wipe, choose "install zip from sdcard",
Select the Slim Bean or any custom ROM image, then click YES.
Friday, 20 September 2013
[Android] Displaying Graphical Chart and Playing Video
In this article, we will talk about how to display a graphical chart and play mp4 video in Android app.
1) Display Graphical Chart from XML data
Imagine you receive the XML data from Web Service, as shown below:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<FahrenheitToCelsiusResponse xmlns="http://tempuri.org/">
<FahrenheitToCelsiusResult>-11.6666666666667</FahrenheitToCelsiusResult>
</FahrenheitToCelsiusResponse>
</soap:Body>
</soap:Envelope>
Now you will call the web service, receive the XML data, parse the XML data, and display a graphical chart based on the data received through the web service.
private String SOAP_ACTION = "http://192.168.10.1/methods/soap-api";
...
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL1);
androidHttpTransport.debug = true;
androidHttpTransport.call(SOAP_ACTION, envelope);
String Data = androidHttpTransport.responseDump;
the start element and end element are FahrenheitToCelsiusResponse.
the tag comparison is using FahrenheitToCelsiusResult.
use the javax xml parsers and org xml sax helpers.
import javax.xml.parsers.SAXParser;
import org.xml.sax.helpers.DefaultHandler;
List<TemperatureData> Data_List;
String DataStr="";
InputStream is = new ByteArrayInputStream(Data.getBytes("UTF-8"));
Data_List = SAXParseXML.readXML(is);
for(int i =0;i<Data_List.size();i++) {
//use integer i as the index
Index = Integer.toString(i);
//Get Fahrenheit from the edit text field
//Fahrenheit = Data_List.get(i).Fahrenheit;
Fahrenheit = txtFar.getText().toString();
Celsius = Data_List.get(i).Celsius;
DataStr+= "["+Index+","+Fahrenheit+","+Celsius+"]";
if (i!=Data_List.size()-1)
DataStr+= ",\n";
else
break;
}
final String chartHtml = getChartHtml(DataStr);
public static String getChartHtml(String Data)
{
String chartHtml = null;
try{
// Generating html content.
chartHtml = URLDecoder.decode(
"<html><head>" +
"<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>\n" +
"<script type=\"text/javascript\">\n" +
"google.load(\"visualization\",\"1\", {packages:[\"corechart\"]});\n" +
"google.setOnLoadCallback(drawChart);\n" +
"function drawChart() {\n" +
"var data = google.visualization.arrayToDataTable([\n" +
"[\'Index\',\'Fahrenheit\',\'Celsius\'],\n" +
Data + // the data
"]);\n" +
"var options = { title: \'Record\',focusTarget:\'category\',pointSize:\'5\' };\n" + // Set options and point size=5.
"var chart = new google.visualization.LineChart(document.getElementById(\'chart_div\'));\n" +
"chart.draw(data,options);" +
"}</script>\n" +
"</head><body><div id=\"chart_div\" style=\"width: 640px; height: 420px;\"></div>" + // Chart frame size
"</body></html>", "utf-8");
} catch (Exception e){
e.printStackTrace();
}
return chartHtml;
}
Use the android webkit to draw graph.
import android.webkit.WebView;
import android.webkit.WebSettings;
runOnUiThread(new Runnable() {
public void run() {
//stuff that updates ui
//web view load data.
setContentView(R.layout.get_measurement_record_online);
mWebView = (WebView)findViewById(R.id.chartWebView);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.setScrollBarStyle
(View.SCROLLBARS_OUTSIDE_OVERLAY);
// the function call to display chart
mWebView.loadDataWithBaseURL(null,chartHtml,"text/html","utf-8",null);
}
});
2) Play mp4 Video
Here is a simple example of clicking a button and playing a video from sdcard. we cannot use it in a separate thread. The actual video playback takes place in runOnUiThread().
public class GatsbyDemoActivity extends Activity
{
....
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// save the context for use later
context = this;
btnVideo = (Button)findViewById(R.id.btnVideo);
...
btnVideo.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
vv = (VideoView) findViewById(R.id.videoView);
// get the Activity context for use within button OnClickListener
mc = new MediaController(context);
//System.out.println("video="+"play video1");
runOnUiThread(new Runnable() {
public void run() {
//stuff that updates ui
getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.get_video);
mVideobackBtn =(
Button)findViewById(R.id.videoBackBtn);
mVideobackBtn
.setOnClickListener(btnBackOnClkLis);
//System.out.println("video="+"play video3");
vv=(VideoView)findViewById(R.id.videoView);
vv.setVideoPath("/sdcard/DCIM/Camera/GATSBY_MOVING_RUBBER.mp4");
mc.setMediaPlayer(vv);
vv.setMediaController(mc);
vv.requestFocus();
vv.start();
} //run
private Button.OnClickListener btnBackOnClkLis = new
Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// Back to the home menu
Intent intent = new Intent(vv.getContext(), GatsbyDemoActivity.class);
startActivity(intent);
}
}; //OnClickListener
}); //runOnUiThread
} //onClick
});
}
}
After that, you can play mp4 video, and click on the back button to go back to previous screen.
3) Screen orientation
In AndroidManifest.xml file, in activity section, set
android:screenOrientation="landscape"
to fix the display in landscape mode.
1) Display Graphical Chart from XML data
Imagine you receive the XML data from Web Service, as shown below:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<FahrenheitToCelsiusResponse xmlns="http://tempuri.org/">
<FahrenheitToCelsiusResult>-11.6666666666667</FahrenheitToCelsiusResult>
</FahrenheitToCelsiusResponse>
</soap:Body>
</soap:Envelope>
Now you will call the web service, receive the XML data, parse the XML data, and display a graphical chart based on the data received through the web service.
- Calling the web service:
private String SOAP_ACTION = "http://192.168.10.1/methods/soap-api";
...
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL1);
androidHttpTransport.debug = true;
androidHttpTransport.call(SOAP_ACTION, envelope);
- Receiving the data:
String Data = androidHttpTransport.responseDump;
- Parsing the data:
the start element and end element are FahrenheitToCelsiusResponse.
the tag comparison is using FahrenheitToCelsiusResult.
use the javax xml parsers and org xml sax helpers.
import javax.xml.parsers.SAXParser;
import org.xml.sax.helpers.DefaultHandler;
List<TemperatureData> Data_List;
String DataStr="";
InputStream is = new ByteArrayInputStream(Data.getBytes("UTF-8"));
Data_List = SAXParseXML.readXML(is);
- Copy the parsed data to a string:
for(int i =0;i<Data_List.size();i++) {
//use integer i as the index
Index = Integer.toString(i);
//Get Fahrenheit from the edit text field
//Fahrenheit = Data_List.get(i).Fahrenheit;
Fahrenheit = txtFar.getText().toString();
Celsius = Data_List.get(i).Celsius;
DataStr+= "["+Index+","+Fahrenheit+","+Celsius+"]";
if (i!=Data_List.size()-1)
DataStr+= ",\n";
else
break;
}
- Format the string into html format, plot the chart using Google Charts:
final String chartHtml = getChartHtml(DataStr);
public static String getChartHtml(String Data)
{
String chartHtml = null;
try{
// Generating html content.
chartHtml = URLDecoder.decode(
"<html><head>" +
"<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>\n" +
"<script type=\"text/javascript\">\n" +
"google.load(\"visualization\",\"1\", {packages:[\"corechart\"]});\n" +
"google.setOnLoadCallback(drawChart);\n" +
"function drawChart() {\n" +
"var data = google.visualization.arrayToDataTable([\n" +
"[\'Index\',\'Fahrenheit\',\'Celsius\'],\n" +
Data + // the data
"]);\n" +
"var options = { title: \'Record\',focusTarget:\'category\',pointSize:\'5\' };\n" + // Set options and point size=5.
"var chart = new google.visualization.LineChart(document.getElementById(\'chart_div\'));\n" +
"chart.draw(data,options);" +
"}</script>\n" +
"</head><body><div id=\"chart_div\" style=\"width: 640px; height: 420px;\"></div>" + // Chart frame size
"</body></html>", "utf-8");
} catch (Exception e){
e.printStackTrace();
}
return chartHtml;
}
- Within the thread, use the runOnUiThread() to update the UI:
Use the android webkit to draw graph.
import android.webkit.WebView;
import android.webkit.WebSettings;
runOnUiThread(new Runnable() {
public void run() {
//stuff that updates ui
//web view load data.
setContentView(R.layout.get_measurement_record_online);
mWebView = (WebView)findViewById(R.id.chartWebView);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.setScrollBarStyle
(View.SCROLLBARS_OUTSIDE_OVERLAY);
// the function call to display chart
mWebView.loadDataWithBaseURL(null,chartHtml,"text/html","utf-8",null);
}
});
2) Play mp4 Video
Here is a simple example of clicking a button and playing a video from sdcard. we cannot use it in a separate thread. The actual video playback takes place in runOnUiThread().
public class GatsbyDemoActivity extends Activity
{
....
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// save the context for use later
context = this;
btnVideo = (Button)findViewById(R.id.btnVideo);
...
btnVideo.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
vv = (VideoView) findViewById(R.id.videoView);
// get the Activity context for use within button OnClickListener
mc = new MediaController(context);
//System.out.println("video="+"play video1");
runOnUiThread(new Runnable() {
public void run() {
//stuff that updates ui
getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.get_video);
mVideobackBtn =(
Button)findViewById(R.id.videoBackBtn);
mVideobackBtn
.setOnClickListener(btnBackOnClkLis);
//System.out.println("video="+"play video3");
vv=(VideoView)findViewById(R.id.videoView);
vv.setVideoPath("/sdcard/DCIM/Camera/GATSBY_MOVING_RUBBER.mp4");
mc.setMediaPlayer(vv);
vv.setMediaController(mc);
vv.requestFocus();
vv.start();
} //run
private Button.OnClickListener btnBackOnClkLis = new
Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// Back to the home menu
Intent intent = new Intent(vv.getContext(), GatsbyDemoActivity.class);
startActivity(intent);
}
}; //OnClickListener
}); //runOnUiThread
} //onClick
});
}
}
After that, you can play mp4 video, and click on the back button to go back to previous screen.
3) Screen orientation
In AndroidManifest.xml file, in activity section, set
android:screenOrientation="landscape"
to fix the display in landscape mode.
Wednesday, 18 September 2013
Joomla
Joomla is an open source CMS, written in PHP and based on MySQL. A CMS is software that keeps track of every aspects of content on your website. CMS manages your content, so you are free to do other creative stuff.
To install Joomla, download the Joomla packages, put it in Apache DocumentRoot, then point your browser to <xxx.xxx.xxx.xxx>/Joomla, such as 127.0.0.1/Joomla. The installation of Joomla will run inside the browser.
To customise Joomla, go to site administrator, then login with admin username and password.
To add user login functionality, then, go to Extensions->Module Manager, click on new, and choose user login module. You can configure the user login module, such as the position, module assignment, etc.
To change template, go to Extensions->Template Manager, you can choose and select the default style for your site.
To install Joomla, download the Joomla packages, put it in Apache DocumentRoot, then point your browser to <xxx.xxx.xxx.xxx>/Joomla, such as 127.0.0.1/Joomla. The installation of Joomla will run inside the browser.
To customise Joomla, go to site administrator, then login with admin username and password.
To add user login functionality, then, go to Extensions->Module Manager, click on new, and choose user login module. You can configure the user login module, such as the position, module assignment, etc.
To change template, go to Extensions->Template Manager, you can choose and select the default style for your site.
Monday, 16 September 2013
[Android] Calling SOAP Web Service
Android App is able to call Web Service using SOAP.
1) create a new Android project as usual. Name the activity file as main.xml.
2) Download the ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar library and copy it to the project libs folder
3) Right click on the project name, select Java Build Path->Libraries, click on "Add JARs...", and add the jar library
4) In the same dialog box, click on "Order and Export", and click the jar library and move it up. Make sure the jar is above Android Dependencies and Private Libraries.
5) Modify the main.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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fahrenheit"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/txtFar"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Celsius"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/txtCel"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnFar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Convert To Celsius" />
<Button
android:id="@+id/btnCel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Convert To Fahrenheit" />
</LinearLayout>
<Button
android:id="@+id/btnClear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Clear" />
</LinearLayout>
6) Make use and understand the ksoap2 class
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
Set the parameter, the parameter are also from wsdl file. The parameter is case-sensitive.
request.addProperty("Fahrenheit", txtFar.getText().toString());
The URL is from <soap:address location="http://mywebsite.com/service"/>
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
Call the soap action, the Soap action is from <soap:operation soapAction="addMyData" style="document"/>
androidHttpTransport.call(SOAP_ACTION1, envelope);
7) Edit the WebServiceDemoActivity.java file.
If you try to access network in the main thread, in Android 4.0 and above, you will get the error of
NetworkOnMainThreadException:
The exception that is thrown when an application attempts to perform a networking operation on its main thread.
The solution is to create a thread, and access the network in the thread
Thread thread = new Thread()
{
@Override
public void run() {
try {
//access the network
......
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
Furthermore, if you try to update the GUI in the thread, you will get the error:
Only the original thread that created a view hierarchy can touch its views.
The solution is to use runOnUiThread() function to update the UI.
runOnUiThread(new Runnable() {
public void run() {
//stuff that updates ui
......
}
});
8) The full source code of WebServiceDemoActivity.java will be published at the bottom.
9) Open your "WebServiceDemo -> android.manifest" file. Add the following line before the <application> tag:
<uses-permission android:name="android.permission.INTERNET" />
This will allow the application to use the internet.
10) Full source code of WebServiceDemoActivity.java:
1) create a new Android project as usual. Name the activity file as main.xml.
2) Download the ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar library and copy it to the project libs folder
3) Right click on the project name, select Java Build Path->Libraries, click on "Add JARs...", and add the jar library
4) In the same dialog box, click on "Order and Export", and click the jar library and move it up. Make sure the jar is above Android Dependencies and Private Libraries.
5) Modify the main.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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fahrenheit"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/txtFar"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Celsius"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/txtCel"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btnFar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Convert To Celsius" />
<Button
android:id="@+id/btnCel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Convert To Fahrenheit" />
</LinearLayout>
<Button
android:id="@+id/btnClear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Clear" />
</LinearLayout>
6) Make use and understand the ksoap2 class
- SOAPObject
- SoapSerializationEnvelope
- HttpTransportSE
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
Set the parameter, the parameter are also from wsdl file. The parameter is case-sensitive.
request.addProperty("Fahrenheit", txtFar.getText().toString());
The URL is from <soap:address location="http://mywebsite.com/service"/>
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
Call the soap action, the Soap action is from <soap:operation soapAction="addMyData" style="document"/>
androidHttpTransport.call(SOAP_ACTION1, envelope);
7) Edit the WebServiceDemoActivity.java file.
If you try to access network in the main thread, in Android 4.0 and above, you will get the error of
NetworkOnMainThreadException:
The exception that is thrown when an application attempts to perform a networking operation on its main thread.
The solution is to create a thread, and access the network in the thread
Thread thread = new Thread()
{
@Override
public void run() {
try {
//access the network
......
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
Furthermore, if you try to update the GUI in the thread, you will get the error:
Only the original thread that created a view hierarchy can touch its views.
The solution is to use runOnUiThread() function to update the UI.
runOnUiThread(new Runnable() {
public void run() {
//stuff that updates ui
......
}
});
8) The full source code of WebServiceDemoActivity.java will be published at the bottom.
9) Open your "WebServiceDemo -> android.manifest" file. Add the following line before the <application> tag:
<uses-permission android:name="android.permission.INTERNET" />
This will allow the application to use the internet.
10) Full source code of WebServiceDemoActivity.java:
package com.webservicedemo;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import com.webservicedemo.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class WebServiceDemoActivity extends Activity
{
/** Called when the activity is first created. */
private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
private static String NAMESPACE1 = "http://tempuri.org/";
private static String METHOD_NAME1 = "FahrenheitToCelsius";
private static String URL1 = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
private static String SOAP_ACTION2 = "http://tempuri.org/CelsiusToFahrenheit";
private static String NAMESPACE2 = "http://tempuri.org/";
private static String METHOD_NAME2 = "CelsiusToFahrenheit";
private static String URL2 = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
Button btnFar,btnCel,btnClear;
EditText txtFar,txtCel;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnFar = (Button)findViewById(R.id.btnFar);
btnCel = (Button)findViewById(R.id.btnCel);
btnClear = (Button)findViewById(R.id.btnClear);
txtFar = (EditText)findViewById(R.id.txtFar);
txtCel = (EditText)findViewById(R.id.txtCel);
btnFar.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
//this is the actual part that will call the webservice
Thread thread = new Thread()
{
@Override
public void run() {
try {
SoapObject request = new SoapObject(NAMESPACE1, METHOD_NAME1);
//Use this to add parameters
request.addProperty("Fahrenheit",txtFar.getText().toString());
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL1);
androidHttpTransport.call(SOAP_ACTION1, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
if(result != null)
{
final String result_str = result.getProperty(0).toString();
runOnUiThread(new Runnable() {
public void run() {
//stuff that updates ui
//Get the first property and change the label text
txtCel.setText(result_str);
}
});
;
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
});
btnCel.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
//this is the actual part that will call the webservice
Thread thread = new Thread()
{
@Override
public void run() {
try {
SoapObject request = new SoapObject(NAMESPACE2, METHOD_NAME2);
//Use this to add parameters
request.addProperty("Celsius",txtCel.getText().toString());
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL2);
androidHttpTransport.call(SOAP_ACTION2, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
if(result != null)
{
final String result_str = result.getProperty(0).toString();
runOnUiThread(new Runnable() {
public void run() {
//stuff that updates ui
//Get the first property and change the label text
txtFar.setText(result_str);
}
});
;
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
});
btnClear.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
txtCel.setText("");
txtFar.setText("");
}
});
}
}
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import com.webservicedemo.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class WebServiceDemoActivity extends Activity
{
/** Called when the activity is first created. */
private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
private static String NAMESPACE1 = "http://tempuri.org/";
private static String METHOD_NAME1 = "FahrenheitToCelsius";
private static String URL1 = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
private static String SOAP_ACTION2 = "http://tempuri.org/CelsiusToFahrenheit";
private static String NAMESPACE2 = "http://tempuri.org/";
private static String METHOD_NAME2 = "CelsiusToFahrenheit";
private static String URL2 = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
Button btnFar,btnCel,btnClear;
EditText txtFar,txtCel;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnFar = (Button)findViewById(R.id.btnFar);
btnCel = (Button)findViewById(R.id.btnCel);
btnClear = (Button)findViewById(R.id.btnClear);
txtFar = (EditText)findViewById(R.id.txtFar);
txtCel = (EditText)findViewById(R.id.txtCel);
btnFar.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
//this is the actual part that will call the webservice
Thread thread = new Thread()
{
@Override
public void run() {
try {
SoapObject request = new SoapObject(NAMESPACE1, METHOD_NAME1);
//Use this to add parameters
request.addProperty("Fahrenheit",txtFar.getText().toString());
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL1);
androidHttpTransport.call(SOAP_ACTION1, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
if(result != null)
{
final String result_str = result.getProperty(0).toString();
runOnUiThread(new Runnable() {
public void run() {
//stuff that updates ui
//Get the first property and change the label text
txtCel.setText(result_str);
}
});
;
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
});
btnCel.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
//this is the actual part that will call the webservice
Thread thread = new Thread()
{
@Override
public void run() {
try {
SoapObject request = new SoapObject(NAMESPACE2, METHOD_NAME2);
//Use this to add parameters
request.addProperty("Celsius",txtCel.getText().toString());
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL2);
androidHttpTransport.call(SOAP_ACTION2, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
if(result != null)
{
final String result_str = result.getProperty(0).toString();
runOnUiThread(new Runnable() {
public void run() {
//stuff that updates ui
//Get the first property and change the label text
txtFar.setText(result_str);
}
});
;
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
});
btnClear.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
txtCel.setText("");
txtFar.setText("");
}
});
}
}
Subscribe to:
Posts (Atom)