Dropbox API: Get your files in your android app

    In this tutorial we will show you how to integrate Dropbox api with your android app and get all the file or folder from your Dropbox space to your own app.

    First download the Dropbox sdk for android from HERE.

    Now go to Apps Console from HERE. Here select the app type as "core". Write your app name in the space provided. You have two types of permission here: "app folder" & "full dropbox". Select app folder if you want to access a specific folder only from your Dropbox account or "full dropbox" if you want access of all the folder/files in your Dropbox account. Here you will get your "app key" and "app secret". Note these, as you will need this for your app.

    Now create a new android project in Eclipse IDE. Once you have the app keys, we'll need to enter the following snippet in your AndroidManifest.xml in order for the Dropbox SDK to finish the authentication process. Insert the following code under the <application> section, replacing APP-KEY with your app key:
<activity
      android:name="com.dropbox.client2.android.AuthActivity"
      android:launchMode="singleTask"
      android:configChanges="orientation|keyboard">
      <intent-filter>
        <!-- Change this to be db- followed by your app key -->
        <data android:scheme="db-INSERT-APP-KEY-HERE" />
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE"/>
        <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
    </activity>
Also make sure that your app has the internet permission by ensuring you have the following under the section of AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    Now import all the Dropbox libraries and dependencies in the libs folder into your Eclipse project. To add the libraries to your build path, perform the following actions in Eclipse: Right click on your project from the Package Explorer and go to Properties. Select Java Build Path from the sidebar. Add External JARs and add the libraries.

    Now you're all set to start interacting with the Dropbox Java and Android SDKs. Continue on to the next tutorial for more on the authentication process and to get started using the API methods.

    We'll need to put your app key and app secret in your code so we can use them to create a session and access your Dropbox account and the API. Replace INSERT_APP_KEY_HERE and INSERT_SECRET_HERE with your app key and app secret in the code below.
final static private String APP_KEY = "INSERT_APP_KEY_HERE";
final static private String APP_SECRET = "INSERT_SECRET_HERE";
When you created an app, you were prompted to decide whether you wanted to create your own app folder in the user's Dropbox (APP_FOLDER) or whether you wanted full Dropbox access (DROPBOX). Insert your choice here where it says INSERT_APP_ACCESS_TYPE_HERE.


final static private AccessType ACCESS_TYPE = AccessType.INSERT_APP_ACCESS_TYPE_HERE;
Create a Dropbox session 

The app keys are in place, now let's use them to create a new session. We'll use this session to create a new DropboxAPI object called mDBApi. You probably want to keep one of these around as an instance variable.

// In the class declaration section:
private DropboxAPI<AndroidAuthSession> mDBApi;


// And later in some initialization function:
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
Start the authentication process

 The next step in the process is for the user to authorize your app through either the official Dropbox mobile app or via the Dropbox mobile web site. The user will be sent to a screen with your app icon and name and buttons to allow or deny access to their Dropbox. If authenticated, your session will have the user's access token pair to use with API calls. Here we get the session and start the authentication process. startAuthentication() is a function that redirects the user to the Dropbox mobile app or, failing to identify its install, redirects to the mobile website for user authorization via the default mobile browser.
// MyActivity below should be your activity class name
mDBApi.getSession().startAuthentication(MyActivity.this);
Return to your app after user authorization 

