Tuesday, July 12, 2011

Exercise AndroidMapper, Android Application using MapView

In the previous exercises, the MapView track the GPS and center on it repeatly. In this exercise, AndroidMapper, it will not track on GPS. Instead, there are three options to center in starting of the MapView.
- Default: Start ViewMap without any center location.
- GPS: It's the current GPS (which will be track before ViewMap start). If no valid GPS, this option will be disable.
- Location: User input location. If no location input, this option will be disable.

This application is not yet finished, more feature (or bug fixed) will be added in the furture.

Create a Android Application named, AndroidMapper.
Package Name: com.AndroidMapper
Target Google Platform 2.0 with Google APIs.

Modify main.xml to have the UI as seen in the picture.


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"
/
RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
RadioButton
android:id="@+id/option_default"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Default Location" /
RadioButton
android:id="@+id/option_gps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GPS:" /
android:id="@+id/option_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location:" /
RadioGroup
TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="latitude"
/
EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/latitude"
android:inputType="numberDecimal"
/
TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="longitude"
/
EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/longitude"
android:inputType="numberDecimal"
/
Button
android:id="@+id/loadmap"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Load Map"
/
LinearLayout


import com.google.android.maps.GeoPoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;

public class AndroidMapper extends Activity {

private LocationManager myLocationManager;
private LocationListener myLocationListener;
private GeoPoint GeoPoint_GPS, GeoPoint_Location;

RadioButton myoption_default, myoption_gps, myoption_location;
EditText mylatitude, mylongitude;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

loadMenu();
validGPS();
validLocation();

myLocationManager = (LocationManager)getSystemService(
Context.LOCATION_SERVICE);

myLocationListener = new MyLocationListener();

myLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
myLocationListener);
}

private void loadMenu()
{
setContentView(R.layout.main);
myoption_default = (RadioButton)findViewById(R.id.option_default);
myoption_gps = (RadioButton)findViewById(R.id.option_gps);
myoption_location = (RadioButton)findViewById(R.id.option_location);
mylatitude = (EditText)findViewById(R.id.latitude);
mylongitude = (EditText)findViewById(R.id.longitude);

mylatitude.setOnKeyListener(locationOnKeyListener);
mylongitude.setOnKeyListener(locationOnKeyListener);

Button myLoadMapButton = (Button)findViewById(R.id.loadmap);
myLoadMapButton.setOnClickListener(myLoadMapButtonOnClickListener);
}

Button.OnClickListener myLoadMapButtonOnClickListener =
new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(myoption_default.isChecked()){
OpenIntentAndroidMapView(null);
}
else if(myoption_gps.isChecked()){
OpenIntentAndroidMapView(GeoPoint_GPS);
}
else if(myoption_location.isChecked()){
OpenIntentAndroidMapView(GeoPoint_Location);
}
else{
OpenMissingOptionDialog();
}

}

};

private void OpenIntentAndroidMapView(GeoPoint startLocation)
{
Intent intent = new Intent();
intent.setClass(AndroidMapper.this, AndroidMapView.class);

Bundle bundle = new Bundle();

if (startLocation == null)
{
bundle.putInt("Mode", 0);
}
else
{
bundle.putInt("Mode", 1);
bundle.putInt("Longitude", startLocation.getLongitudeE6());
bundle.putInt("Latitude", startLocation.getLatitudeE6());
}

intent.putExtras(bundle);
startActivityForResult(intent, 0);
}

private void OpenMissingOptionDialog()
{
new AlertDialog.Builder(this)
.setTitle("missing selection")
.setMessage("Please select one of the option")
.setPositiveButton("OK",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialoginterface, int i)
{}
})
.show();
}

EditText.OnKeyListener locationOnKeyListener =
new EditText.OnKeyListener(){

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
validLocation();
return false;
}

};

private void validGPS()
{
GeoPoint_GPS = loadGPS();
if (GeoPoint_GPS==null)
{
myoption_gps.setClickable(false);
}
else
{
myoption_gps.setText("GPS: (" +
String.valueOf((float)GeoPoint_GPS.getLatitudeE6()/1000000) +" : " +
String.valueOf((float)GeoPoint_GPS.getLongitudeE6()/1000000) +")");
myoption_gps.setClickable(true);
}
}

private void validLocation()
{
/*
Toast.makeText(AndroidMapper.this,
mylatitude.getText().toString(),
Toast.LENGTH_LONG).show();*/
if (mylatitude.getText().toString().equals("") || mylongitude.getText().toString().equals(""))
{

myoption_location.setText("Location: ");
myoption_location.setClickable(false);
myoption_location.setChecked(false);
}
else
{
float locationLatitude = Float.parseFloat(mylatitude.getText().toString());
float locationLongitude = Float.parseFloat(mylongitude.getText().toString());

myoption_location.setText("Location: (" +
String.valueOf(locationLatitude) +" : " +
String.valueOf(locationLongitude) +")");
myoption_location.setClickable(true);
myoption_location.setChecked(true);

GeoPoint_Location = new GeoPoint(
(int)(locationLatitude*1000000),
(int)(locationLongitude*1000000));
}
}

private GeoPoint loadGPS()
{
//Get the current location from GPS
myLocationManager = (LocationManager)getSystemService(
Context.LOCATION_SERVICE);
Location initLocation=myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(initLocation != null)
{
return (
new GeoPoint(
(int)(initLocation.getLatitude()*1000000),
(int)(initLocation.getLongitude()*1000000)));
}
else
return null;
}

private class MyLocationListener implements LocationListener{

@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
GeoPoint_GPS = new GeoPoint(
(int)(location.getLatitude()*1000000),
(int)(location.getLongitude()*1000000));
myoption_gps.setText("GPS: (" +
String.valueOf((float)GeoPoint_GPS.getLatitudeE6()/1000000) +" : " +
String.valueOf((float)GeoPoint_GPS.getLongitudeE6()/1000000) +")");
myoption_gps.setClickable(true);
}

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub

}

}

LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"

LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"

LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

CheckBox
android:id="@+id/satellite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Satellite "
/
/LinearLayout
LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"

