Saturday, June 29, 2013

What is the difference between C# and C++?

        C# is a programming language that is derived from C programming language and C++ programming language. C# is uniquely designed to be used in .NET platform. The differences between C# and C++ are: 
C#
C++
C# is a high level language that is component oriented.
C++ is a low level and indeed platform neutral programming language.
When compiled, C# code is converted into Intermediate language code. This intermediate language code is converted into executable code through the process called Just-In-Time compilation.
When compiled, C++ code is converted into assembly language code.
In C#, memory management is automatically handled by garbage collector.
In C++, the memory that is allocated in the heap dynamically has to be explicitly deleted.
In C# Switch Statement, the test variable can be a string.
In C++ Switch Statement, the test variable cannot be a string.
In C# switch statement, when break statement is not given, the fall through will not happen to the next case statement if the current case statement has any code.
In C++ switch statement, when break statement is not given, the fall through will happen to the next case statement even if the current case statement has any code.
In addition to for, while and do..while, C# has another flow control statement called for each.
C++ does not contain for each statement.
C# struts can contain only value types. The struts is sealed and it cannot have a default no-argument constructor.
C++ struts behave like classes except that the default access is public instead of private.
In C#, delegates, events and properties can also be specified as class members.
In C++, only variables, constructors, functions, operator overloads and destructors can be class members. Delegates, events and properties cannot be specified as class members.
In C#, the end of the class definition has a closing brace alone.
In C++, the end of the class definition has a closing brace followed by a semicolon.
The access modifiers in C# are public, private, protected, internal and protected internal.
The access modifiers in C++ are public, private, protected. C++ does not have internal and protected internal access modifiers.
C# has finally block in exception handling mechanism. The code statements in the finally block will be executed once irrespective of exception occurrence.
C++ does not have finally block in exception handling mechanism.
The exception in C# can only throw a class that is derived from the System.Exception class.
The exception in C++ can throw any class.
C# does not have the concept of function pointers. C# has a similar concept called Delegates.
C++ has the concept of function pointers.

ASP.Net Web API and REST Services

            This article explains what a REST Service actually is and how the ASP.NET Web API helps with the creation of such services.

What Is a Restful Service?

Representational State Transfer (REST) is an architectural style. A service that conforms to the REST constraints is referred to as being RESTful

To be RESTful, a service has to conform to the following mandatory constraints:
  1. Client-Server constraint, which is based on the separation of concerns, is about separating user interface concerns from data storage concerns. Clients are not concerned with data storage, which is a concern of servers, and servers are not concerned with the user interface or user state, which are concerns of clients. 
  2. Stateless constraint, is about each request being an independent self-contained unit with all the necessary information for the server to service the request without looking at anything else for the context. 
  3. Cache constraint, is about the server being able to label a response as Cacheable or not, so that the client handles the response appropriately from the point of view of later use.
  4. Layered constraint, is about composing the system into layers, with each layer being able to see and interact with only its immediate neighbor. A layer cannot see through its neighbor. Between the client and the server, there could be any number of intermediaries; caches, tunnels, proxies, and so on.
  5. Uniform Interface constraint, is about providing a uniform interface for identification of resources, the manipulation of resources through representations, self-descriptive messages, and hypermedia as the engine of the application state.
Let's see how a service built with the ASP.NET Web API Framework satisfies the given constraints.

The client-server constraint is an easy one to satisfy since the ASP.NET Web API is all about responding to the client request with the data, without bothering about the client state or how data will be presented to the end user.

The stateless constraint can also be easily satisfied, unless something horrible is done such as using the ASP.NET session state from the web API.

ASP.NET MVC supports the OutputCache attribute that can be used to control output caching. The ASP.NET Web API has no built in ways to support this feature out of the box, but it's easy to roll out our own action filter attribute. The ASP.NET Web API can use a Cache-Control response header to label a response as Cacheable or not. By default, Cache-Control is set to no-cache and the response is not cached. This way it satisfies the Cache constraint.

The layered constraint is more along the infrastructure line-proxies, firewalls, and so on. There is nothing special that needs to be done from the ASP.NET Web API to satisfy this constraint.

The uniform interface constraint includes the following four constraints and is a key factor in deciding if an HTTP service is RESTful or not:
  1. Identification of resources
  2. Manipulation of resources through representations
  3. Self-descriptive messages
  4. Hypermedia as the engine of application state (HATEOAS)