Upon authentication, users are returned to the activity from which they came. To finish authentication after the user returns to your app, you'll need to put the following code in your onResume function. Please note, it's important that the order and the timing of these calls stay the same. In fact, it might be easier to just copy this code verbatim rather than writing it from scratch.
protected void onResume() {
    super.onResume();

    // ...

    if (mDBApi.getSession().authenticationSuccessful()) {
        try {
            // MANDATORY call to complete auth.
            // Sets the access token on the session
            mDBApi.getSession().finishAuthentication();

            AccessTokenPair tokens = mDBApi.getSession().getAccessTokenPair();

            // Provide your own storeKeys to persist the access token pair
            // A typical way to store tokens is using SharedPreferences
            storeKeys(tokens.key, tokens.secret);
        } catch (IllegalStateException e) {
            Log.i("DbAuthLog", "Error authenticating", e);
        }
    }

    // ...
}
      The finishAuthentication() method will bind the user's access tokens to the session. You'll now be able to retrieve them via mDBApi.getSession().getAccessTokenPair(). You'll need these tokens again after your app closes, so it's important to save them for future access. If you don't, the user will have to re-authenticate every time they access their Dropbox from your app. A common way to implement storing keys is through Android's SharedPreferences API. To learn how, check out the Android documentation. In the meantime, for simplicity, the code above pretends the storeKeys function invokes whatever method you'd like to use to store your keys in a more permanent location. If in the process of authenticating you run into an error message like "Another app on your phone may be trying to pose as the app you are currently using." it means more than one app installed on the phone has a callback activity registered for a single app key. You can fix this error by deleting one of the offending apps or by switching to a new app key.

Getting the folder listing:

      To get the Dropbox folder listing follow the below code snippet.
try{ 
ArrayList<String> folderName=new ArrayList<String>;
    Entry dropboxDir1 = mApi.metadata("/", 0, null, true, null);    
     if (dropboxDir1.isDir) { 
      
      
            List<Entry> contents1 = dropboxDir1.contents;
            
           if (contents1 != null) {
            folderName.clear();
            
                for (int i = 0; i < contents1.size(); i++) {
                    Entry e = contents1.get(i);
                    
                    String a = e.fileName();  
                   
                    
                    if(String.valueOf(e.isDir).equalsIgnoreCase("true")){
                     folderName.add(a);
                    }
                 }
           }
     }}catch (Exception ex) {
               
                   
           }
The folder listing will be store in "folderName" ArrayList. Now we will get the files under a particular folder. So here is the code:
try{ 
ArrayList<String> file_name=new ArrayList<String>;
    Entry dropboxDir1 = mApi.metadata("/"+folderName.get(pos), 0, null, true, null);    
     if (dropboxDir1.isDir) { 
      System.out.println("___isdir");
      
            List<Entry> contents1 = dropboxDir1.contents;
            
           if (contents1 != null) {
            file_name.clear();
            
                for (int i = 0; i < contents1.size(); i++) {
                    Entry e = contents1.get(i);
                    
                    String a = e.path;                                                              
                    file_name.add(a);                   
                 }
           }
     }}catch (Exception ex) {               
                   
           }
The file list will be store in "file_name" ArrayList.

Download a file:
To download a file follow the below code snippet:
FileOutputStream outputStream = null;
           try {
            sdCard = Environment.getExternalStorageDirectory();

               File file = new File(sdCard.getAbsolutePath()+"/temp");
               
               outputStream = new FileOutputStream(file);
               @SuppressWarnings("unused")
          DropboxFileInfo info = mApi.getFile(file_name.get(0), null, outputStream, null);
           } catch (Exception e) {
               System.out.println("Something went wrong: " + e);
           } finally {
               if (outputStream != null) {
                   try {
                       outputStream.close();
                   } catch (IOException e) {
                  System.out.println("___"+e);
                   }
               }
           }
Now you can get the file from "outputStream". Now you can use the file as needed.

Play video in android app from project resource...

           In this application we will play a video in our own app from the project resources.It is very easy to do. First of all make a simple xml layout containing a videoview and a button. When we will press the button video will start. So please collect a .3gp video and save it in raw folder under res folder. In our project we take the video name as test.3gp.
          So, here is the xml layout for this...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="PLAY" />

        <VideoView
            android:id="@+id/videoView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>
   

</LinearLayout>
Now we will write the java code to make the button working and start the video. Check it carefully.
package com.myandroid.videoPlayer;

