Posts Tagged ‘Application programming interface’

testActionBarCompat

Android 4.3 and Nexus 7 announced, Google released a new backward-compatible Action Bar implementation called ActionBarCompat that’s part of the Support Library r18. The ActionBarCompat APIs let you build the essential Action Bar design pattern into your app, with broad compatibility back to Android 2.1.

ActionBarCompat Step-by-step:

 

You may have heard about the “ Google Now project” where you give the voice command and Android fetches result for you. It recognizes your voice and converts it into the text or takes the appropriate action. Have you ever thought how is it done? If your answer is voice recognition API, then you are absolutly right. Recently while playing with Android voice recognition APIs, I found some interesting stuffs. APIs are really easy to use with application. Given below is a small tutorial on voice/speech recognition API. The final application will look similar to that of application shown below. The application may not work on the Android Emulator because it doesn’t support voice recognition. But the same can work on the phone.

Read More »

 

google-play-logo11

The Google Play services SDK is an extension to the Android SDK and is available as a downloadable package from the SDK Manager. The download includes the client library and code samples. To develop using the Google Play services APIs, you must download the Google Play services SDK. Google Play services is not supported on the Android emulator, a physical…

Read More »

This tutorial about my favorite place Dzone like data loading while page scrolling down with jQuery and PHP. We have lots of data but can not display all. This script helps you to display little data and make faster your website.
Load Data while Scrolling Page Down with jQuery and  PHP

Read More »

Android invasion, Sydney, Australia

In this article I explain a possible cause of android.os.NetworkOnMainThreadException and how to avoid it.
From the Android site you can read:
NetworkOnMainThreadException
The exception that is thrown when an application attempts to perform a networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or higher…

Here is a sample developed for Gingerbread, API level 9:

  1. create an Android project called HttpClient
  2. edit the file AndroidManifest.xml
    1 <?xml version="1.0" encoding="utf-8"?>
    2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    3     package="eu.lucazanini.httpclient"
    4     android:versionCode="1"
    5     android:versionName="1.0" >
    6
    7     <uses-sdk android:minSdkVersion="9" />
    8     <uses-permission android:name="android.permission.INTERNET"/>
    9
    10     <application
    11         android:icon="@drawable/ic_launcher"
    12         android:label="@string/app_name" >
    13         <activity
    14             android:name=".HttpClientActivity"
    15             android:label="@string/app_name" >
    16             <intent-filter>
    17                 <action android:name="android.intent.action.MAIN" />
    18
    19                 <category android:name="android.intent.category.LAUNCHER" />
    20             </intent-filter>
    21         </activity>
    22     </application>
    23
    24 </manifest>

    where <uses-sdk android:minSdkVersion=”9″ /> means an API version earlier to Honeycomb (Gingerbread, API level 9), and <uses-permission android:name=”android.permission.INTERNET”/> authorizes the application to perform an internet connection

  3. edit the file HttpClientActivity.java
    1 package eu.lucazanini.httpclient;
    2
    3 import java.io.IOException;
    4
    5 import org.apache.http.HttpResponse;
    6 import org.apache.http.client.ClientProtocolException;
    7 import org.apache.http.client.methods.HttpGet;
    8 import org.apache.http.impl.client.DefaultHttpClient;
    9
    10 import android.app.Activity;
    11 import android.os.Bundle;
    12 import android.util.Log;
    13
    14 public class HttpClientActivity extends Activity {
    15
    16     @Override
    17     public void onCreate(Bundle savedInstanceState) {
    18         super.onCreate(savedInstanceState);
    19         setContentView(R.layout.main);
    20
    21         connect();
    22
    23     }
    24
    25     private void connect() {
    26         try {
    27             DefaultHttpClient client = new DefaultHttpClient();
    28             HttpGet request = new HttpGet("http://www.google.com");
    29             HttpResponse response = client.execute(request);
    30         } catch (ClientProtocolException e) {
    31             Log.d("HTTPCLIENT", e.getLocalizedMessage());
    32         } catch (IOException e) {
    33             Log.d("HTTPCLIENT", e.getLocalizedMessage());
    34         }
    35     }
    36
    37 }