Let's have a look at a unique interface constraint in detail through each of the four constraints.

1. Identification of Resources

A resource is any data that a web API sends to its clients. Examples could be an individual employee in your company, a product that your company sells etc. In the real world, a product or an employee could be uniquely identified through an identifier, such as a product ID or an employee ID.

In the case of RESTful web services, a resource is identified by a Uniform Resource Identifier (URI). An employee with an identifier of 12345 will be represented by http://myServer/employees/12345. In the case of the ASP.NET Web API, the URI can be slightly different and it includes "api" by default in the URI, so it will be more like http://myServer/api/employees/12345. If you fire up an instance of Internet Explorer, enter that URI in the address bar, and press Enter then Internet Explorer does an HTTP GET and you will get the JSON representation of the resource, which is an employee with the ID of 12345 in this case.

From the .NET code point of view (see Listing 2-1), the corresponding class will be EmployeesController, which is a subclass of ApiController and the method that executes to create the resource representation to be sent back to the client in its Get(int) method. Observe the code snippet below:

Identification-of-Resources.jpg

Picture 1 - Identification of Resources

You see here that a known resource with the URI representation http://myServer/api/employee/12345 is accessed using the GET HTTP Method. A list of employees is also a resource identified by http://myServer/api/employees pointing to the GetAllEmployees() method.

2. Manipulation of Resources through Representations

The example of a user typing http://myServer/api/employees/12345 in Internet Explorer can be described as a user requesting a resource using the GET verb and getting back the employee JSON, which is the representation of the resource. GET is guaranteed not to cause any side effect and is said to be nullipotent; nothing happens to the system's state, even when called multiple times or not called at all. In other words, the system state will be the same for all the following scenarios: (1) method was not called at all, (2) method was called once, and (3) method was called multiple times.

Other important verbs are POST, PUT, and DELETE. POST is for creating a new resource, PUT is for updating an existing resource, and DELETE is for deleting an existing resource. PUT and DELETE are idempotent; the effect to the system state will be the same as that of the first call, even when called multiple times subsequent to the first call.

To create a new employee, the client sends a POST request, with the new employee (JSON or XML representation) in the body of the request. This request gets mapped to a method with a name starting with Post, which is Post(Employee) in this case.

Updating an employee is the same as creating a new employee except that the PUT verb is used and mapping is based on the name starting with Put. One important difference compared to POST is that PUT is idempotent. If a user sends multiple requests to update an employee to the same state, no error must be sent back.

Deleting an employee is similar except that a resource representation is not needed. A DELETE request against the URI will be sufficient to delete the resource. Similar to PUT, the DELETE method is also idempotent. Even if the underlying data source sends an error back when the employee to be deleted no longer exists, because it is already deleted in response to the previous request then no error must be sent back.

Manipulation-of-Resources-through-representations.jpg

Picture 2 - Manipulation of Resources through representations

For all the preceding actions, a status code is the means through which the status of the action is communicated back. By default it is 200 – OK, indicating success. As a special case, 201 – Created gets sent for POST, when a resource was created. 401 – Not Authorized gets sent when a user requests an action on a resource that requires the user to be authenticated and that user has either not provided the credentials or provided invalid credentials. 404 – Not Found gets sent when the user has requested an action on a resource that does not exist.

3. Self-Descriptive Messages

A resource can have multiple representations, JSON and XML being just two examples. A request body having a specific representation of a resource must have a self-description of the representation so that it is parsed and handled correctly. The same holds for responses.

In the ASP.NET Web API, the Multipurpose Internet Mail Extensions (MIME) type determines how the web API serializes or deserializes the message body. There is built-in support for XML, JSON, and form-url encoded data. 

Let's take the case of a request to create a new employee, the corresponding code snippet in the picture below, to review a few scenarios.

Self-Descriptive-Messages.jpg

Picture 3- Self-Descriptive Messages

Scenario 1: JSON Representation

Here is an example of a request–response message pair with JSON being the content type for both messages. The web API determines the media-type formatter to be used based on the content type. Because it is JSON, it uses JsonMediaTypeFormatter to deserialize JSON in the CLR object of type Employee named value. Again on the way out, the CLR object to be returned, in this case an object of Employee type, is serialized into JSON. If the request content type comes in as XML then XmlMediaTypeFormatter would have been used to deserialize and this entire process is seamless to the action method code, since it always receives the Employee object. This is one of the powerful features of the ASP.NET Web API.