TextView
android:id="@+id/longitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Longitude:"
/
TextView
android:id="@+id/latitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Latitude:"
/
/LinearLayout
/LinearLayout
com.google.android.maps.MapView
android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:apiKey=""
/



import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class AndroidMapView extends MapActivity {

private TextView myLongitude, myLatitude;
private CheckBox mySatellite;

private MapView myMapView;
private MapController myMapController;

private void SetSatellite()
{
myMapView.setSatellite(mySatellite.isChecked());
};

@Override
protected void onCreate(Bundle icicle) {
// TODO Auto-generated method stub
super.onCreate(icicle);
setContentView(R.layout.mymapview);

Bundle bundle = this.getIntent().getExtras();
int Mode = bundle.getInt("Mode");

myMapView = (MapView)findViewById(R.id.mapview);
myMapController = myMapView.getController();
myMapView.setBuiltInZoomControls(true);

myLongitude = (TextView)findViewById(R.id.longitude);
myLatitude = (TextView)findViewById(R.id.latitude);
mySatellite = (CheckBox)findViewById(R.id.satellite);
mySatellite.setOnClickListener(mySatelliteOnClickListener);

SetSatellite();


if(Mode == 1)
{
int intLatitude = bundle.getInt("Latitude");
int intLongitude = bundle.getInt("Longitude");
GeoPoint initGeoPoint = new GeoPoint(intLatitude, intLongitude);
CenterLocation(initGeoPoint);
}


}



@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}

private void CenterLocation(GeoPoint centerGeoPoint)
{
myMapController.animateTo(centerGeoPoint);


myLongitude.setText("Longitude: "+
String.valueOf((float)centerGeoPoint.getLongitudeE6()/1000000)
);
myLatitude.setText("Latitude: "+
String.valueOf((float)centerGeoPoint.getLatitudeE6()/1000000)
);
};

private CheckBox.OnClickListener mySatelliteOnClickListener =
new CheckBox.OnClickListener(){

public void onClick(View v) {
// TODO Auto-generated method stub
SetSatellite();
}
};

}

xmlns:android="http://schemas.android.com/apk/res/android"
package="com.AndroidMapper"
android:versionCode="1"
android:versionName="1.0"
application android:icon="@drawable/icon" android:label="@string/app_name"
activity android:name=".AndroidMapper"
android:label="@string/app_name"
intent-filter
action android:name="android.intent.action.MAIN" /
category android:name="android.intent.category.LAUNCHER" /
/intent-filter
/activity
activity android:name=".AndroidMapView"
/activity
uses-library android:name="com.google.android.maps" /
/application
uses-permission android:name="android.permission.INTERNET" /
uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /
uses-sdk android:minSdkVersion="5" /

AndroidLocation: with a CheckBox to toggle MapView.setSatellite()

LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"

LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"

LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

CheckBox
android:id="@+id/satellite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Satellite "
/
/LinearLayout
LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
android:id="@+id/longitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Longitude:"
/
TextView
android:id="@+id/latitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Latitude:"
/
/LinearLayout
/LinearLayout
SeekBar
android:id="@+id/zoombar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="20"
android:progress="0"/
com.google.android.maps.MapView
android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="false"
android:apiKey=""
/
/LinearLayout


import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidLocation extends MapActivity {

private LocationManager myLocationManager;
private LocationListener myLocationListener;
private TextView myLongitude, myLatitude;
private CheckBox mySatellite;

private MapView myMapView;
private SeekBar myZoomBar;

private MapController myMapController;

private void CenterLocation(GeoPoint centerGeoPoint)
{
myMapController.animateTo(centerGeoPoint);


myLongitude.setText("Longitude: "+
String.valueOf((float)centerGeoPoint.getLongitudeE6()/1000000)
);
myLatitude.setText("Latitude: "+
String.valueOf((float)centerGeoPoint.getLatitudeE6()/1000000)
);
};

private void SetZoomLevel()
{
int myZoomLevel = myZoomBar.getProgress()+1;
myMapController.setZoom(myZoomLevel);
Toast.makeText(this,
"Zoom Level : " + String.valueOf(myZoomLevel),
Toast.LENGTH_LONG).show();
};

private void SetSatellite()
{
myMapView.setSatellite(mySatellite.isChecked());
};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myMapView = (MapView)findViewById(R.id.mapview);
myLongitude = (TextView)findViewById(R.id.longitude);
myLatitude = (TextView)findViewById(R.id.latitude);
myZoomBar = (SeekBar)findViewById(R.id.zoombar);
mySatellite = (CheckBox)findViewById(R.id.satellite);

SetSatellite();
myMapController = myMapView.getController();
SetZoomLevel();

myLocationManager = (LocationManager)getSystemService(
Context.LOCATION_SERVICE);

myLocationListener = new MyLocationListener();

myLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
myLocationListener);

//Get the current location in start-up
//check LastKnownLocation, if not valid, skip it.
Location initLocation=myLocationManager.getLastKnownLocation(
LocationManager.GPS_PROVIDER);
if(initLocation != null)
{
GeoPoint initGeoPoint = new GeoPoint(
(int)(initLocation.getLatitude()*1000000),
(int)(initLocation.getLongitude()*1000000));
CenterLocation(initGeoPoint);
}
myZoomBar.setOnSeekBarChangeListener(myZoomBarOnSeekBarChangeListener);
mySatellite.setOnClickListener(mySatelliteOnClickListener);
}

private CheckBox.OnClickListener mySatelliteOnClickListener =
new CheckBox.OnClickListener(){

public void onClick(View v) {
// TODO Auto-generated method stub
SetSatellite();
}

};

private SeekBar.OnSeekBarChangeListener myZoomBarOnSeekBarChangeListener =
new SeekBar.OnSeekBarChangeListener(){

public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
SetZoomLevel();
}

public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub

}

public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub

}

};

private class MyLocationListener implements LocationListener{

public void onLocationChanged(Location argLocation) {
// TODO Auto-generated method stub
GeoPoint myGeoPoint = new GeoPoint(
(int)(argLocation.getLatitude()*1000000),
(int)(argLocation.getLongitude()*1000000));

CenterLocation(myGeoPoint);
}

public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}

public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}

public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}

@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
};
}

Status Bar Notifications