import android.app.Activity;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.VideoView;

public class VideoPlayActivity extends Activity
{
Button btPlay;
VideoView vv;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btPlay=(Button)findViewById(R.id.button1);
        vv=(VideoView)findViewById(R.id.videoView1);
        btPlay.setOnClickListener(new OnClickListener()
        {
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
playVideo();

}

private void playVideo()
{
getWindow().setFormat(PixelFormat.TRANSLUCENT);
VideoView videoHolder = new VideoView(VedioPlayActivity.this);
videoHolder.setMediaController(new MediaController(VedioPlayActivity.this));
Uri video = Uri.parse("android.resource://" + getPackageName() + "/"  + R.raw.test);
videoHolder.setVideoURI(video);
setContentView(videoHolder);
videoHolder.start();

}
});
   
    }
}
Please note, this code will work on android 2.3.3 or higher(api 10 or higher).

Simple code to capture an image by camera from android powered devices...

    In this application by pressing a button,we will open the camera preview window. After that we will capture an image and save it to gallery of the device.So here comes the simple xml layout design for this. You can always make your layout design as per your need.

?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Capture Image" />

    <Button
        android:id="@+id/btCamera_main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Take Picture" />

</LinearLayout>
Now here is the activity class(CameraTestAppsActivity.java) that makes the button working...

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class CameraTestAppsActivity extends Activity {

Button btCamera;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btCamera=(Button)findViewById(R.id.btCamera_main);
              
        btCamera.setOnClickListener(new OnClickListener()
        {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
     startActivityForResult(intent, 0);

}
});
         
    }
   
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && requestCode == 0) {
                  String result = data.toURI();
    }
    }
}
In this code by tapping the button we call the camera intent class via this code snippet ...
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
then we use startActivityForResult(intent, 0); to get the result code when image capturing is complete. As a last step please add the following code snippet to your Android manifest.
<uses-permission android:name="android.permission.CAMERA"></uses-permission>

Set image dynamically by retrieving image name from a data source in android...

    Sometimes there may be situation,where we have the images in our project's drawable folder.But we have to set the images by getting the image name from a data source.In normal condition we can use "R.drawable.imageName"  and the image is set. But in this as we get the image name at run time,we have to set the images dynamically.
     So in this situation first we have to retrieve the image name from the data source(It can be a SQLite database or any other data source).Store it in a string variable.Note here,we have to store  the image name here(not with the extension).So if the data source gives you image name with extension then cut the name from the extension.We need "imageName" here,not "imageName.png".So follow the code below...
try {                
                Class<drawable> res = R.drawable.class;
                if(str!=null){                                    
                Field field = res.getField(str);
                int drawableId = field.getInt(null);
                bengalidaypng.setImageResource(drawableId);               
                }
            }
            catch (Exception e) {
                      System.out.println("Image not found in drawable folder");
            } 
         Here "str" is the string variable that hold the imageName retrieved from a data source.If the image with desired name not found in the project's drawable folder then the "catch" block will execute.Hope it is very easy to understand.Feel free to make a comment if you have a doubt.

Want to run a Progress dialog in your Android apps? Here is the way...

            Hey loving readers,in this post I will discuss about the Progress Dialog features in a android application.Usually we use it,when our application needs some time to process a request or waiting for a resource like internet connection or anything.So here I build a demo application to show you, how the progress dialog actually works.
            In this application we take a button.When we press the button,the progress dialog will appear and it also give the users information that what the application is doing in the background.Int this application we just count 0-900 value in background.You can show the counting in the logcat view(Eclipse IDE is used here).The progress dialog also give some information,when and what the application is counting.

screenshot 1
screenshot 2
screenshot 3

     After the counting process is over,the progress dialog will be dismissed and a toast will be  shown to inform the user that the counting process is completed.Then  the button can be pressed again and the counting process will begin.So simple! Isn't it?
     So lets take a look at the xml layout.It is really simple one with a button only with the name "Counting Button". Lets take a look....

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/button1"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="Counting Button" 
        android:layout_gravity="center" 
        android:layout_marginTop="100dp"
        />