Request Sent

POST /api/employees HTTP/1.1
Content-Type: application/json; charset=utf-8
Content-Length: 49
{"Name":"John Q Law", "Department":"Enforcement"}

Response Received

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{"Department":"Enforcement","Id":"123","Name":"John Q Law"}

Scenario 2: No Content Type

What if there is no content type specified in the request header? The ASP.NET Web API will not know what to do with the message. The web API returns 500 – Internal Server Error with a message that no MediaTypeFormatter is available to read the object of the type Employee with media type undefined.

Request Sent

POST /api/employees HTTP/1.1
Content-Length: 49
{"Name":"John Q Law", "Department":"Enforcement"}

Response Received

HTTP/1.1 500 Internal Server Error
Content-Type: application/json; charset=utf-8
{"ExceptionType":"System.InvalidOperationException","Message":"No 'MediaTypeFormatter' is available to read an object of type 'Employee' with the media type ''undefined''.","StackTrace":" at System.Net.Http.ObjectContent.SelectAndValidateReadFormatter(..."}

Scenario 3: XML Representation

If the content type is specified for XML and the XML representation of the resource is sent in the request message body then it starts to work again. The web API uses XmlMediaTypeFormatter, although this time around the resource sent back in the response also becomes XML.

Request Sent

POST /api/employees HTTP/1.1
Content-Type: application/xml; charset=utf-8
Content-Length: 80
<Employee><Name>John Q Law</Name><Department>Enforcement</Department></Employee>

Response Received

HTTP/1.1 200 OK
Content-Type: application/xml; charset=utf-8
<?xml version="1.0" encoding="utf-8"?><Employee xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Id>123</Id><Name>John Q Law</
Name><Department>Enforcement</Department></Employee>

Scenario 4: Mix and Match

It is possible to mix and match, that is, send the XML representation of the resource in the request body and ask for JSON to be returned or vice versa. If a web API is capable of handling the content type specified in the Accept header then it will send the resource in that representation. In the following example request, the client sends the request body as XML and indicates the same by specifying application/xml in Content-Type. However, the client prefers the response to be returned as JSON and indicates that preference by specifying application/json in the Accept header.

Request

POST /api/employees HTTP/1.1
Content-Type: application/xml; charset=utf-8
Accept: application/json
Content-Length: 80
<Employee><Name>John Q Law</Name><Department>Enforcement</Department></Employee>

Response

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{"Department":"Enforcement","Id":"123","Name":"John Q Law"}

The key point to note in this transaction is that the client asks and does not tell the server. If the Accept header of application/pdf, application/json is sent in the request then the ASP.NET Web API will not be able to send the response back as PDF, by default, and hence switches to the second choice, JSON. This process is therefore called Content Negotiation.

It is interesting to note that a web API switches to XML if the Accept header has just the application/pdf. It can't send a PDF for sure but there is nothing else specified as the second choice, so it switches over to the MIME type of the request, which is XML in this case.

4. Hypermedia as the Engine of Application State

The HATEOAS constraint requires a client to enter a RESTful service through a fixed URL. From that point onward, any future action a client takes will be based on what the client gets to discover within the resource representation returned by the service.

Let's take an example. A client makes a GET request to the resource with the identifier http://server/api/employees. In other words, the client is asking for a list of employees. As the next step, if the client needs to GET an employee, how will it go about doing it? One option is that the client "knows" it! Then, the client has to know quite a bit about the service. Another option is hypermedia, or hypertext. A service that satisfies the HATEOAS constraint returns not just data, but data and links.
In the previous example of the employee listing, each employee can have multiple links; one to look at employee details, or one perhaps to fire him, for example. Of course, the links available will be based on what the client is authorized to do. For a user who is not authorized to fire employees, there is no point in sending the firing link. Here is an example JSON representation of an employee resource with links.

Hypermedia-as-the-Engine-of-Application-State.jpg

Picture 4 - Hypermedia as the Engine of Application State

One obvious problem is what the client will do with the links. To get details, GET must be executed and for the next one, DELETE, probably, but how will the client know? The answer to the question is forms, which will contain all the necessary information for the client to make the next move.

HATEOAS is not supported by the ASP.NET Web by default if you expect a web API to provide links or forms intelligently without ever writing a line of code. However, it is possible to include them in the resource representation returned by writing your own custom code.
 
Thanks : c-sharpcorner



