Thursday, September 30, 2010

Best Android Phones 2010

Android fans now becoming more and more, here are Best Android Phones 2010, check now below:
1. Google Nexus One: Google Nexus One that features the best of them are equipped with processors made by Qualcomm Snapdragon 1 GHz and 2.1 Android operating system is not used on any device. Nexus One other feature of this 3.7-inch AMOLED touchscreen, 5 megapixel camera, WiFi connectivity, accelerometer, and a digital compass.
nexus one google phone
2. HTC EVO 4G: HTC Evo is the Android-based phones are connected with the 4G network. The phone is equipped with a 1GHz processor, 4.3-inch screen, dual video cameras, each of which has a 8MP resolution, and 1.3 Megapixel.
Sprint HTC EVO 4G
3. HTC Droid Incredible: Incredible considered commensurate droid opponents even exceed the iPhone. Its features include 3.7 inch AMOLED screen multitouch, Snapdragon processor 1 GHz, 8-megapixel camera with dual-LED flash, Wi Fi and integrated GPS. Android operating system 2.1 with HTC user interface Sense.
Droid Incredible
4. Sony Ericsson Xperia X10: Xperia X10 comes with a screen width up to 4 inch capacitive touchscreen and of course to the processor using the Qualcomm Snapdragon processor 1GHz. This phone also uses 8.1 megapixel camera that has been equipped with LED flash, microUSB Card slot and will use the Google Android OS version 1.6.
Sony Ericsson XPERIA X10
5. Motorola Backflip: Motorola Backflip comes with a 1.3 inch touchscreen display, 320 x 480 pixel resolution, and a QWERTY keyboard that can be folded behind the screen. This phone has a unique folding design and equipped with WiFi, Bluetooth 2.0, GPS, GSM networks 850/900/1800/1900 850/900/1700/1900/2100 W-CDMA, Qualcomm MSM7201A 528 MHz processor, 512MB of ROM storage, and RAM 256MB.
Motorola Backflip


Your Ad Here

Wednesday, September 29, 2010

Passing data to activity

Launching an activity is not all. After launching another subactivity/activity you might want to send some data/parameter to that activity. This is done in a new way known as Bundle. To launch an activity we create an intent. Suppose our intent name is "intent". We can put data with the intent like this

intent.putExtra("keyName", "somevalue");

We can add multiple entries here. This is a key,value pair. So to receive this data from the receiving activity we have to write this code

Bundle extras = getIntent().getExtras();
if(extras !=null)
{
String value = extras.getString("keyName");
}

This is how we can send data to another activity, here simple string is sent, complex structures like array can be also sent through bundle. Didn't use those as i am a bad bad programmmer and very bad at reading documentations ;).



Your Ad Here

Tuesday, September 28, 2010

How to download and display Images in android

In this article, let's turn our attention to some bread-and-butter issues—like connecting your Android application to the Web to download files.
Very often, you need to connect your Android application to the outside world, such as downloading images as well as consuming web services. This article will show you how to make your Android application communicate with the outside world using an HTTP connection.


public class main extends Activity {
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        Bitmap bitmap =
            DownloadImage(
            "http://ichart.finance.yahoo.com/instrument/1.0/%5ENSEI/chart;range=1d/image;size=239x110");
        ImageView img = (ImageView) findViewById(R.id.ImageView01);
        img.setImageBitmap(bitmap);
    }
private Bitmap DownloadImage(String URL)
    {      
        Bitmap bitmap = null;
        InputStream in = null;      
        try {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return bitmap;              
    }
private InputStream OpenHttpConnection(String urlString)
    throws IOException
    {
        InputStream in = null;
        int response = -1;
              
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
                
        if (!(conn instanceof HttpURLConnection))                    
            throw new IOException("Not an HTTP connection");
      
        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();

            response = httpConn.getResponseCode();                
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                                
            }                    
        }
        catch (Exception ex)
        {
            throw new IOException("Error connecting");          
        }
        return in;    
    }
}


Please add permission to access internet in androidmanifest.xml file..
<uses-permission android:name="android.permission.INTERNET"></uses-permission>.




I hope you found this article helpful...

Your Ad Here