</LinearLayout>

           Now it;s time for some java code,that actually runs the progress dialog.Note here, that we don't define a Progress Dialog widget in the xml file.This is not provided by the ADT plugin(Eclipse platform) as we don't need a Progress dialog at start up.We need it,when an event occurs,that requires some time.So we define it in the java file.Lets take a look....

package com.androidcookers.progressdialog;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/**
 * @author www.androidcookers.co.cc
 * {@link www.androidcookers.co.cc}
 *
 */
public class MyProgressbarActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final Button btn=(Button)findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {    
    new Progress().execute("ASD");
   }
  });
    }
    private class Progress extends AsyncTask{
     ProgressDialog pd;
     int count=0;
  public void onPreExecute(){
   pd=new ProgressDialog(MyProgressbarActivity.this);   
   pd.show();
  }
  @Override
  protected String doInBackground(String... params) {
   publishProgress(new Integer(1));
   for(int i=0;i<=300;i++){
    System.out.println(i);
   }
   publishProgress(new Integer(1));
   for(int i=301;i<=600;i++){
    System.out.println(i);
   }
   publishProgress(new Integer(1));
   for(int i=601;i<=900;i++){
    System.out.println(i);
   }
   pd.dismiss();//dismiss the progress dialog here...
   return null;
  }
  protected void onProgressUpdate(Integer... values){
   count++;
   if(count==1){
    pd.setMessage("Now counting 0 to 300...");  
   }
   if(count==2){
    pd.setMessage("Now counting 301 to 600...");
   }
   if(count==3){
    pd.setMessage("Now counting 601 to 900...");
   }
  }
  protected void onPostExecute(String result) {
   Toast.makeText(MyProgressbarActivity.this,"Counting completed!", Toast.LENGTH_LONG).show();
  }
    }     
}

             In this java file,first we initialize the button and when the button is pressed the Progress class is called.This class extends AsyncTask.That enable us to run a thread in the background,that process the counting task.It make us to implement the doInBackground() method.In this method the actual counting process is defined.We additionally define three other methods named onPreExecute(),onProgressUpdate() and the onPostExecute().
             The first one[onPreExecute()] makes a progress dialog object and initialize it. onProgressUpdate() method give us information when and what is counting. onPostExecute() method defines what will happen when the Progress dialog will be dismissed.In this application we showed a toast here.
             Don't forget to dismiss the progress dialog at the end of doInBackground() method by calling the dismiss method.Otherwise the progress dialog will continuously rotate even the background counting process is over.

Show Google Map on your android app.

     Showing Google map on your android application,you can make many useful application like gps tracker,navigation systems etc.But how to show Google map in your application?So follow this tutorial to get the Google map in some easy steps.

      First of all,make a project in your favorite IDE(this tutorial is based on Eclipse IDE).Here the important think is set your application build target as Google APIs.Otherwise you will not be able to use MapView widget.

      Now open the main.xml in layout folder.There you don't get some MapView widget that can be dragged & dropped like the other widgets(Button,EditText etc.). You have to write xml code for the MapView. Now lets check the code...

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <com.google.android.maps.MapView
        android:id="@+id/mapview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true"
        android:apiKey="Your Android Maps API key"
    />
</LinearLayout>

I-phone style tabbar in Android...

           By default we have a tabhost widget for android,that is shown at the top of the screen.This tabhost can be used effectively.But sometimes we want to move the tabhost at the bottom of the screen.There are to ways for this.
1:Using Relative Layout as a container of the tabhost childrens(i.e.:the tabcontents and the tab).
2:Give "android:layout_weight" the value "1".