A status bar notification adds an icon to the system's status bar (with an optional ticker-text message) and an expanded message in the "Notifications" window.
After Notification generated, a selected notification icon and Ticket will be displayed on the status bar.

User can reveal the Notifications window by pulling down the status bar (or selecting Notifications from the Home options menu), to view the Title and Content.

Notification can be generated inside Service or Activity. This exercise show the basic steps to generate a Notification in Activity.

The most important class is NotificationManager and Notification.

In the exercise:
android.R.drawable.btn_star_big_on is a drawable icon in Android system resource, you can assign any drawable icon.
when is when the notification should be generated, System.currentTimeMillis() = NOW.
NOTIFICATION_ID is a number which is unique in your application.
contentIntent is the expected intent to handle the notification. It's the own activity in this exercise.

The generated Notification can be cleared by:
NotificationManager.cancel(NOTIFICATION_ID);

TextView
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
Button
 android:id="@+id/gen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Generate Notification"
 android:id="@+id/clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Clear Notification"
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class AndroidNotification extends Activity {

 NotificationManager myNotificationManager;
 private static final int NOTIFICATION_ID = 1;
 
 /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button myGen = (Button)findViewById(R.id.gen);
    myGen.setOnClickListener(myGenOnClickListener);
    Button myClear = (Button)findViewById(R.id.clear);
    myClear.setOnClickListener(myClearOnClickListener);


}

private void GeneratNotification(){
  
  myNotificationManager =
   (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
  
  CharSequence NotificationTicket = "*** Notification";
  CharSequence NotificationTitle = "Attention Please!";
  CharSequence NotificationContent = "- Notification is coming -";
  long when = System.currentTimeMillis();
  
  Notification notification =
   new Notification(android.R.drawable.btn_star_big_on,
     NotificationTicket, when);
    
  Context context = getApplicationContext();

  Intent notificationIntent = new Intent(this,
   AndroidNotification.class);
  PendingIntent contentIntent =
   PendingIntent.getActivity(this, 0, notificationIntent, 0);

  notification.setLatestEventInfo(context, NotificationTitle,
    NotificationContent, contentIntent);
  
  myNotificationManager.notify(NOTIFICATION_ID, notification);

}

Button.OnClickListener myGenOnClickListener =
 new Button.OnClickListener(){

  @Override
  public void onClick(View v) {
   // TODO Auto-generated method stub
   GeneratNotification();
  }
 
};

Button.OnClickListener myClearOnClickListener =
 new Button.OnClickListener(){

  @Override
  public void onClick(View v) {
   // TODO Auto-generated method stub
   myNotificationManager.cancel(NOTIFICATION_ID);
  }
 
};
}

Layout Animation

Layout Animation can be used to add visual effects on any controls derived from ViewGroup, such as ListView. ListView is a view that shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view.

In this article, I will have a example to show how to implement a simple Layout Animation.


Create a Android Application named AndroidLayoutAnimation.

- Create a new folder named /anim under /res

- Create two xml file under /res/anim to handle the animation
list_layout_controller.xml




layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
 android:delay="50%"
 android:animation="@anim/scale"
scale
set xmlns:android="http://schemas.android.com/apk/res/android"
 android:interpolator="@android:anim/accelerate_interpolator"
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:fromXScale="0.1"
  android:toXScale="1"
  android:fromYScale="0.1"
  android:toYScale="1.0"
  android:duration="2000"
  android:pivotX="10%"
  android:pivotY="10%"
  android:startOffset="100"
ListView
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
Button
  android:id="@+id/myListView"
  android:persistentDrawingCache="animation|scrolling"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layoutAnimation="@anim/list_layout_controller"
  android:id="@+id/myRestartButton"
  android:layout_width="fill_parent" 
     android:layout_height="wrap_content"
     android:text="Restart"

Modify AndroidLayoutAnimation.java to setContentView() using listlayout.xml, and SetupListView(). In order to show the effect, a button is used to restart the animation.
package com.exercise.AndroidLayoutAnimation;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class AndroidLayoutAnimation extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        loadScreen();
    }
    
    private Button.OnClickListener MyRestartButtonOnClickListener
     = new Button.OnClickListener(){

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    loadScreen();
   }
    };
    
    private void loadScreen(){
     setContentView(R.layout.main);
        SetupListView();
        
        Button MyRestartButton = (Button)findViewById(R.id.myRestartButton);
        MyRestartButton.setOnClickListener(MyRestartButtonOnClickListener);
    }
    
    private void SetupListView()
    {
     String[] listItems = new String[] {
       "Hello!",
       "It's a Demo to use Layout Animation",
       "Is it Great?",
       "android-er.blogspot.com"
     };

     ArrayAdapter listItemAdapter 
       = new ArrayAdapter(
         this, 
         android.R.layout.simple_list_item_1, 
         listItems);
       
     ListView lv = (ListView)this.findViewById(R.id.myListView);
     lv.setAdapter(listItemAdapter);
    }
}

AndroidRunnable, with Runnable Thread.


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class AndroidRunnable extends Activity{
 
 int i = 0;
 TextView myi;
 
 Handler handler = new Handler(){

  @Override
  public void handleMessage(Message msg) {
   // TODO Auto-generated method stub
   update_i();
  }
 };
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        myi =(TextView)findViewById(R.id.i);
    }
    
    @Override
 protected void onStart() {
  // TODO Auto-generated method stub
  super.onStart();
  
  Thread myThread=new Thread(new Runnable() {
   public void run() {
    while(true){
     try {
      handler.sendMessage(handler.obtainMessage());
      Thread.sleep(1000);
     }
     catch (Throwable t) {
     }
    }
   }
  });
   
  myThread.start();
 }

 private void update_i()
    {
     i++;
     myi.setText(String.valueOf(i));
    }
}

Perform stress-test on your applications using Monkey, a UI/Application Exerciser



The Monkey is a program that runs on your emulator or device and generates pseudo-random streams of user events such as clicks, touches, or gestures, as well as a number of system-level events. You can use the Monkey to stress-test applications that you are developing, in a random yet repeatable manner.
The simplest way to use the monkey is with the following command, which will launch your application and send 500 pseudo-random events to it.
$ adb shell monkey -v -p your.package.name 500
For more information about command options for Monkey, see the complete UI/Application Exerciser Monkey documentation page.