This app is executed without errors.

If you specify an API level after Honeycomb, such as Ice Cream Sandwich, replacing the line <uses-sdk android:minSdkVersion=”9″ /> with <uses-sdk android:minSdkVersion=”14″ /> and you launch the application, you get the exception android.os.NetworkOnMainThreadException.

An easy way to avoid the exception is to insert the following code (which requires import android.os.StrictMode):

1 StrictMode.ThreadPolicy policy = new
2 StrictMode.ThreadPolicy.Builder()
3 .permitAll().build();
4 StrictMode.setThreadPolicy(policy);

before the row connect() in HttpClientActivity.java
But this method is recommended in development environments only, the recommended method is to use the class AsyncTask.

An example is the following in which the code of the class HttpClientActivity.java is replaced by:

1 package eu.lucazanini.httpclient;
2
3 import java.io.IOException;
4
5 import org.apache.http.HttpResponse;
6 import org.apache.http.client.ClientProtocolException;
7 import org.apache.http.client.methods.HttpGet;
8 import org.apache.http.impl.client.DefaultHttpClient;
9
10 import android.app.Activity;
11 import android.os.AsyncTask;
12 import android.os.Bundle;
13 //import android.os.StrictMode;
14 import android.util.Log;
15
16 public class HttpClientActivity extends Activity {
17     /** Called when the activity is first created. */
18     @Override
19     public void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.main);
22
23 //      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
24 //              .permitAll().build();
25 //      StrictMode.setThreadPolicy(policy);
26
27 //      connect();
28
29         new Connection().execute();
30
31     }
32
33     private class Connection extends AsyncTask {
34
35         @Override
36         protected Object doInBackground(Object... arg0) {
37             connect();
38             return null;
39         }
40
41     }
42
43     private void connect() {
44         try {
45             DefaultHttpClient client = new DefaultHttpClient();
46             HttpGet request = new HttpGet("http://www.google.com");
47             HttpResponse response = client.execute(request);
48         } catch (ClientProtocolException e) {
49             Log.d("HTTPCLIENT", e.getLocalizedMessage());
50         } catch (IOException e) {
51             Log.d("HTTPCLIENT", e.getLocalizedMessage());
52         }
53     }
54
55 }

You can override not only doInBackground but also other methods of the AsyncTask class like OnPreExecute(), OnPostExecute(Result), publishProgress(Progress. ..).

Are you working with multiple devices like iPhone, Android and Web then take a look at this post that explains you how to develop a RESTful API in PHP.  Representational state transfer (REST) is a software system for distributing the data to different kind of applications. The web service system produce status code response in JSON or XML format.
Create a RESTful Services API in PHP.


Download Script

Database
Sample database users table columns user_id, user_fullname, user_email, user_password and user_status.