Monday, September 27, 2010

Multicolumn ListView in Android

Ever since I started programming on the Android platform, I have been wondering when the SDK would include a ready-made multicolumn ListView (or listbox as it is often called in other frameworks). One could of course construct such a thing by slapping regular ListViews side by side and then painfully adding code to keep them all in sync when scrolled and so on. It felt such a hack that I used GridView instead. GridView is not really a great list, though, because the cells will all be formatted the same. There are other issues besides that, but for me that was the main one.
I finally saw a blog post which customized ListView to put two TextViews vertically into one line. It was pretty simple going from there to one that would display three TextViews side-by-side. The main layout XML file could define ListView something like this:
<!-- main.xml -->
<ListView android:id="@+id/SCHEDULE" android:layout_width="wrap_content" android:layout_height="wrap_content">
</ListView>
Here is the XML for each row, main point being that we put three TextViews in LinearLayout with horizontal orientation:
<?xml version="1.0" encoding="utf-8"?>
<!-- row.xml -->
<LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:paddingTop="4dip"
     android:paddingBottom="6dip"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal">
 
     <TextView android:id="@+id/TRAIN_CELL"
         android:layout_width="50dip"
         android:layout_height="wrap_content"/>
 
     <TextView android:id="@+id/FROM_CELL"
         android:layout_width="70dip"
         android:layout_height="wrap_content" android:layout_weight="1"/>
 
     <TextView android:id="@+id/TO_CELL"
         android:layout_width="60dip"
         android:layout_height="wrap_content"  android:layout_weight="1"/>
</LinearLayout>
Notice how you can format each TextView separately. There is no column separator, but something decent should not be too hard to whip up if desired. My understanding is that the screen width is supposed to be 160 dip, but for some reason I had to use width values that actually add up to more than that, as well as using layout weight to grow some fields proportionally so that when you switch to landscape mode things are still nicely aligned. I would have expected specifying widths in dip would have automatically done that.
Here is how you could populate that ListView with data:
ListView list = (ListView) findViewById(R.id.SCHEDULE);
 
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("train", "101");
map.put("from", "6:30 AM");
map.put("to", "7:40 AM");
mylist.add(map);
map = new HashMap<String, String>();
map.put("train", "103(x)");
map.put("from", "6:35 AM");
map.put("to", "7:45 AM");
mylist.add(map);
// ...
mSchedule = new SimpleAdapter(this, mylist, R.layout.row,
            new String[] {"train", "from", "to"}, new int[] {R.id.TRAIN_CELL, R.id.FROM_CELL, R.id.TO_CELL});
list.setAdapter(mSchedule);
The main point here is that the SimpleAdapter requires the data to be in a List, where each entry is a Map. In my case, I simulate the columns by putting in three entries into each of the maps, and the maps each have the same keys. The adapter then maps the key values (like "train") to the corresponding TextView (R.id.TRAIN_CELL).
Putting the above pieces of code into Caltroid produces results that look like this:
Multicolumn ListView in Android
Multicolumn ListView in Android




Your Ad Here

Sunday, September 26, 2010

Starting new Activity in Android

An Android application, at most, contains more than one screen. But, how we can open a new screen after clicking a button, choosing a menu, or other? It is not too difficult to do in Android.

There are a few step to do, to open a new screen in android. You have to create an activity class, an xml layout, update AndroidManifest to know your second/third .. activity class, and put a code to call the new activity / screen.

An Activity class can be created with extending from Activity, ListActivity or other Activity class. Each Activity Class should have an xml layout as a view screen as a representation of the Activity Class.

Android Manifest should be updated to know the new activity / screen. so, when requested to show the new screen, it knows which class to execute.

At last you should put a piece of code to first screen, to show the new screen. Below is an example to open a new screen:

//screen1.java


package test.android;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.Button;

public class Screen1 extends Activity
{
   public void onCreate(Bundle icicle)
   {
      super.onCreate(icicle);
      setContentView(R.layout.screen1);
      Button b = (Button) findViewById(R.id.btnClick);
      b.setOnClickListener(new View.OnClickListener() {
         public void onClick(View arg0) {
         Intent i = new Intent(screen1.this, screen2.class);
         startActivity(i);
         }
      });
   }
}