startActivity() with action Intent.ACTION_VIEW

When call startActivity() with action Intent.ACTION_VIEW, the system will start an activity to display the data to the user. ACTION_VIEW is the most common action performed on data -- it is the generic action you can use on a piece of data to get the most reasonable thing to occur.


In the exercise, Uri.parse() is used to creates a Uri which parses the URI string entered in the EditText. The text entered in the EditText should be an RFC 2396-compliant string.


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/inputuri"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/;
Button
android:id="@+id/startintent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="startActivity with ACTION_VIEW"
/;
/LinearLayout


import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

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

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    String uriString = inputUri.getText().toString();
    Uri intentUri = Uri.parse(uriString);
    
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setData(intentUri);
    
    startActivity(intent);
    
   }});

   }
}

SensorSimulator: simulate sensor on Android emulator.

The OpenIntents SensorSimulator lets you simulate sensor data with the mouse in real time. It currently supports accelerometer, compass, orientation, and temperature sensors, where the behavior can be customized through various settings.


Use this URL to Know more details about Sensors

http://code.google.com/p/openintents/wiki/SensorSimulator

String Resources

A string resource provides text strings for your application with optional text styling and formatting. There are three types of resources that can provide your application with strings:

String
XML resource that provides a single string.
String Array
XML resource that provides an array of strings.
Plurals
XML resource that carries different strings for different pluralizations of the same word or phrase.
All strings are capable of applying some styling markup and formatting arguments. For information about styling and formatting strings, see the section about Formatting and Styling.


Modify /res/values/strings.xml to add our String Resources in XML


resources
string name="hello"Hello World, AndroidStringResources!/string
string name="app_name"AndroidStringResources/string
string name="string_1"It\'s a exercise about \"String Resources\"!/string
string-array name="DayOfWeek"
itemSunday/item
item>MondaTuesday/item
item>Wednesday/item
item>Thursday/item
item>Friday/item
item>Saturday/item
/string-array
plurals name="NumberOfMan"
item quantity="one"man/item
item quantity="other"men/item
/plurals
/resources


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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/string_1"
/
TextView
android:id="@+id/numberofman"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/
Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/
/LinearLayout


import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class AndroidStringResources extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Spinner spinnerDayOfWeek = (Spinner)findViewById(R.id.spinner);
String[] dayOfWeek = getResources().getStringArray(R.array.DayOfWeek);
ArrayAdapter adapter
= new ArrayAdapter(this,
android.R.layout.simple_spinner_item, dayOfWeek);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDayOfWeek.setAdapter(adapter);

TextView textviewNumberOfMan = (TextView)findViewById(R.id.numberofman);
int numberOfMan = 2;
String stringNumberOfMan
= getResources().getQuantityString(R.plurals.NumberOfMan, numberOfMan);
textviewNumberOfMan.setText("It's " + String.valueOf(numberOfMan) + " "
+ stringNumberOfMan + " here.");
}
}

Example of using Color Resource

Color XML resource that carries a color value (a hexadecimal color).

The value always begins with a pound (#) character and then followed by the Alpha-Red-Green-Blue information in one of the following formats:

#RGB
#ARGB
#RRGGBB
#AARRGGBB


create /res/values/colors.xml to add our Color Resources in XML

?xml version="1.0" encoding="utf-8"?
resources
color name="background_color"#f0f0f0/color
color name="text_color_red"#ff0000/color
resources


LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/background_color"

TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/
/LinearLayout



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

public class AndroidColorResources extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TextView Text = (TextView)findViewById(R.id.text);
Text.setTextColor(getResources().getColor(R.color.text_color_red));
}
}

ProgressBar running in AsyncTask

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/startprogress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start"
/
ProgressBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
android:id="@+id/progressbar_Horizontal"
android:max="100"
/
/LinearLayout





import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class AndroidAsyncTaskProgressBar extends Activity {

ProgressBar progressBar;
Button buttonStartProgress;

public class BackgroundAsyncTask extends
AsyncTask {

int myProgress;

@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
Toast.makeText(AndroidAsyncTaskProgressBar.this,
"onPostExecute", Toast.LENGTH_LONG).show();
buttonStartProgress.setClickable(true);
}

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Toast.makeText(AndroidAsyncTaskProgressBar.this,
"onPreExecute", Toast.LENGTH_LONG).show();
myProgress = 0;
}

@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
while(myProgress<100){
myProgress++;
publishProgress(myProgress);
SystemClock.sleep(100);
}
return null;
}

@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressBar.setProgress(values[0]);
}

}


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

buttonStartProgress = (Button)findViewById(R.id.startprogress);
progressBar = (ProgressBar)findViewById(R.id.progressbar_Horizontal);
progressBar.setProgress(0);

buttonStartProgress.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new BackgroundAsyncTask().execute();
buttonStartProgress.setClickable(false);
}});
}
}

A simple exercise to play MIDI audio using MediaPlayer

Put a MIDI file into the res/raw folder of your project, where the Eclipse plugin (or aapt) will find it and make it into a resource that can be referenced from your R class. "midi_sound.mid" in my exercise.





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/play"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="- PLAY -"
Button
android:id="@+id/pause"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="- PAUSE -"
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class AndroidAudioPlayer extends Activity {

MediaPlayer mediaPlayer;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mediaPlayer = MediaPlayer.create(this, R.raw.midi_sound);

    Button buttonPlay = (Button)findViewById(R.id.play);
    Button buttonPause = (Button)findViewById(R.id.pause);
    buttonPlay.setOnClickListener(buttonPlayOnClickListener);
    buttonPause.setOnClickListener(buttonPauseOnClickListener);
}

Button.OnClickListener buttonPlayOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!mediaPlayer.isPlaying()){
 mediaPlayer.start();
 Toast.makeText(AndroidAudioPlayer.this,
   "mediaPlayer.start()",
   Toast.LENGTH_LONG).show();
}
}
};

Button.OnClickListener buttonPauseOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mediaPlayer.isPlaying()){
 mediaPlayer.pause();
 Toast.makeText(AndroidAudioPlayer.this,
   "mediaPlayer.pause()",
   Toast.LENGTH_LONG).show();
}
}
};

}