Thank you for reading this article, I hope you enjoyed it. Feedback and comments are highly appreciated. Follow for more!!

REST(Representational state transfer) Software Architecture



                         
                  The REST architectural style was developed by W3C Technical Architecture Group in parallel with HTTP/1.1, based on the existing design of HTTP/1.0. The World Wide Webrepresents the largest implementation of a system conforming to the REST architectural style. REST exemplifies how the Web's architecture emerged by characterizing and constraining the macro-interactions of the four components of the Web, namely origin serversgatewaysproxies and clients, without imposing limitations on the individual participants. As such, REST essentially governs the proper behavior of participants.
REST-style architectures consist of clients and servers. Clients initiate requests to servers; servers process requests and return appropriate responses. Requests and responses are built around the transfer of representations of resources. A resource can be essentially any coherent and meaningful concept that may be addressed. A representation of a resource is typically a document that captures the current or intended state of a resource.
The client begins sending requests when it is ready to make the transition to a new state. While one or more requests are outstanding, the client is considered in transition. The representation of each application state contains links that may be used the next time the client chooses to initiate a new state-transition.
REST facilitates the transaction between web servers by allowing loose coupling between different services. REST is less strongly typed than its counterpart, SOAP. The REST language uses nouns and verbs, and has an emphasis on readability. Unlike SOAP, REST does not require XML parsing and does not require a message header to and from a service provider. This ultimately uses less bandwidth. REST error-handling also differs from that used by SOAP.

Friday, June 28, 2013

Creating Your First Android Application (SMS App)

                  Beginning Android tutorial series covered the overview of the Android platform. If you haven't seen it yet, please take some time to read it before reading this article.

                  In this article, you will develop your first Android application. You will learn how to send SMS programmatically within an Android application.
NOTE: This tutorial assumes that you are familiar with Java programming and IDE's like Eclipse and NetBeans.



Brief Contents
  1. The Four Components of Android
  2. Creating The SMS Application
    • Obtaining The Required Tools
    • Developing SendingSMS project



The Four Components of Android

Your Android projects should contain at least one class that is derived from one of these components:
  • Activity - If your Android application has a UI, you must create one class that extends this component. You will learn how to create an Activity in this article.
  • Service - If your Android application has a long running task, you should do it in the background and not in the UI thread. This class provides the facility to make a task run in the background.
  • BroadcastReceiver - If your Android application will receive and respond to global events such as the sending and delivery of SMS, your class must be registered as a subclass of this component. You will learn how to use this component to get feedback after sending SMS.
  • ContentProvider - If your Android application has data that you wants to share with other Android applications, you should create and implement this component.
For the detailed look at the Android Build process please refer to Android documentation.

Creating The SMS Application

Android development has four phases. Below is a diagram of Android development process:

Obtaining The Required Tools

Before you can start creating Android application, you must setup your development environment first. You will need the following to develop our SMS application:
  • Android SDK
  • Eclipse (Helios or greater)
NoteYou need to install at least the Android 1.6 platform for this tutorial.
See Android Installation Instructions and System Requirements for more information and watch this video to learn how to setup your development environment for the first time on Windows. 
I use Windows 7, Java 7, Eclipse Indigo for Java Developers, ADT and Android SDK revision 17 in this screencast.

Developing The SMS Project

SMS messaging is one of the killer applications on Android or any mobile phones today. Let's create your first simple and practical Android project. I assume that you are already familiar with Java programming; I will not explain each line of code in detail.

Follow these steps:
1. Start your Eclipse IDE

2. Go to File -> New -> Project

3. Select Android Project in the New Project dialog
4. Complete the New Android Project wizard.