//screen1.xml


<?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="You are in the first Screen"
/>
<Button
   id ="@+id/btnClick"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Open New Screen"
/>

</LinearLayout>

//screen2.java


package test.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

public class Screen2 extends Activity
{
   public void onCreate(Bundle icicle)
   {
      super.onCreate(icicle);
      setContentView(R.layout.screen2);
      Button b = (Button) findViewById(R.id.btnClick2);
      b.setOnClickListener(new View.OnClickListener() {
         public void onClick(View arg0) {
         setResult(RESULT_OK);
         finish();
         }
      });
   }
}

//screen2.xml

<?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="You are in the New Screen"
/>
<Button
   id ="@+id/btnClick2"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Close"
/>

</LinearLayout>

//AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="test.android">
   <application android:icon="@drawable/icon">
      <activity class=".Screen1" android:label="Screen 1">
         <intent-filter>
         <action android:value="android.intent.action.MAIN" />
         <category android:value="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      <activity class=".Screen2" android:label="Screen 2">
      </activity>
   </application>
</manifest>


Your Ad Here

Saturday, September 25, 2010

Android SQLite Basics: creating and using a database, and working with sqlite3

Because I often have to revisit this stuff myself, I thought I would write a quick reference tutorial on creating and using a database with an Android application. This isn't terribly well covered in the Android docs, and though many ContentProvider tutorials exist (such as the Unlocking Android code for chapter 5, and the NotePad tutorial included with the SDK), and these help a lot with general database concepts, they are really more complicated than what a basic application needs - a database to store and retrieve stuff.


I will walk through the code and tools for an oversimplified example here, with the ultimate goal of inserting and retrieving some data from an database in an Android app, and then examining the database using a shell and the sqlite3 command line tool. 
NOTE This code was updated for part 2, and part 3 of this series, so it no longer exactly matches this example -- it's still a working sample app, it just now does a bit more than the original.
First, to get this rolling, we need to create an Android application that HAS a database. We could use any built in application that has a database just to explore it, such as com.android.alarmclock), but we are going to create one here for completeness. After it's setup, the interface for our application will look like the screen shot shown below:
Android Examples
Yeah this project is ugly, and it only has one Activity, but for our purposes here we really aren't trying to create a fancy UI (or anything that is complicated on any level). To create this project we will use the Eclipse IDE. Along with Eclipse, we will also of course need to have the Android SDK with the correct Eclipse ADT Plug-In as a prerequisite too (to get that see the instructions at the aforelinked site).
1. To create a basic Android project, we will simply select File->New->Other->Android->Android Project. On the dialog we will then enter the application name AndroidExamples, and the package name com.totsp.androidexamples, along with some other settings, as shown in the figure below:
Create Android Project with Eclipse
The target we choose must be one that we have installed when we setup or configued the Android SDK. For this example we are using 1.6 because it is still the most common Android platform that user's phones are running (we are using the 2.1 SDK, with a 1.6 Target). We will also set the "Min SDK Version" to "4" which is SDK 1.6. This is a confusing part of the Android setup at this point (names are transposed from "sdk" to "api" and such) but the details are documented somewhat.
Once we have the default sample project in place, the next step will be to create a helper class that can create the database and encapsulate other SQL details. We will call this class DataHelper. Within this class (at the end) we will include an important inner class that provides a SQLiteOpenHelper. The full code is shown below:


package com.android.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import java.util.ArrayList;

import java.util.List;

public class DataHelper {
 private static final String DATABASE_NAME = "example.db";
  private static final int DATABASE_VERSION = 1;
  private static final String TABLE_NAME = "table1";

  private Context context;
  private SQLiteDatabase db;

  private SQLiteStatement insertStmt;
  private static final String INSERT = "insert into "
     + TABLE_NAME + "(name) values (?)";

  public DataHelper(Context context) {
     this.context = context;
     OpenHelper openHelper = new OpenHelper(this.context);
     this.db = openHelper.getWritableDatabase();
     this.insertStmt = this.db.compileStatement(INSERT);
  }