Play audio resources using SoundPool

The SoundPool class manages and plays audio resources for applications.

A SoundPool is a collection of samples that can be loaded into memory from a resource inside the APK or from a file in the file system. The SoundPool library uses the MediaPlayer service to decode the audio into a raw 16-bit PCM mono or stereo stream. This allows applications to ship with compressed streams without having to suffer the CPU load and latency of decompressing during playback


Modify the last exercise "play MIDI audio using MediaPlayer" to play a ogg file using SoundPool instead of MediaPlayer.

Copy a ogg sound file into res/raw folder.

Keep using the main.xml file in the last exercise "play MIDI audio using MediaPlayer".






import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class AndroidAudioPlayer extends Activity {

SoundPool soundPool;
HashMap soundPoolMap;
int soundID = 1;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
    
      soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
      soundPoolMap = new HashMap();
      //soundPoolMap.put(soundID, soundPool.load(this, R.raw.midi_sound, 1));
      soundPoolMap.put(soundID, soundPool.load(this, R.raw.fallbackring, 1));
    
      Button buttonPlay = (Button)findViewById(R.id.play);
      Button buttonPause = (Button)findViewById(R.id.pause);
      buttonPlay.setOnClickListener(buttonPlayOnClickListener);
      buttonPause.setOnClickListener(buttonPauseOnClickListener);
  }

  Button.OnClickListener buttonPlayOnClickListener
  = new Button.OnClickListener(){
 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
  float curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
  float maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
  float leftVolume = curVolume/maxVolume;
  float rightVolume = curVolume/maxVolume;
  int priority = 1;
  int no_loop = 0;
  float normal_playback_rate = 1f;
  soundPool.play(soundID, leftVolume, rightVolume, priority, no_loop, normal_playback_rate);
 
  Toast.makeText(AndroidAudioPlayer.this,
    "soundPool.play()",
    Toast.LENGTH_LONG).show();
 }
  };

  Button.OnClickListener buttonPauseOnClickListener
  = new Button.OnClickListener(){
 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  soundPool.pause(soundID);
  Toast.makeText(AndroidAudioPlayer.this,
    "soundPool.pause()",
    Toast.LENGTH_LONG).show();
 }
  };

}

Play foreground and background music using SoundPool and MediaPlayer

Merge the previous exercises "A simple exercise to play MIDI audio using MediaPlayer" and "Play audio resources using SoundPool", to implement a app to play audio using both MediaPlayer and SoundPool



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/playmediaplayer" 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="- PLAY MediaPlayer -"   /
Button
   android:id="@+id/pausemediaplayer" 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="- PAUSE MediaPlayer -"
   /
Button
   android:id="@+id/playsoundpool" 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="- PLAY SoundPool -"
   /
Button
   android:id="@+id/pausesoundpool" 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="- PAUSE SoundPool -"
LinearLayout


import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class AndroidAudioPlayer extends Activity {

MediaPlayer mediaPlayer;
SoundPool soundPool;
HashMap soundPoolMap;
int soundID = 1;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mediaPlayer = MediaPlayer.create(this, R.raw.midi_sound);
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
soundPoolMap = new HashMap();
//soundPoolMap.put(soundID, soundPool.load(this, R.raw.midi_sound, 1));
soundPoolMap.put(soundID, soundPool.load(this, R.raw.fallbackring, 1));

Button buttonPlayMediaPlayer = (Button)findViewById(R.id.playmediaplayer);
Button buttonPauseMediaPlayer = (Button)findViewById(R.id.pausemediaplayer);
Button buttonPlaySoundPool = (Button)findViewById(R.id.playsoundpool);
Button buttonPauseSoundPool = (Button)findViewById(R.id.pausesoundpool);
buttonPlayMediaPlayer.setOnClickListener(buttonPlayMediaPlayerOnClickListener);
buttonPauseMediaPlayer.setOnClickListener(buttonPauseMediaPlayerOnClickListener);
buttonPlaySoundPool.setOnClickListener(buttonPlaySoundPoolOnClickListener);
buttonPauseSoundPool.setOnClickListener(buttonPauseSoundPoolOnClickListener);
}

Button.OnClickListener buttonPlayMediaPlayerOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!mediaPlayer.isPlaying()){
mediaPlayer.start();
Toast.makeText(AndroidAudioPlayer.this,
"soundPool.pause()",
Toast.LENGTH_LONG).show();
}
}
};

Button.OnClickListener buttonPauseMediaPlayerOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
Toast.makeText(AndroidAudioPlayer.this,
"soundPool.pause()",
Toast.LENGTH_LONG).show();
}
}
};

Button.OnClickListener buttonPlaySoundPoolOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
float curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float leftVolume = curVolume/maxVolume;
float rightVolume = curVolume/maxVolume;
int priority = 1;
int no_loop = 0;
float normal_playback_rate = 1f;
soundPool.play(soundID, leftVolume, rightVolume, priority, no_loop, normal_playback_rate);

Toast.makeText(AndroidAudioPlayer.this,
"soundPool.play()",
Toast.LENGTH_LONG).show();
}
};

Button.OnClickListener buttonPauseSoundPoolOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
soundPool.pause(soundID);
Toast.makeText(AndroidAudioPlayer.this,
"soundPool.pause()",
Toast.LENGTH_LONG).show();
}
};

}

Play 3gp video file using MediaPlayer

The former exercise show how to "play MIDI audio using MediaPlayer". MediaPlayer can play video file also. This exercise show hoe to play 3gp video file in sdcard using MediaPlayer



Copy 3gp file to root folder on SD Card.
For Putting file into SDCARD select File explorer from Eclips Windows->showView->Others->file explorer
In file explorer MNT->sdcared....see the push and pull button int the left bottom of the explorer ,push the 3gp file.

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/playvideoplayer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="- PLAY Video -"
/
Button
android:id="@+id/pausevideoplayer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="- PAUSE Video -"
/
SurfaceView
android:id="@+id/surfaceview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/
LinearLayout

import java.io.IOException;

import android.app.Activity;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