5. Open main.xml (located in <your project's name>/res/layout) and replace its contents with the code below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <EditText
        android:id="@+id/editRecipient"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="14dp"
        android:hint="@string/recipientHint"
        android:inputType="phone" />
    <EditText
        android:id="@+id/editMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="17dp"
        android:layout_toLeftOf="@+id/sendButton"
        android:hint="@string/messageBodyHint" >
    </EditText>
    <Button
        android:id="@+id/sendButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/editMessage"
        android:onClick="send"
        android:text="@string/sendButtonText" />
</RelativeLayout>
Note: I used RelativeLayout here because I need to align each common form component relative to the other components.
6. Open SMSActivity.java (located in <your project's name>/src/<your package name>) and add the following code:
public void send(android.view.View view) {
final android.widget.EditText recipient = (android.widget.EditText) findViewById(R.id.editRecipient);
final android.widget.EditText message = (android.widget.EditText) findViewById(R.id.editMessage);
final android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault();
final String addr = recipient.getText().toString();
final String text = message.getText().toString();
smsManager.sendTextMessage(addr, null, text, null, null);
recipient.setText("");
message.setText("");
}
7. To allow our application to send SMS, add the following permission to AndroidManifest.xml (located in your project's root directory):
<uses-permission android:name="android.permission.SEND_SMS" />
8. That's it. Deploy and run the project.


How It Works

Steps 1 to 4 show you how to create a new Android application in Eclipse. Steps 5 to 7 cover the code that will enable your new application to send SMS: step 5 changes the layout of your application's UI; step 6 includes the actual code that sends an SMS, and; step 7 includes a code snippet that informs our users about the permissions the application needs to send SMS. Step 8 shows you how to run the application.

The application uses the built-in Android telephony API class `android.telephony.SmsManager` to send SMS; for more information, see: documentation of SmsManager API.







Using Sqlite database in android

To quote from the website of sqlite
"SQLite is a software library that implements a self-contained serverless zero-configuration transactional  SQL database engine."
It is small database which an android programmer can use conveniently in his/her program.

Let us learn how to use sqlite database in steps.

Opening database : openOrCreateDatabas e fuction can be used to open an existing db or create a new one if it does not exist.
SQLiteDatabase mydb;
mydb = mContext.openOrCreateDatabase("mysqdb",
SQLiteDatabase.OPEN_READWRITE, null);

 First parameter is name of database and second one is mode of opening the file. Third parameter if present will be cursorfactory which is used to allow sub classes of cursor to be returned from a query. You can even use openDatabase function. On success the db is returned. The function throws SqliteException if there is error.

Next let us try to create a table with 3 fields - id, name and salary. We need to have a string which stores the create table sql statement.
String sqlStatement = "create table if not exists  nameSal" +  
"(_id Integer PRIMARY KEY AUTOINCREMENT ,Name text, salary Integer)";
mydb.execSQL(sqlStatement);

Note that _id field is made primary key as well as auto increment which will ensure each row gets unique _id automatically.
if not exists clause ensures that if the table is already present, there will not be any error. And the function call just returns.

execSQL will execute the SQL statement and creates the table. 

Next let us see, how to add records to the table. To add records to the table, you can use contentValues and insert statement.
ContentValues v=new ContentValues();
 v.put("name", "Anil");
 v.put("salary", 24000);  
 mydb.insert("nameSal" , null, v);

You store key-value pairs in contentValues and then use insert function which takes table name as first parameter, nullColumnhack as second parameter and contentValue as third parameter.

Next let us consider how to extract data from our table. A query function can be used for this purpose. Query  will return a cursor.
mCursor = mydb.query(nameSal, null, null, null, null,
  null, null);

Here first argument is the table name to query.
Second argument is the column list to return- if null all columns are returnred
Third argument is selection like where clause in select statement excluding where
Fourth argument are the values to be filled for ? in selection 
Fifth argument is group by clause 
sixth argument is having clause which denotes which row groups to be returned
seventh argument is order by column
eighth argument is maximum number of columns to be returned

Let us look at another example using query
Cursor c = mydb.query("nameSal",new String[]{"name","salary"},
"salary > 26000",
null,
null,null,
"salary ASC ",null);
Here the query will return the columns name and salary given by second argument, where salary is greater than 26000 (the condition is given by 3rd argument). The rows returned will be arranged in ascending order of salary(7th argument).

Once we get the cursor, we can iterate through the rows using loop. Look at the example below.
c.moveToFirst();
do{ String name = c.getString(0); int salary = c.getInt(1); Toast.makeText(this, "name is "+name+" salary is "+salary, 2000).show(); }while(c.moveToNext());


c.moveToNext  method will return false when the end is reached.

Android Tips and Tricks

Tips
  • Visual cue for scrolling: When you are in a scrollable list (like your Gmail inbox) and you reach the end of the list it shows an orange hue—a visual cue that you can’t scroll anymore.
  • Notification bar icons (Wi-Fi, network coverage bars, etc.): Turn green when you have an uninhibited connection to Google, white when you don't. Hint: if you're in a hotel or airport using Wi-Fi, the bars won't turn green until you launch the browser and get past the captive portal.
  • Voice actions: Tell your phone what to do by pressing the microphone icon next to the search box on the home screen, or long press the magnifying glass. You can tell it to send an email or text message (“send text to mom, see you for pizza at 7”), call someone ("call mom"), navigate somewhere (“navigate to pizza”), or listen to music ("listen to Mamma Mia").
  • Find things you’ve downloaded from your browser: Your downloads are now neatly collected in a Downloads manager, which you can find in the apps drawer.
  • Turn a Gallery stack into a slideshow: In Gallery, when you are looking at a stack of photos, put two fingers on the stack and spread them. The stack spreads out and the pictures flow from one finger to the other, a moving slideshow that lets you see all of the photos.
  • Walk, don’t drive: Once you’ve gotten directions within Google Maps, click on the walking person icon to get walking directions.
  • Easy text copy/paste from a webpage: To copy/paste from a webpage, long press some text, drag the handles around to select the text you want to copy, and press somewhere in the highlighted region. To paste, simply long press a text entry box and select paste. Gmail is a bit different: you need to go to Menu > More > Select Text.
  • Turn your phone into a Wi-Fi hotspot: Go to Settings > Wireless & Networks > Tethering & Portable Hotspot. (You may have to pay extra for this feature.)
  • Look at Maps in 3D: With the latest release of Google Maps , you can now look at 3D maps. Tilt the map by sliding two fingers vertically up/down the screen, and rotate it by placing two fingers on the map and sliding in a circular motion, e.g., from 12 and 6 o’clock to 3 and 9.
  • Cool shutdown effect: When you put the phone to sleep, you’ll see an animation that resembles an old cathode tube TV turning off.
Keyboard tricks
  • Shift+Key to capitalize a word: In Gingerbread (and supported hardware), you can Shift+Key to capitalize a letter instead of going to a separate all caps keyboard.
  • Auto-complete: The space bar lights up when auto-complete can finish a word.
  • Quick replace: Tap on any previously typed word, then tap on a suggestion to automatically replace it with the suggested word.
  • Easy access to special characters (like numbers, punctuation): Press and hold any key to go to the special character keyboard. You can also press and hold the "," key for an extensive punctuation keyboard.
Applications
  • Angry Birds: Popular game that lets you knock down blocks by slingshotting birds.
  • Astro: Awesome file explorer app. Browse and access the directories on your phone, and take full advantage of its capabilities. Great if you’re a power user.
  • Chrome to Phone: This one is really useful for Chrome users. You can send anything you browse on your computer to your phone. So if you are heading out to a restaurant or party and look up directions on your computer, just click the “send to phone” button (requires Chrome to Phone extension) and that exact page will open on your phone. Same with virtually any webpage.
  • Flash: Install from Android Market to watch Flash videos embedded throughout the web. Runs even better on Gingerbread.
  • Fruit Ninja: A juicy action game that tests your ability to smash flying fruit. A fun time-killer on the bus or train.
  • FXCamera: Popular photo sharing app with slick effects and filters.
  • Google Maps: Use your device as a GPS navigation system with free turn-by-turn voice guidance, and take advantage of other Google Maps features like Street View, Latitude and Places.
  • Instant Heart Rate: Measure your heart rate using your camera.
  • Phoneanlyzr: Track your phone usage: who you text most, call most, average call length distribution, etc.
  • RemoteDroid: Control your computer from your phone. Gives you a mobile wireless mouse and keyboard. Great if you’re using your computer for music or movies.
  • Shazam: Identifies virtually any song you are listening to.
  • SoundHound: Record a snippet of a song and get it identified instantly. You can even hum (if you can carry a tune!).
  • Tango: A free, high-quality video call app that works on both 3G and Wi-Fi. If your device has a front facing camera (e.g., Nexus S), you will love this app.
  • YouTube: New UI. Plus, portrait-mode player, and view comments and drop-down box video information

Using multiselect list with a dialog box


        AlertDialog is a versatile dialog. It can be used even for displaying a list where multiple values can be checked.

First you create a alertdialog.
AlertDialog.Builder  d = new AlertDialog.Builder(yourcontext);

Next you create the array which holds the items to be displayed

 String elements [] = {"Burger","Pizza","Cake","Coke","Fruits"};

Next you add multichoiceitems to the dialog

d.setMultiChoiceItems(elements, null , new OnMultiChoiceClickListener() {
 @Override
 public void onClick(DialogInterface dialog, int which, boolean isChecked) {
       if(isChecked){
          String str = elements[which];
          Toast.makeText(youractivity.this,
                    "you have selected"+str,
                     Toast.LENGTH_LONG).show();
        }
   }
 });
d.setPositiveButton("Save", new OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
yourOnClickMethod();
   }
});
d.show();
Now our dialog looks something like this



 The second parameter to setMultiChoiceItems is a boolean array, which will have true for all items which must be checked. If you do not want any to be checked, it can be null as we have used.
e.g
boolean selected[]= {true,false,false,true,true};
d.setMultiChoiceItems(elements,selected,
new OnMultiChoiceClickListener(){
                    --------
                    -------
});
With this modification, initially first, fourth and fifth items will be checked.

Tabs with different background colors

I was trying to have different colors for android tabs instead of normal grey and whitish grey.Finally i got it. Here is the code

View view = new MyView(this, R.drawable.custombutton, R.drawable.custombutton, "Channels");
       //         channelTabSpec = tabhost.newTabSpec("channels").setIndicator(view)
        .setContent(intent);
 tabhost.addTab(channelTabSpec);
---
----
---
Similarly I created two more tabs in application. The class MyView used above is 
private class MyView extends LinearLayout {
          ImageView iv;
          TextView tv;
          public MyView(Context c, int drawable, int drawableselec, String label) {
           super(c);
       
           tv = new TextView(c);
           tv.setText(label);
         
           tv.setGravity(Gravity.CENTER);
           tv.setBackgroundColor(Color.TRANSPARENT);
           tv.setTextColor(Color.WHITE);
           tv.setTextSize(14);
         
           tv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
             LayoutParams.WRAP_CONTENT, (float) 1.0));
           setOrientation(LinearLayout.VERTICAL);
           Drawable d = getResources().getDrawable(drawableselec);
           tv.setBackgroundDrawable(d);
         
            addView(tv);
       
          }
         }