1st approach(Using Relative Layout):
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <FrameLayout android:id="@android:id/tabcontent"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent"
             android:layout_alignParentTop="true"
             android:layout_above="@android:id/tabs" />
    <TabWidget android:id="@android:id/tabs"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:layout_alignParentBottom="true" />
             //this property moves the tabwidget to bottom
    </RelativeLayout>
</TabHost>

Now the 2nd approach(Using "android:layout_weight"):
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp">
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:layout_weight="1"/>
            //this property moves the tabwidget to bottom
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"/>
    </LinearLayout>
</TabHost>

But we want the I-phone style tab here.Now the tabhost is in bottom,but it does not look like the i-phone tabbar.
So we need to follow some steps that give us the following screen...
First of all make a new project with your desired name.Now define the "main.xml" in layout folder like this:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@android:id/tabhost" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 <LinearLayout android:orientation="vertical"
  android:layout_width="fill_parent" android:layout_height="fill_parent">
  <FrameLayout android:id="@android:id/tabcontent"
   android:layout_width="fill_parent" android:layout_height="0dip"
   android:layout_weight="1" /> 
  <TabWidget android:id="@android:id/tabs"
   android:layout_width="fill_parent" android:layout_height="wrap_content"
   android:layout_weight="0"  />
 </LinearLayout>
</TabHost>

Android chronometer timer...

             In this application we will use a chronometer,that will be act as a timer.So we take the xml layout containing a chronometer and three button widget.Here is the xml code for this:

THE XML LAYOUT
<?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:id="@+id/txt"
    />
    
    <Chronometer 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/chrono"
    />
    
    <Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/btnStart"
    android:text="Start"
    android:onClick="onClick"
    />
    
    <Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/btnStop"
    android:text="Stop"
    android:onClick="onClick"
    />
    
    <Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/btnReset"
    android:text="Reset"
    android:onClick="onClick"
    />
</LinearLayout>

Retrieve an image from internet...

           In this application,by pressing a button we can retrieve a image from internet by giving a link to the application code.For this we need a xml layout containing a button and a imageview widget.When the button is pressed,the image data is retrieved and showed in the imageview widget.Here is the xml code of the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:orientation="vertical">
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Connect"></Button>

<ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>
</LinearLayout>
      Now we will use three java class for this.In the first one named ImageReadMain ,we initialize the button and the imageview and define the onClick method of the button.In the second java class connection1 the code for connection is written in setNetwork() method.In the last one named Data class,we simply write a static bitmap variable,that we will use in previous two classes.

Now look at the ImageReadMain class...


package Image.Read.a;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

Connection with internet...

      In this application we connect with internet when a button is pressed.It gives a response code of 200 in LogCat view,when properly connected with server and page is found.
So,we take a xml layout with a button in it...And here is the code below..


<?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="@string/hello"
    />
<Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Connect"></Button>
<ImageView android:id="@+id/ImageView01" android:layout_height="100dip" android:layout_width="100dip"></ImageView>
</LinearLayout>


Here we use two java class.In the first one named MyConnection we initialize the button and add the onClick method and inside we call the callNetwork method of another class Connection.The MyConnection class is defined below:

Using SQLite database with Android...

        Android default Database engine is Lite. SQLite is a lightweight transactional database engine that occupies small amount of disk storage and memory, so its a perfect choice for creating databases on many mobile operating systems such as Android, IOS.

Things to consider when dealing with SQLite:
  1. Data type integrity is not maintained in SQLite, you can put a value of a certain data type in a column of another data type (put string in an integer and vice versa).
  2. Referential integrity is not maintained in SQLite, there is no FOREIGN KEY constraints or JOIN statements.
  3. SQLite Full Unicode support is optional and not installed by default.

In this tutorial we will create a simple database application to store employees data.
This DB has:
Tables:
  1. Employees
  2. Dept.
Views:
  1. ViewEmps: to display employees and their relative departments.