public class AndroidVideoPlayer extends Activity implements SurfaceHolder.Callback{

MediaPlayer mediaPlayer;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean pausing = false;;

String stringPath = "/sdcard/samplevideo.3gp";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button buttonPlayVideo = (Button)findViewById(R.id.playvideoplayer);
Button buttonPauseVideo = (Button)findViewById(R.id.pausevideoplayer);

getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setFixedSize(176, 144);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();

buttonPlayVideo.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
pausing = false;

if(mediaPlayer.isPlaying()){
mediaPlayer.reset();
}

mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDisplay(surfaceHolder);

try {
mediaPlayer.setDataSource(stringPath);
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

mediaPlayer.start();


}});

buttonPauseVideo.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(pausing){
pausing = false;
mediaPlayer.start();
}
else{
pausing = true;
mediaPlayer.pause();
}
}});

}



@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub

}

@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub

}
}

Sunday, July 10, 2011

How to Display Progress Bar in Android

In many cases we need to display the progress bar, like loading the apps, performing new task, closing apps and more. In order to perform you can use the below code to program your android apps to show the progress bar.

public class MyActivity extends Activity {
private static final int PROGRESS = 0x1;
private ProgressBar mProgress;
private int mProgressStatus = 0;
private Handler mHandler = new Handler();
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.progressbar_activity);
mProgress = (ProgressBar) findViewById(R.id.progress_bar);
// Start lengthy operation in a background thread
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) { mProgressStatus = doWork(); // Here we updating progress bar mHandler.post(new Runnable() { public void run() { mProgress.setProgress(mProgressStatus); } }); } } }).start(); } } Add the below line in AndroidManifast file to display the progress bar.


JSON Example.. Sending data using URLConnection Post method in Android

If we like to create a android apps there will be some necessary to send the data from android device to server. The below program will help us to send data using post method in android

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
TextView Tname,TCountry,TDob,TCity;
EditText Ename,ECountry,EDob,ECity;
Button btnCreate;
String page="";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
btnCreate = (Button) findViewById(R.id.btnGen);
Tname = (TextView) findViewById(R.id.txtName);
Ename = (EditText) findViewById(R.id.editName);
TCity = (TextView) findViewById(R.id.txtCity);
ECity = (EditText) findViewById(R.id.editCity);
TCountry = (TextView) findViewById(R.id.txtCountry);
ECountry = (EditText) findViewById(R.id.editCountry);
TDob = (TextView) findViewById(R.id.txtDob);
EDob = (EditText) findViewById(R.id.editDob);

btnCreate.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
examineJSONFile();
}
});
}

void examineJSONFile()
{
try
{
JSONObject object=new JSONObject();
object.put("Name", Ename.getText());
object.put("City", ECity.getText());
object.put("Country", ECountry.getText());
object.put("Dob", EDob.getText());
String str=object.toString();
executeHttpPost(str);
Log.i("JsonString :", str);
Toast.makeText(this, "Json Objects are : " + str,Toast.LENGTH_LONG).show();


}
catch (Exception je)
{

}
}

public void executeHttpPost(String string) throws Exception
{
//This method for HttpConnection
try
{
HttpClient client = new DefaultHttpClient();

HttpPost request = new HttpPost("http://192.168.1.118:80/androidjsontest/recieve.php");

List value=new ArrayList();

value.add(new BasicNameValuePair("Name",string));

UrlEncodedFormEntity entity=new UrlEncodedFormEntity(value);

request.setEntity(entity);

client.execute(request);

System.out.println("after sending :"+request.toString());

}
catch(Exception e) {System.out.println("Exp="+e);
}

}

}
//main.xml
//==============





















Gmail - Inbox - ganga.kondati@gmail.com

Gmail - Inbox - ganga.kondati@gmail.com

Contacts API

Starting from Android 2.0 (API Level 5), the Android platform provides an improved Contacts API for managing and integrating contacts from multiple accounts and from other data sources. To handle overlapping data from multiple sources, the contacts content provider aggregates similar contacts and presents them to users as a single entity. This article describes how to use the new API to manage (insert, update, delete, view) contacts.

The new Contacts API is defined in the android.provider.ContactsContract and related classes. The older API is still supported, although deprecated.

We need to understand the underlying structure of storage to better manipulate the contacts. We have three distinct types of tables – Contacts, Raw Contacts and Data.

All data related to a contact is stored in this generic data table with each row telling what is the data it stores through its MIME type. So we could have a Phone.CONTENT_ITEM_TYPE as the MIME type of the data row, it contains Phone data. Similarly, if we have Email.CONTENT_ITEM_TYPE as the row’s MIME type, then it stores email data. Like this lot of data rows are associated with a single Raw Contact.

Each Raw Contact refers to a specific contact’s data coming from one single source – say, you gmail account or your office Microsoft account.

The Contact is the topmost in the hierarchy which aggregates similar looking data from various sources into one single contact – a very handy feature when you have redundant data coming about the same contact from you various accounts – like a facebook account, orkut account, yahoo account and goggle account. So the hierarchy looks like this:

So, when we want to insert a new contact, we always insert a Raw Contact. When we want to update an existing contact, we most often deal with the data tables which are accessible through a series of CommonDataKind classes. Because this would be to update particular types of data like phone or email.
Coming to the example:

I create an activity with four buttons to View, Add, Modify and Delete Contacts.

Button view = (Button)findViewById(R.id.viewButton);
Button add = (Button)findViewById(R.id.createButton);
Button modify = (Button)findViewById(R.id.updateButton);
Button delete = (Button)findViewById(R.id.deleteButton);


view.setOnClickListener(new OnClickListener() {
public void onClick(View v){
displayContacts();
Log.i("NativeContentProvider", "Completed Displaying Contact list");
}
});

On the click of each of the buttons I invoke their respective methods: like displayContacts(), createContact(), updatecContact() and deleteContact(). We will now see each of these methods.


displayContacts() is pretty straightforward. Access to each of the tables mentioned above is through a content URI. I use the topmost level ‘Contacts’ URI to iterate through all the existing contacts and display their names and phone numbers (Toast them).

We know Contacts is a ContentProvider and hence we need to query through a ContentResolver which returns all the data of the contacts.