  public long insert(String name) {
     this.insertStmt.bindString(1, name);
     return this.insertStmt.executeInsert();
  }

  public void deleteAll() {
     this.db.delete(TABLE_NAME, null, null);
  }

  public List<String> selectAll() {
     List<String> list = new ArrayList<String>();
     Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
       null, null, null, null, "name desc");
     if (cursor.moveToFirst()) {
        do {
           list.add(cursor.getString(0));
        } while (cursor.moveToNext());
     }
     if (cursor != null && !cursor.isClosed()) {
        cursor.close();
     }
     return list;
  }

  private static class OpenHelper extends SQLiteOpenHelper {

     OpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
     }

     @Override
     public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT)");
     }

     @Override
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w("Example", "Upgrading database, this will drop tables and recreate.");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
     }
  }
}

This class is simple, as I have said it would be. For example it's using a database with one table and one column, but, it still covers some core Android concepts. We won't go into great detail concerning this class here, it should be mostly understandable from the code, but a few important things to note are:
  • it includes an implementation of SQLiteOpenHelper as an inner class
  • it demonstrates two different ways of interacting with the database in code, with aSQLiteStatement for inserts (which has the advantage of being pre-compiled, versus regular, but easier SQLiteDatabase.query() methods you probably also want to be familiar with), and directly by querying for selects
  • it shows a useful pattern (though again, oversimplified here) of exposing data persistence/retrieval methods on the helper
To use this class from the default Main.java class that we let the Android Eclipse Plug-In generate, we will modify it a bit to create an instance of our DataHelper and then use it to create and retrieve data as seen below.(NOTE: In the real world you might do this once per application, say by using the oft overlooked Android Application class, where you could create the DataHelper once, and then expose the reference to other classes, rather than in Activity.onCreate()):


package com.android.database;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;


public class Main extends Activity {
private TextView output;

  private DataHelper dh;

/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
 this.output = (TextView) this.findViewById(R.id.out_text);
      
        this.dh = new DataHelper(this);
        this.dh.deleteAll();
        this.dh.insert("Porky Pig");
        this.dh.insert("Foghorn Leghorn");
        this.dh.insert("Yosemite Sam");      
        List<String> names = this.dh.selectAll();
        StringBuilder sb = new StringBuilder();
        sb.append("Names in database:\n");
        for (String name : names) {
           sb.append(name + "\n");
        }
      
        Log.d("EXAMPLE", "names size - " + names.size());
      
        this.output.setText(sb.toString());
    }
}
For this class to work, we also need to change the main.xml layout file it relies on. We need to include one additional TextView for the output, as seen below:


<?xml version="1.0" encoding="utf-8"?>
<ScrollView
  xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content">
  <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="@string/hello" />
    <TextView android:id="@+id/out_text"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="" />
  </LinearLayout>
</ScrollView>

With that, we have an application that we should be able to launch and run in the emulator, and it should look like the first screen shot we saw above - a basic black screen with white text and a few names as output. The names come from the database, which now exists, and now we can move on to using sqlite3.
Android uses SQLite as it's built in embedded database. If you need to store local application data, rather than going to simpler mechanisms like the file system, or more complicated means such as the network, you use the database.
To examine the database we can login using the shell provided by the Android Debug Bridge. To use this we need the "tools" folder of the SDK on our path (see the SDK documentation if you need more information about that). If we start the app in Eclipse (Run As -> Android Application), and leave it running, we should then be able to login with the command:
ccollins@crotalus:~$ adb -e shell
# 