Creating SQLite Database:

      By default SQLite on Android does not have a management interface or an application to create and manage data bases from, so we're going to create the database ourselves by code.

     First we will create a class that handles all the operations required to deal with the database such as creating the database, creating tables, inserting and deleting records and so on.

     The first step is to create a class that inherits from SQLiteOpenHelper class. this class provides two methods to override to deal with the database:
  1. onCreate(SQLiteDatabase db): invoked when the database is created, this is where we can create tables and columns to them, create views or triggers.
  2. onUpgrade(SQLiteDatabse db, int oldVersion, int newVersion): invoked when we make a modification to the database such as altering, dropping , creating new tables.
Our class will have the following members :

public class DatabaseHelper extends SQLiteOpenHelper {

 static final String dbName="demoDB";
 static final String employeeTable="Employees";
 static final String colID="EmployeeID";
 static final String colName="EmployeeName";
 static final String colAge="Age";
 static final String colDept="Dept";
 
 static final String deptTable="Dept";
 static final String colDeptID="DeptID";
 static final String colDeptName="DeptName";
 
 static final String viewEmps="ViewEmps";
The Constructor:
 
public DatabaseHelper(Context context) {
  super(context, dbName, null,33); 
  }
The constructor of the super class has the following parameters:

Context con: The context attached to the database.
DataBaseName: The name of the database.

CursorFactory: some times we may use a class that extends the 
Cursor class to implement some extra validations or operations on the 
queries run on the database. In this case we pass an instance of 
CusrsorFactory to return a reference to our derived class to be used 
instead of the default cursor,

         In this example we are going to use the standard Cursor Interface to 
retrieve results, so the CursorFactory parameter is going to be null.

Version: The version of the schema of the database.

The constructor creates a new blank database with the specified name and version.

Android shared preferences code...

       In this application we will use shared preferences to remember a piece of data entered by user,that can be used later during application reuse.The data can be a user settings,a piece of user name or password or anything.

      Here we simply save a piece of string and later we will use it after application restart.So here we take a xml layout containing a EditText widget and a button.When we will press the button the data in EditText is saved and when the application is restarted the data will still be there for using.So here is the xml code:
<?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="@string/hello"
    />
<EditText
    android:id="@+id/EditText01"
    android:layout_height="wrap_content"
    android:layout_width="200dip">
</EditText>
<Button 
    android:id="@+id/Button01"
    android:layout_height="wrap_content"
    android:layout_width="150dip"
    android:text="Save">
</Button>
</LinearLayout>
Now we write the java code for the application.Look carefully...

AutoComplete widget code...

In this android application we will use Auto Complete features.I mean, when user try to start typing a string in a AutoCompleteTextView field,it gives suggesion as per user input.For this we take some strings in our code.When the user input matches with one or more string the strings are shown accordingly.Then the user can type the full text or simply select the desired string from the list.In our code the selected string is shown in a TextView.
For this application we will take a XML layout containing a TextView and a AutoCompleteTextView.The XML code is:

<?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:id="@+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<AutoCompleteTextView android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:completionThreshold="3"/>
</LinearLayout>


Now we write the code to implement the AutoCompleteTextView widget.The strings in the array(items) are the suggestion that will pop up during user input.Now look at the code below:

package com.android.autocomplete;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;

public class AutoCom extends Activity implements TextWatcher{

Custom ListView code...

To make a custom ListView here we will use two XML layout.One is the main layout,where the ListView widget is taken and another is simple_list XML,where a TextView with a background.The ListView items will be shown above this TextView.So the code of main is:

<?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="@string/hello"
    />
<ListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/statelist"></ListView>
</LinearLayout>


And the code of simple_list.xml is:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:padding="1dip" android:layout_height="wrap_content">
   