CREATE TABLE IF NOT EXISTS `users`
(
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_fullname` varchar(25) NOT NULL,
`user_email` varchar(50) NOT NULL,
`user_password` varchar(50) NOT NULL,
`user_status` tinyint(1) NOT NULL DEFAULT ‘0’,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Rest API Class: api.php
Contains simple PHP code, here you have to modify database configuration details like database name, username and password.

<?php
require_once(“Rest.inc.php”);class API extends REST
{
public $data = “”;
const DB_SERVER = “localhost”;
const DB_USER = “Database_Username”;
const DB_PASSWORD = “Database_Password”;
const DB = “Database_Name”;private $db = NULL;

public function __construct()
{
parent::__construct();// Init parent contructor
$this->dbConnect();// Initiate Database connection
}

//Database connection
private function dbConnect()
{
$this->db = mysql_connect(self::DB_SERVER,self::DB_USER,self::DB_PASSWORD);
if($this->db)
mysql_select_db(self::DB,$this->db);
}

//Public method for access api.
//This method dynmically call the method based on the query string
public function processApi()
{
$func = strtolower(trim(str_replace(“/”,””,$_REQUEST[‘rquest’])));
if((int)method_exists($this,$func) > 0)
$this->$func();
else
$this->response(”,404);
// If the method not exist with in this class, response would be “Page not found”.
}

private function login()
{
…………..
}

private function users()
{
…………..
}

private function deleteUser()
{
………….
}

//Encode array into JSON
private function json($data)
{
if(is_array($data)){
return json_encode($data);
}
}
}

// Initiiate Library
$api = new API;
$api->processApi();
?>

Login POST
Displaying users records from the users table Rest API URL http://localhost/rest/login/. This Restful API login status works with status codes if status code 200 login success else status code 204 shows fail message. For more status code information check Rest.inc.php in download script.

private function login()
{
// Cross validation if the request method is POST else it will return “Not Acceptable” status
if($this->get_request_method() != “POST”)
{
$this->response(”,406);
}$email = $this->_request[’email’];
$password = $this->_request[‘pwd’];// Input validations
if(!empty($email) and !empty($password))
{
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$sql = mysql_query(“SELECT user_id, user_fullname, user_email FROM users WHERE user_email = ‘$email’ AND user_password = ‘”.md5($password).”‘ LIMIT 1″, $this->db);
if(mysql_num_rows($sql) > 0){
$result = mysql_fetch_array($sql,MYSQL_ASSOC);

// If success everythig is good send header as “OK” and user details
$this->response($this->json($result), 200);
}
$this->response(”, 204); // If no records “No Content” status
}
}

// If invalid inputs “Bad Request” status message and reason
$error = array(‘status’ => “Failed”, “msg” => “Invalid Email address or Password”);
$this->response($this->json($error), 400);
}

Users GET
Displaying users records from the users table Rest API URL http://localhost/rest/users/

private function users()
{
// Cross validation if the request method is GET else it will return “Not Acceptable” status
if($this->get_request_method() != “GET”)
{
$this->response(”,406);
}
$sql = mysql_query(“SELECT user_id, user_fullname, user_email FROM users WHERE user_status = 1”, $this->db);
if(mysql_num_rows($sql) > 0)
{
$result = array();
while($rlt = mysql_fetch_array($sql,MYSQL_ASSOC))
{
$result[] = $rlt;
}
// If success everythig is good send header as “OK” and return list of users in JSON format
$this->response($this->json($result), 200);
}
$this->response(”,204); // If no records “No Content” status
}

DeleteUser
Delete user function based on the user_id value deleting the particular record from the users table Rest API URL http://localhost/rest/deleteUser/

private function deleteUser()
{if($this->get_request_method() != “DELETE”){
$this->response(”,406);
}
$id = (int)$this->_request[‘id’];
if($id > 0)
{
mysql_query(“DELETE FROM users WHERE user_id = $id”);
$success = array(‘status’ => “Success”, “msg” => “Successfully one record deleted.”);
$this->response($this->json($success),200);
}
else
{
$this->response(”,204); // If no records “No Content” status
}
}

Chrome Extention
A Extention for testing PHP restful API response download here Advanced REST client Application

.htaccess code
Rewriting code for friendly URLs. In the download code you just modify htaccess.txt to .htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ api.php?rquest=$1 [QSA,NC,L]RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ api.php [QSA,NC,L]RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^(.*)$ api.php [QSA,NC,L]
</IfModule>

 

In today’s tutorial I will show you how to open the wifisettings in android programatically.
This code comes handy when the user have not enabled the wifi and you want the user to enable it for your application to work.

Here is the code for that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.coderzheaven;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class OpenWifiSettingsDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button open = (Button)findViewById(R.id.open);
        open.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openWifiSettings();
            }
        });
    }
    public void openWifiSettings(){
        final Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.wifi.WifiSettings");
        intent.setComponent(cn);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity( intent);
    }
}

Here is the layout xml– main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="How to open Wifi Settings Demo"
    />
  <Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Open Wifi settings"
    android:id="@+id/open"
    />
</LinearLayout>

Wifi settings in android

Enhanced by Zemanta

by Paul Beusterien, Mobile Developer Solutions, Carl Stehle, Appception Inc. and Tomaz Kregar, Bucka IT

Image representing PayPal as depicted in Crunc...

Adding the Plugin to your project

Using this plugin requires Android Cordova (PhoneGap) and the PayPal Mobile Payments Library. The PayPal Mobile Payments Library can be downloaded here.

  1. Create an Android Cordova project. Details at http://docs.phonegap.com/en/2.0.0/guide_getting-started_android_index.md.html
  2. Put PayPal_MPL.jar into your project’s libs directory and add it to the build path. In Eclipse, right click on PayPal_MPL.jar and select Add to Build Path.
  3. Copy assets/www/ files into your project’s assets/www/ directory
  4. Copy src/com/phonegap/plugin/ files into your project’s src/com/phonegap/plugin/ directory
  5. Make sure your AndroidManifest.xml includes a superset of the permissions shown in the reference AndroidManifest.xml
  6. Add the com.paypal.android.MEP.PayPalActivity as shown in the reference AndroidManifest.xml
  7. Include the plugin registration in /res/xml/config.xml as shown in the reference config.xml
  8. Make sure the cordova.{version}.js filename in index.html matches the filename in your www directory.
  9. Deploy and test the app. The default environment is ENV_NONE.

Using the PayPal Sandbox

  1. Set up a PayPal buyer and seller sandbox account from https://developer.paypal.com/
  2. Update demo.js to use ENV_SANDBOX instead of ENV_NONE. See comments near bottom of demo.js
  3. In index.html, update the pmt_recipient field to your sandbox seller account

 

Helping URl: https://github.com/phonegap/phonegap-plugins/tree/master/Android/PayPalPlugin

 

Enhanced by Zemanta

Generische Objektklassen der IUM

 

This tutorial is specifically designed with the intention to understand the creation of the generic class and how it works.

What is a generic class?

Java generic is a term that is used to denote a set of features which are related to the use of generic types and methods. A Generic class in java is nothing but an interface which one can parameterize for different types. We can follow the below format when it comes to defining a Generic class.

1
Class name<t1, t2,="" …tn=""> {/*…*/}

The angle bracket defined above is basically used to specify the type parameters which are also known as type variables T1, T2..Tn.

We can customize the Java classes as well since we don’t have generics just limited to the predefined classes in the Java APIs. The below is an illustration of the declaration we learned above.

Listing 1: Customizing the Java classes

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Generic<E> {
    Class theClass = null;
    public Generic(Class theClass) {
        this.theClass = theClass;
    }
    public E createInstance()
    throws IllegalAccessException, InstantiationException {
        return (E) this.theClass.newInstance();
    }
}

What is <E>?

The alphabet E in the angle brackets displayed in the code above is a token that gives a hint that the class can have a type set once this is instantiated.

Let us understand the above said statement by using an example.

Listing 2: Defining type set

1
2
3
Generic<MyClass>  = new Generic<MyClass>(MyClass.class);
MyClass myClassInstance = createInstance();

Objective of Java Generics:

The main benefit of generic classes is that they are useful in early error detection at compile time. In order to get this benefit, we need to use a parameterized type such as LinkedList. This needs to be used in place of LinkedList and this will help the compiler to perform more type checks. This in turn requires lesser dynamic casts.

Using the above technique, it will be easier to detect the errors early since they will be reported at a compile time with the help of a compiler error message instead of getting an exception at run time.

Let us consider the example of LinkedList which is used to express the homogeneous list of elements. These homogenous lists of elements are of the type String.

Listing 3: Example of a parameterized type

1
2
3
LinkedList<String> list = new LinkedList<String>();
List.add(“abc”);
List.add(new Date());

Interfaces

In assition to classesclasses, we should also be aware of another hierarchy that is known by the name of interfaces which can be seen as a class specification. This however is not considered to be an implementation.

What does the interface lists?

An interface actually lists the method descriptors and not the actual code that are required by this interface. A class can always implement an interface by providing implementation to all methods declared in the interface. It is an interesting point to note that any class can be used to implement several interfaces and the only thing that is required to make this happen is the below method.

1
int compareTo(Object o) {...}

The advantage of using this method is that it helps the object to get compared -to other objects that are of the same type. The output of the above method could be in any form-positive, negative and even zero. This means the specified object here is either less than, greater than or equal to the object that is being passed as a parameter.

Generic type:

A generic type with formal type parameters is a declaration of a generic type with actual type of arguments. This is a reference type that has more than one parameter which are later replaced by type arguments the moment generic type is declared.

Listing 4: Example of a generic type

1
2
3
4
Interface Collections {
Public void add (E x);
Public Iterator iterator;
}

As discussed above the alphabet E in angle brackets is nothing but a place holder that will be later replaced by a type argument the moment generic type is declared.

Much on the similar lines of generic methods, the type parameter may comprise of more than one parameter that are separated by commas.

Why are these known as parameterized types? This is for the reason that they accept at least one parameter. Below is an example that illustrates this.

Listing 5: Example of a parameterized type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class GenericClassExample<X> {
private X a;
public void set(X a) {
this.a = a;
}
public X get() {
return a;
}
public static void main(String[] args) {
GenericClassExample integerObj = new GenericClassExample<Integer>();
GenericClassExample stringObj = new GenericClassExample<String>();
integerObj.set(new Integer(50));
stringObj.set(new String("Mrbool"));
System.out.printf("Integer Type Object's Value :%d\n\n", integerObj
.get());
System.out.printf("String Type Object's Value :%s\n", stringObj.get());
}
}

The below Listing displays the output of the above code:

Listing 6: Output

1
2
Integer Type Object’s value: 50
String Type Object’s value: Mrbool

Here it can be observed that after the creation of a integer type object, the type of the variable X is modified to integer and same is the case with the String type .

We can use the below code to create a generic array with the following method signature.

Listing 7: Creating the generic array

1
2
3
4
5
6
7
public static T[] createArray(List list,Class ){
       T[1..n] array = (T[]) Array.newInstance(class, list.size());
       for(int i = 0; i < array.length; i++){
           array[i] = list.get(i);
       }
       return array;
   }

The point to note here is that we will not be able to make arrays and generics work together with current versions of Java and can only define arrays for non-generic types, and do casts in all the accessory.

Here in this tutorial so far we have defined a generic interface MyInterface and several classes that implement this interface. We would now be creating an array of the members of which can be assigned any object belonging to a class that implements the interface.

We can also make this happen by using an Object array. However this can lead to the loss of type information and then it needs to be cast each time we get something from the array. The other workaround of this could be to consider java.lang.reflect.Array.newInstance( Class C, int size ). But again this would require a single class C which would end up with an array that will allow assignments of C subclass objects.

The best way to do it is to use the wildcard HashMap[] x=new HashMap[3] and the prime reason behind this design is to maintain compatibility with existing code which is directly related to generics.

At the time of writing a generic which is nothing but a parameterized class, we have the class declaration that normally contains the type parameter in angle brackets. After this, we can have methods in a parameterized class which can make use of that parameter in the form of a return type. Also it can be used for its parameter types. As a result of this, we will observe that methods will view the type similar to concrete type because of its declaration in the class. The below example displays what we just discussed:

Listing 8: class declaration

1
2
3
4
5
6
7
public class LinkedList<A> {
...
public A getFront() { ... }
...
public void setFront(A a1) { ... }
...
}

Here is nothing but a type parameter that is normally passed to the class upon declaration. The point to note here is that A is being used as a return type for one method and a parameter type for another.

At the time of writing a parameterized code, we can also limit the range of acceptable types. This can be done with the introduction of a definite upper boundary which can be set so that only subtypes of that bound can be passed as the type parameter. In order to see the upper bound, we can make use of the extend keyword as shown below.

1
public class LinkedList<K extends Comparable> { ... }

We can see that any class that is normally used to implement the interface Comparable can accept this implementation of LinkedList.

It is a must to specify the type parameter whenever an instance of a parameterized object is created and the below example explains this.

1
LinkedList<String> _list = new LinkedList<String>();

The objective of the above code is to create a LinkedList. This can only be used to contain String objects and then we will have the compiler check that the actual type which in this case is a String is a subtype of the bound of the type parameter. Otherwise, the code will not compile.

Conclusion

We learned several techniques to create Generic Java classes . Hope you liked the article.