I have created a file custombutton.xml in the folder /res/drawable for having different appearances for the normal tab and selected tab. Here is the file

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="false">
        <shape>
            <gradient android:startColor="@color/darkblue"  android:centerColor="@color/lightblue"
                android:endColor="@color/darkblue" android:angle="270" />
            <stroke android:width="1dp" android:color="@color/lightblue" android:radius="1dp"/>
             <corners android:radius="5dp" />
            <padding android:left="1dp" android:top="20dp"
                android:right="1dp" android:bottom="20dp" />
        </shape>
    </item>
    <item android:state_selected="true">
        <shape>
            <gradient android:endColor="@color/steel_blue"  android:gradientRadius="50"
                android:startColor="@color/blue" android:angle="270" android:type="radial" />
              
            <stroke android:width="1dp" android:color="@color/lightblue" />
            <corners android:radius="5dp" />
            <padding android:left="1dp" android:top="20dp"
                android:right="1dp" android:bottom="20dp" />
        </shape>
    </item>
  

</selector>

First item is for non-selected tab and second for selected. In selected tab we are using radial gradient with start color and end color. In non-selected tab we are using linear gradient with start color, center color and end color and angle as 270. Angle can be 90, 180, and 270. Other values for angle will crash the program. Center color is optional.

You can get more info about custom shapes in this android tutorialhttp://developer.android.com/guide/topics/resources/drawable-resource.html
At the end, my tabs look like this. Well don't bother about color combination, I know I am not so good in that.



The gradient type can be linear, radial or sweep - linear is default. For selected tab I am using radial gradient.

Notice one more thing here, I am defining two shapes - one for selected and another for not selected - using selector. If you want to use this for button you can use android:state_pressed and android:state_focused and define different shapes for these.
Look at another example where I am defining different drawable pngs for different states
<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false"
         android:drawable="@drawable/lightbtn" >
       
    </item>
    <item android:state_pressed="true"
        android:drawable="@drawable/darkbtn">
       
    </item> 
   

</selector>

This xml file is stored as mybutton.xml in /res/drawable-hdpi and I use the following line in my layout file
----
----
<Button
    android:layout_height="wrap_content"                 android:layout_width="wrap_content"
    android:id="@+id/okbutton"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="50dp"
    android:background="@drawable/mybutton">
    </Button>

I have lightbtn.png and darkbtn.png in my /res/drawable-hdpi . Now when I touch the button darkbtn is displayed else lightbtn is displayed