private void displayContacts() {

ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(NativeContentProvider.this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
}
pCur.close();
}
}
}
}

I will try to briefly explain the above method. Line 1 gets a handle to the ContentResolver. Line 2 queries the Contacts URI (ContactsContract.Contacts.CONTENT_URI ) without any mention of the specific columns or “where” clause of an SQL query. Notice all the 4 parameters are null. This means that we are not making any conditional query into the contacts table and hence all data is returned into the cursor.

Next, I check that the cursor is not empty and iterate through the cursor data. I retrieve the _ID and DISPLAY_NAME from the Contacts and then, I check for the flag if the contact has a phone number. This information is available in contacts table itself. But the Phone number details are in the data tables. Hence after checking for the flag, I query the CommonDataKings.Phone.CONTENT_URI for the phone data of that specific ID. From this new cursor named pCur, I retrieve the Phone Number. If there are multiple phone number for one contact, all of them will be retrieved and toasted one after another.
Now, let us see how to create or insert a new contact.

In the createContact() method which is called when you click on the “Add Contact” button, I first query to see if the hardcoded name “Sample Name” already exists. If so, I toast a message stating the same. If not, then I get into actually inserting the name along with a phone number. The first part of the check you can view in the complete source code available for download. Only the second part of inserting a contact is explained here. For this, we need to use a ContentResolver always.

A ContentResolverprovides an applyBatch(…) method which takes an array of ContentProviderOperation classes as a parameter. All the data built into the ContentProviderOperations are committed or inserted into the ContentProvider that we are working on. IN this case, the ContentProvider we are working on are Contacts and the authority associated with the same is ContactsContract.AUTHORITY

Here is the code for the same:

ArrayList ops = new ArrayList();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "accountname@gmail.com")
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "com.google")
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
.build());


try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
….

In the first element in the ops array, I am setting the details of the account to which I want to add the contact. In this case the gmail account type is accontname@gmail.com and the account name is “com.google”. The latter has to be unique and hence it is recommended to use the internet URLs of the source of data.

In the second element, I am adding the name of the contact and in the third the phone data. You notice that I use .withValueBackReference(..) as we still have not created the Raw contact and hence we do not have the Id. The first row creates the id and hands over the id to the next rows of data.
This array ops is passed into the ContentResolver and thus the data is inserted.

For updating the phone number of an existing contact, I again use the ContentResolver with the ContentProviderOperation array. However, now, I pass the where clause and the parameters of the where clause – specifically indicating that only the phone number of the “Sample Name” contact has to be updated.
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.CommonDataKinds.Phone.DATA, phone)
.build());

Notice the .withSelection(where, params). The where and params look like this:

String where = ContactsContract.Data.DISPLAY_NAME + " = ? AND " +
ContactsContract.Data.MIMETYPE + " = ? AND " +
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";

String[] params = new String[] {name,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)};

Delete too is done in a very similar manner with no values but only the selection criteria is provided for which contact to be deleted.

ContentResolver cr = getContentResolver();
String where = ContactsContract.Data.DISPLAY_NAME + " = ? ";
String[] params = new String[] {name};

ArrayList ops = new ArrayList();
ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
.withSelection(where, params)
.build());
try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
….

The complete source code is downloadable here.

"Listing" and "let search engines find your blog" settings - Blogger Help

"Listing" and "let search engines find your blog" settings - Blogger Help

Friday, July 8, 2011

Using SQLite Saving DATA

This is a sample program which shows usage of SQLite in android application for saving data. This application has two buttons in the main menu one for saving information and another for showing all saved information. Last blog published in this forum is How to handle bluetooth settings from your application.
Underlying Algorithm:
Basic description of algorithm in step by step form:
1.) Create a Project DatabaseSample.
2.) Replace the following code with res/layout/main.xml :

Create a helper class DataManipulator.java that can create the database and encapsulate other SQL details. In this DataManipulator class we will include an important inner class OpenHelper that provides a SQLiteOpenHelper.
package com.app.DatabaseSample;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import java.util.ArrayList;
import java.util.List;
public class DataManipulator
{
    private static final  String DATABASE_NAME = "mydatabase.db";
    private static final int DATABASE_VERSION = 1;
    static final String TABLE_NAME = "newtable";
    private static Context context;
    static SQLiteDatabase db;
    private SQLiteStatement insertStmt;
     
    private static final String INSERT = "insert into " + TABLE_NAME + " (name,number,skypeId,address) values (?,?,?,?)";
    public DataManipulator(Context context) {
        DataManipulator.context = context;
        OpenHelper openHelper = new OpenHelper(DataManipulator.context);
        DataManipulator.db = openHelper.getWritableDatabase();
        this.insertStmt = DataManipulator.db.compileStatement(INSERT);
    }
    public long insert(String name,String number,String skypeId,String address) {
        this.insertStmt.bindString(1, name);
        this.insertStmt.bindString(2, number);
        this.insertStmt.bindString(3, skypeId);
        this.insertStmt.bindString(4, address);
        return this.insertStmt.executeInsert();
    }
    public void deleteAll() {
        db.delete(TABLE_NAME, nullnull);
    }
    public List<String[]> selectAll()
    {
        List<String[]> list = new ArrayList<String[]>();
        Cursor cursor = db.query(TABLE_NAME, new String[] {"id","name","number","skypeId","address" }nullnullnullnull"name asc");
        int x=0;
        if (cursor.moveToFirst()) {
           do {
                String[] b1=newString[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),
cursor.getString(3),cursor.getString(4)};
                list.add(b1);
                x=x+1;
           } while (cursor.moveToNext());
        }
        if (cursor != null && !cursor.isClosed()) {
           cursor.close();
        }
        cursor.close();
        return list;
   }
   public void delete(int rowId) {
        db.delete(TABLE_NAME, nullnull);
   }
   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, number TEXT, skypeId TEXT, address TEXT)");
        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
             db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
             onCreate(db);
        }
   }
}
4.) Create a save.xml in res/layout/save.xml:
 version="1.0" encoding="UTF-8"?>
 xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/LinearLayout01" android:orientation="vertical"       android:layout_width="wrap_content" android:layout_height="wrap_content"android:paddingLeft="20sp">
     android:id="@+id/button1_label" android:layout_height="fill_parent"android:layout_width="wrap_content" android:text="Fill Information"android:textSize="24.5sp" android:layout_gravity="center"android:layout_marginBottom="25dip" />
     android:layout_width="fill_parent"       android:layout_height="wrap_content" android:text="Name:"android:layout_gravity="center" android:textSize="14.5sp" />
     android:id="@+id/name" android:layout_width="fill_parent"android:layout_height="wrap_content" />
     android:layout_width="fill_parent"       android:layout_height="wrap_content" android:text="Telephone Number:"android:layout_gravity="center" android:textSize="14.5sp" />
     android:id="@+id/number" android:layout_width="fill_parent"android:layout_height="wrap_content" />
     android:layout_width="fill_parent"       android:layout_height="wrap_content" android:text="Skype ID:"android:layout_gravity="center" android:textSize="14.5sp" />
     android:id="@+id/skypeId" android:layout_width="fill_parent"android:layout_height="wrap_content" />
     android:layout_width="fill_parent"       android:layout_height="wrap_content" android:text="Address:"android:layout_gravity="center" android:textSize="14.5sp" />
     android:id="@+id/address" android:layout_width="fill_parent"android:layout_height="wrap_content" />
     android:id="@+id/LinearLayout02"android:orientation="horizontal" android:layout_width="wrap_content"android:layout_height="wrap_content" android:paddingLeft="20sp">
     android:text="Save" android:id="@+id/Button01add"android:layout_width="wrap_content" android:layout_height="wrap_content"android:layout_marginTop="20sp" android:layout_marginLeft="20sp">
    >

     android:text="Back" android:id="@+id/Button01home"android:layout_width="wrap_content" android:layout_height="wrap_content"android:layout_marginTop="20sp" android:layout_marginLeft="20sp">
    >

    >