The -e option tells ADB to use the emulator, rather than a possible connected device (and returns an error if more than one emulator is running). The "#" is the command prompt, we are logged in.
Once logged in we can browse around with the "ls" command. The directory we are interested in is/data/data/com.totsp.androidexamples/databases (each application has a directory at the path /data/data/PACKAGE_NAME). We can change to that directory with the "cd" command. Once there we can use the command line SQLite tool, sqlite3, to examine our database, as follows:
# sqlite3 example.db
SQLite version 3.5.9
Enter ".help" for instructions
sqlite> select * from sqlite_master;
table|android_metadata|android_metadata|3|CREATE TABLE android_metadata (locale TEXT)
table|table1|table1|4|CREATE TABLE table1 (id INTEGER PRIMARY KEY, name TEXT)
sqlite> 
We login with "sqlite3 [database_name]" and then we can run basic SQL commands that are supported by SQLite (see the documentation there for full details). One handy table is thesqlite_master that we can see shows all the other tables inside our database.
Some other interesting commands are:
sqlite> .schema
CREATE TABLE android_metadata (locale TEXT);
CREATE TABLE table1 (id INTEGER PRIMARY KEY, name TEXT);
sqlite> .tables
android_metadata  table1          
sqlite> select * from table1;
1|Porky Pig
2|Foghorn Leghorn
3|Yosemite Sam
sqlite> 
We can use .help from within the sqlite3 shell (it has it's own shell, apart from the emulator shell we are logged in to), to see a full list of commands. Commands that start with "." are built in, and perform a function - such as .schema and .tables that we see above. SQL commands themselves can also be run directly by typing them in -- something we also see above (typed commands are run as soon as a ; is encountered and you press enter).

With that, we have the basics. We have an application that creates a database and stores and retrieves data using it, and we have done a bit of exploring with the SQLite tools in ADB. In the future I hope to expand on this article and add some more involved tables, and further examples such as Android unit testing (another not so well documented, but extremely useful, part of the platform).

Your Ad Here

Friday, September 3, 2010

Samsung Launches Galaxy Tab

Samsung has finally revealed the Galaxy Tab, a tablet computer running Android 2.2 that will begin shipping in October in Europe. A launch date for the U.S. was not revealed. The tablet can be used to surf the Web, watch movies, read e-books, navigate using GPS -- and even make phone calls, according to Samsung.The Galaxy Tab has a 7-inch touchscreen with a resolution of 1024 by 600 pixels, and a 1GHz Cortex A8 processor with 16GB of integrated storage. There is also a MicroSD card slot that can expand the storage capacity with another 32GB.

The higher resolution, compared to Android-based smartphones, is compatible with about 85 percent to 90 percent of applications on the Android Market, according to Samsung. The company is also working with developers of some of the most popular applications that don't work to help them convert their applications, it said.

The screen is based on TFT, instead of AMOLED, which Samsung uses on some of its smartphones. The concession was made to lower the cost of the product and improve battery life, which should last up to eight hours, according to Samsung.

On the front is a 1.3-megapixel camera for video calls or conferencing, and on the back a 3-megapixel camera with a LED lamp. The Tab weighs 380 grams, and measures 19 centimeters by 12 cm by 1.2 cm.

The tablet's lower weight and ability to make phone calls are two of the main advantages it has over Apple's iPad, Samsung said. The Galaxy Tab is a product you use on the go, and the iPad is for the living room, Samsung said. The iPad has a 9.7-inch touchscreen and weighs up to 730 grams.

So far, Samsung doesn't want to comment on pricing, but the tablet will be sold via operators with subsidies and monthly plans.

Users can connect to the Internet using HSPA (High-Speed Packet Access) at up to 7.2M bps (download) or 5.76M bps (upload), or at even higher speeds over 802.11n Wi-Fi networks. When not surfing the Web, users can watch movies in a number of different formats, including DivX, Xvid, WMV and MPEG-4.The fact that the Tab is based on Android version 2.2 means it also has Adobe Flash 10.1.Other software on board includes Samsung's TouchWiz 3.0 addition to the Android user interface and Social Hub, an application that collects messages from different social networks in one place. Samsung developed TouchWiz and Social Hub for its smartphones.

The Tab also will come with Hubs for accessing ebooks, magazines, newspapers, music and movies. The latter will only be available in the U.S. Samsung will install Layar, an augmented reality application, and Swype, which allows users to input text on a touchscreen by gliding their finger from one letter to another on a virtual keyboard, as well. For users who don't like virtual keyboards, Samsung will also offer a hardware keyboard as an accessory.

The Galaxy Tab is the first, but not the last tablet from Samsung, which expects to launch a family of such products at different price points and sizes. Also, the Galaxy Tab will get a Gingerbread update, which is the next version of Android.

Your Ad Here