    <TextView android:id="@+id/toptext" android:gravity="center_vertical" android:layout_height="wrap_content" android:padding="5dip" android:layout_width="fill_parent" android:textColor="#000000" android:background="@drawable/textfield" android:focusable="true"/>

</LinearLayout>

Here in the drawable folder of the project we take a  image that is linked for the TextView background.In this project the image name is "textfield".(Remember,always give the image name a lower case name with no special character and image format should be png.).

Now it is time for the code.For this we take a array of string with different strings.(Here we use the states of USA).Now watch the code carefully:

package com.custom.list;


Passing intent value to another activity...

In this program we will pass value of a intent to another activity class.This is pretty simple.We have to use putExtra() method to pass the value.
For this we will take two XML layout.One is the main and another is newintent.The XML code for the main is

<?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="@string/hello"
    />
<Button android:text="@+id/Button01" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

Here we take a button.when we press it the value is passed to the NewIntent Activity.We take another XML (newintent)with a TextView.The passed value will be shown in this TextView.The XML code for newintent:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
</LinearLayout>

Now we code the MyValue class.(Notice,by convention we should start a class name with capital letter and a XML name with a small letter.)In this class the value(the string "hello") is given that will be passed.

package com.value.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MyValue extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Button btn = (Button)findViewById(R.id.Button01);
        btn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                String a = "hello";
                Intent intent = new Intent(MyValue.this,NewIntent.class);
                intent.putExtra("extra_value", a);
                startActivity(intent);
            }
           
        });
    }
}

Here in this code we create a object named intent of Intent class.The value of "a" is passed to NewIntent class via putExtra.Now we code the NewIntent class.

package com.value.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class NewIntent extends Activity{
   
    public void onCreate(Bundle savedInsatanceState){
        super.onCreate(savedInsatanceState);
        setContentView(R.layout.newintent);
        TextView tv=(TextView)findViewById(R.id.TextView01);
       
        Intent intent = this.getIntent();
       
        String value = intent.getStringExtra("extra_value");
        tv.setText("Carried value is:::"+value);
    }

}

Here the most important things to remember is,we have to register the new Activity class NewIntent in the Android manifest.For this we have to open the manifest,open the Activity tab and there we have to add the NewIntent Activity.Otherwise it will give a runtime error,when the button will be pressed.

Find your location via GPS...

        In this program we can calculate the GPS location.First we have to take a XML layout that contains a simple button and a textView widget.When we click the button,it gives us a toast containing the GPS location.Here is the XML code for the layout:

 <?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="@string/hello"
    />
<Button android:text="@+id/Button01" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

Now it's time for some coding.For this we will use three java class here.

The class MyGps.class is the main class here,where the button click event is defined.

package com.android.gps;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MyGps extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
       final  Button btn = (Button)findViewById(R.id.Button01);
       
      
       btn.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            gpsLocation gp = new gpsLocation(MyGps.this);
            gp.getlocation();
            Toast.makeText(MyGps.this, Data.Gps, Toast.LENGTH_LONG).show();
           
        }
          
       });
  
}

In this code when we click the button the go object of gpsLocation class (that is defined in the next java code) is created.This gp with the getLocation() method(defined in gpsLocation class) fetch the gps location and show it with the toast.Now it's time for the gpsLocation class:

Using Intents to launch activities:

we can use Intents to launch the phone's basic activities such as the phone dialer, the browser or search.

these intents are called implicit intents cause you don't specify the activity you want to launch, rather Android determines the proper activity to launch based on the required action. also when the launched activity finisheds its work, the original activity has no information that the launched activity has finished it's work

in this example we create an intent that performs a phone number dial action. we don not specify that we want the dialer activity to launch, rather we specify that we want to dial a number and Android launches the dialer activity to perform this action

consider this activity: consists of a TextView and a button to dial the number in the text view.

<?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="Enter the phone number"
        />
    <EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/txtNumber"
    android:inputType="phone"
    />
    <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Dial"
    android:id="@+id/btnDial"
    />
    </LinearLayout>


This is the XML layout.Now to use the DIAL button we need the following java code...