>
5.) Create a Activity SaveData.java to Save the information :
package com.app.DatabaseSample;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class SaveData extends Activity implements OnClickListener {
    private DataManipulator dh;  
    static final int DIALOG_ID = 0;
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.save);
        View add = findViewById(R.id.Button01add);
        add.setOnClickListener(this);
        View home = findViewById(R.id.Button01home);
        home.setOnClickListener(this);        
    }
    public void onClick(View v){
        switch(v.getId()){
            case R.id.Button01home:
                Intent i = new Intent(this, DatabaseSample.class);
                startActivity(i);
            break;
            case R.id.Button01add:
                View editText1 = (EditText) findViewById(R.id.name);
                View editText2 = (EditText) findViewById(R.id.number);
                View editText3 = (EditText) findViewById(R.id.skypeId);
                View editText4 = (EditText) findViewById(R.id.address);
                String myEditText1=((TextView) editText1).getText().toString();
                String myEditText2=((TextView) editText2).getText().toString();
                String myEditText3=((TextView) editText3).getText().toString();
                String myEditText4=((TextView) editText4).getText().toString();
                this.dh = new DataManipulator(this);
                this.dh.insert(myEditText1,myEditText2,myEditText3,myEditText4);
                showDialog(DIALOG_ID);
            break;
        }
    }
    protected final Dialog onCreateDialog(final int id) {
        Dialog dialog = null;
        switch(id) {
            case DIALOG_ID:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("Information saved successfully ! Add Another Info?").setCancelable(false).setPositiveButton("No"newDialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                                SaveData.this.finish();
                        }
                }).setNegativeButton("Yes"new DialogInterface.OnClickListener(){
                        public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                        }
                });
                AlertDialog alert = builder.create();
                dialog = alert;
                break;
             default:
        }
        return dialog;
    }
}
6.) Create a ListView to show the all data in a list in res/layout/check.xml :
 version="1.0" encoding="utf-8"?>
 xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent" >
 android:id="@+id/selection2" android:layout_width="fill_parent"android:layout_height="wrap_content"
android:text="NAME – TELPHONE NO – SKYPE ID- ADDRESS" />
 android:id="@+id/selection" android:layout_width="fill_parent"android:layout_height="wrap_content" />
 android:id="@android:id/list" android:layout_width="fill_parent"android:layout_height="fill_parent" android:drawSelectorOnTop="false"android:textSize="3dip" />
>
7.) Create a Activity CheckData.java :
package com.app.DatabaseSample;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class CheckData extends ListActivity  {  
    TextView selection;
    public int idToModify;
    DataManipulator dm;
    List<String[]> list = new ArrayList<String[]>();
    List<String[]> names2 =null ;
    String[] stg1;
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.check);
        dm = new DataManipulator(this);
        names2 = dm.selectAll();
        stg1=new String[names2.size()];
        int x=0;
        String stg;
        for (String[] name : names2) {
                stg = name[1]+" – "+name[2]+ " – "+name[3]+" – "+name[4];
                stg1[x]=stg;
                x++;
        }
        ArrayAdapter<String> adapter = newArrayAdapter<String>(this,android.R.layout.simple_list_item_1,stg1);
        this.setListAdapter(adapter);
        selection=(TextView)findViewById(R.id.selection);
   }      
   public void onListItemClick(ListView parent, View v, int position, long id) {
        selection.setText(stg1[position]);
   }
}
9.) Run the Application.
Steps to Create:
1.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name i.e. DatabaseSample. Enter following information:
Project name: DatabaseSample
Build Target: Android 2.1
Application name: DatabaseSample
Package name: com.app.DatabaseSample
Create Activity: DatabaseSample


On Clicking Finish DatabaseSample code structure is generated with the necessary Android Packages being imported along with DatabaseSample.java. DatabaseSample class will look like following :
package com.app.DatabaseSample;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class DatabaseSample extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        View button1Click = findViewById(R.id.button1);
        button1Click.setOnClickListener(this);
        View button2Click = findViewById(R.id.button2);
        button2Click.setOnClickListener(this);      
   }
   @Override
   public void onClick(View v) {
        // TODO Auto-generated method stub
        switch(v.getId()){
            case R.id.button1:
                Intent i = new Intent(this, SaveData.class); 
                startActivity(i);
            break;
            case R.id.button2:
                Intent i1 = new Intent(this, CheckData.class); 
                startActivity(i1);
            break;
        }
    }
}