Tuesday, January 22, 2013

Android Services Tutorial and Example


A service is an Android component that runs in the background without any user interaction.
It can be started and stopped by any component.While it is running, any component
can bind to it,












src/com/jitesh/servicesdemo/SimpleActivity.java

package com.jitesh.servicesdemo;


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

public class SimpleActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button startButton = (Button) findViewById(R.id.Button01);
        startButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view){
                startService(new Intent(SimpleActivity.this, SimpleService.class));
            }
        });      

        Button stopButton = (Button)findViewById(R.id.Button02);
        stopButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v){
                stopService(new Intent(SimpleActivity.this,SimpleService.class));
            }                
        });
    }
}




src/com/jitesh/servicesdemo/SimpleService.java


package com.jitesh.servicesdemo;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;

public class SimpleService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}

boolean paused = false;

@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service created ...", Toast.LENGTH_LONG).show();
paused = false;
Thread initBkgdThread = new Thread(new Runnable() {
public void run() {
play_music();
}
});
initBkgdThread.start();
}

@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
paused = true;
}

int[] notes = { R.raw.c5, R.raw.b4, R.raw.a4, R.raw.g4 };
int NOTE_DURATION = 400; // millisec
MediaPlayer m_mediaPlayer;

private void play_music() {
for (int ii = 0; ii < 12; ii++) {
// check to ensure main activity not paused
if (!paused) {
if (m_mediaPlayer != null) {
m_mediaPlayer.release();
}
m_mediaPlayer = MediaPlayer.create(this, notes[ii % 4]);
m_mediaPlayer.start();
try {
Thread.sleep(NOTE_DURATION);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jitesh.servicesdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".SimpleActivity"
            android:label="@string/title_activity_simple" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
          <service android:name=".SimpleService"></service>
    </application>

</manifest>


res/layout/main.xml


<?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="Do it" >
    </Button>

    <Button
        android:id="@+id/Button02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop it" >
    </Button>

</LinearLayout>

create a raw inside res and put some *RTTL files and give their name accordingly used in  program.


Monday, January 21, 2013

Android Telephony


The Android telephony API provides a way to monitor basic phone information, such as
the network type, connection state, and utilities for manipulating phone number strings.


Some of the telephony information is permission protected, so access must be declared in the AndroidManifest XML file:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

The main activity code is given below :

package com.jitesh.hardware.telephony;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.TextView;
public class TelephonyApp extends Activity {
TextView tv1;
TelephonyManager telManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv1 =(TextView) findViewById(R.id.tv1);
telManager = (TelephonyManager)
getSystemService(TELEPHONY_SERVICE);
StringBuilder sb = new StringBuilder();
sb.append("deviceid:")
.append(telManager.getDeviceId()).append("\n");
sb.append("device Software Ver:")
.append(telManager.getDeviceSoftwareVersion()).append("\n");
sb.append("Line number:")
.append(telManager.getLine1Number()).append("\n");
sb.append("Network Country ISO:")
.append(telManager.getNetworkCountryIso()).append("\n");
sb.append("Network Operator:")
.append(telManager.getNetworkOperator()).append("\n");
sb.append("Network Operator Name:")
.append(telManager.getNetworkOperatorName()).append("\n");
sb.append("Sim Country ISO:")
.append(telManager.getSimCountryIso()).append("\n");
sb.append("Sim Operator:")
.append(telManager.getSimOperator()).append("\n");
sb.append("Sim Operator Name:")
.append(telManager.getSimOperatorName()).append("\n");
sb.append("Sim Serial Number:")
.append(telManager.getSimSerialNumber()).append("\n");
sb.append("Subscriber Id:")
.append(telManager.getSubscriberId()).append("\n");
sb.append("Voice Mail Alpha Tag:")
.append(telManager.getVoiceMailAlphaTag()).append("\n");
sb.append("Voice Mail Number:")
.append(telManager.getVoiceMailNumber()).append("\n");
tv1.setText(sb.toString());
}
}

res/layout/main.xml


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



Sunday, January 20, 2013

Android Taking Picture (Using Camera)

The camera is the most visible and most used sensor in an Android device. There are two ways to access the camera from an application
1)The first is by declaring an implicit intent


Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);



2)The second way leverages the Camera class, which provides more flexibility in the settings.This creates a custom camera interface, which is the focus of the examples that follow. Camera hardware access requires explicit permission in the AndroidManifest XML file:

<uses-permission android:name="android.permission.CAMERA" />

Customizing the Camera=>

please have a look on the following codes

res/layout/main.xml



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


    <SurfaceView android:id="@+id/surface"
        android:layout_width="fill_parent" android:layout_height="fill_parent">

    </SurfaceView>
</LinearLayout>

res/layout/cameraoverlay.xml


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

<LinearLayout
   android:layout_width="fill_parent" android:layout_height="wrap_content"
   android:orientation="horizontal"
   android:gravity="center_horizontal">
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show data"
/>
</LinearLayout>
<LinearLayout
   android:layout_width="fill_parent" android:layout_height="wrap_content"
   android:orientation="horizontal"
   android:gravity="center_horizontal">
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show temperature"
/>
</LinearLayout>
<LinearLayout
   android:layout_width="fill_parent" android:layout_height="wrap_content"
   android:orientation="horizontal"
   android:gravity="center_horizontal">
<TextView
android:id="@+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show temperature"
/>
</LinearLayout>

</LinearLayout>
<LinearLayout
   android:layout_width="fill_parent" android:layout_height="fill_parent"
   android:orientation="vertical"
   android:gravity="bottom"
   android:layout_gravity="bottom">

<LinearLayout
   android:layout_width="fill_parent" android:layout_height="wrap_content"
   android:orientation="horizontal"
   android:gravity="center_horizontal">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="take picture"
/>
</LinearLayout>
</LinearLayout>

</FrameLayout>

src/com/jiteshcamerademo/CameraApplication.java


package com.jiteshcamerademo;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class CameraApplication extends Activity implements SurfaceHolder.Callback{
    /** Called when the activity is first created. */
    private static final String TAG = "Jitesh hardware";
    private LayoutInflater mInflater = null;
    Camera mCamera;
    byte[] tempdata;
    boolean mPreviewRunning = false;
    private SurfaceHolder mSurfaceHolder;
    private SurfaceView mSurfaceView;
    Button takepicture;
    SensorManager sensorManager;
    TextView tv1,tv2,tv3;
    private final SensorEventListener mSensorEventListener = new SensorEventListener(){

public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}


public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
// Log.v("test","Event Azimuth:"+event.values[0]+" Pitch:"+event.values[1]+" Roll:"+event.values[2]);
// Log.v("test","onSensorChanged:"+event.sensor.getName());
if(event.sensor.getType()==Sensor.TYPE_ORIENTATION){
tv1.setText("Jitesh Data:"+Math.round(event.values[0])+" Pitch:"+Math.round(event.values[1])+" Roll:"+Math.round(event.values[2]));
}
}

    };
    private final SensorEventListener mTListener = new SensorEventListener(){

public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}


public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
// Log.v("test","Event Azimuth:"+event.values[0]+" Pitch:"+event.values[1]+" Roll:"+event.values[2]);
// Log.v("test Temperature","onSensorChanged:"+event.sensor.getName());
if(event.sensor.getType()==Sensor.TYPE_TEMPERATURE){
tv2.setText("Temperature:"+event.values[0]);
}
}

    };
   
    private final SensorEventListener mLListener = new SensorEventListener(){

public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}


public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
// Log.v("test","Event Azimuth:"+event.values[0]+" Pitch:"+event.values[1]+" Roll:"+event.values[2]);
// Log.v("test Light","onSensorChanged:"+event.sensor.getName());
if(event.sensor.getType()==Sensor.TYPE_LIGHT){
tv3.setText("Light:"+event.values[0]);
}
}

    };

   
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);

        mSurfaceView = (SurfaceView)findViewById(R.id.surface);
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.addCallback(this);      
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    //    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
       
        mInflater = LayoutInflater.from(this);
        View overView = mInflater.inflate(R.layout.cameraoverlay, null);
        this.addContentView(overView,new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        takepicture = (Button)findViewById(R.id.button);
        tv1 =(TextView) findViewById(R.id.tv1);
        tv2 =(TextView) findViewById(R.id.tv2);
        tv3 =(TextView) findViewById(R.id.tv3);
        takepicture.setOnClickListener(new OnClickListener(){
    public void onClick(View view){
       {
       
      mCamera.takePicture(mShutterCallback, mPictureCallback,mjpeg);
       }
    }
   
    });
      sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
      sensorManager.registerListener(mSensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),SensorManager.SENSOR_DELAY_FASTEST);
      sensorManager.registerListener(mTListener, sensorManager.getDefaultSensor(Sensor.TYPE_TEMPERATURE),SensorManager.SENSOR_DELAY_FASTEST);
      //sensorManager.registerListener(mLListener, sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT),SensorManager.SENSOR_DELAY_FASTEST);
         
      List<Sensor> sensors= sensorManager.getSensorList(Sensor.TYPE_ALL);
      for(int i =0;i<sensors.size();i++){
     Log.v("LST",i+"] type:"+sensors.get(i).getName()+" type code:"+sensors.get(i).getType());
      }
 
    }

    PhoneStateListener mphoneListner = new PhoneStateListener(){
   
    };
   
   
   
    Camera.ShutterCallback mShutterCallback = new Camera.ShutterCallback(){


public void onShutter() {
// TODO Auto-generated method stub

}
   
    };
    Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
        public void onPictureTaken(byte[] data, Camera c) {
        if(data !=null)
        {

        }
        }
    };

    Camera.PictureCallback mjpeg = new Camera.PictureCallback() {
        public void onPictureTaken(byte[] data, Camera c) {
        if(data !=null)
        {
        tempdata=data;
        done();
           

        }
        }
    };

    void done()
    {
      Bitmap bm = BitmapFactory.decodeByteArray(tempdata,0,tempdata.length);
         String url = Images.Media.insertImage(getContentResolver(),
          bm, null, null);                                
         bm.recycle();
         Bundle bundle = new Bundle();
         if(url!=null)
         {
        bundle.putString("url", url);
       
        Intent mIntent = new Intent();
        mIntent.putExtras(bundle);
        setResult(RESULT_OK, mIntent);
         }
         else
         {
        Toast.makeText(this, "Picture can not be saved", Toast.LENGTH_SHORT).show();
         }
         finish();
    }


public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// TODO Auto-generated method stub
        Log.e(TAG, "surfaceChanged");
try
{
       // XXX stopPreview() will crash if preview is not running
       if (mPreviewRunning) {
           mCamera.stopPreview();
       }

       Camera.Parameters p = mCamera.getParameters();
       p.setPreviewSize(w, h);
/*
       p.set("rotation", 90);
     
       p.setPictureSize(480,640);
*/      
       mCamera.setParameters(p);
       mCamera.setPreviewDisplay(holder);
       mCamera.startPreview();
       mPreviewRunning = true;
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
}

public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
        Log.e(TAG, "surfaceCreated");
        mCamera = Camera.open();
}

public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
        Log.e(TAG, "surfaceDestroyed");
        mCamera.stopPreview();
        mPreviewRunning = false;
        mCamera.release();
        mCamera=null;
}

}



Saturday, January 19, 2013

Android adding EULA(END USER LICENSE AGREMENT)

Adding an EULA


it is often useful to have an End User License Agreement (EULA) display when a user first installs and runs an app. If the user does not accept it, the downloaded application does not run.After a user does accept it, the EULA is never shown again.


It uses SharedPreferences with the boolean PREFERENCE_EULA_ACCEPTED to determine whether the EULA was previously accepted or not accepted.

src/com/jitesh/eula/Eula.java


package com.jitesh.eula;





import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Closeable;


class Eula {
    private static final String ASSET_EULA = "EULA";
    private static final String PREFERENCE_EULA_ACCEPTED = "eula.accepted";
    private static final String PREFERENCES_EULA = "eula";

    /**
     * callback to let the activity know when the user has accepted the EULA.
     */
    static interface OnEulaAgreedTo {

        /**
         * Called when the user has accepted the eula and the dialog closes.
         */
        void onEulaAgreedTo();
    }

    /**
     * Displays the EULA if necessary. This method should be called from the onCreate()
     * method of your main Activity.
     *
     * @param activity The Activity to finish if the user rejects the EULA.
     * @return Whether the user has agreed already.
     */
    static boolean show(final Activity activity) {
   
        final SharedPreferences preferences = activity.getSharedPreferences(PREFERENCES_EULA,
                Activity.MODE_PRIVATE);
        //to test:  preferences.edit().putBoolean(PREFERENCE_EULA_ACCEPTED, false).commit();
        if (!preferences.getBoolean(PREFERENCE_EULA_ACCEPTED, false)) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle(R.string.eula_title);
            builder.setCancelable(true);
            builder.setPositiveButton(R.string.eula_accept, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    accept(preferences);
                    if (activity instanceof OnEulaAgreedTo) {
                        ((OnEulaAgreedTo) activity).onEulaAgreedTo();
                    }
                }
            });
            builder.setNegativeButton(R.string.eula_refuse, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    refuse(activity);
                }
            });
            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    refuse(activity);
                }
            });
            builder.setMessage(readEula(activity));
            builder.create().show();
            return false;
        }
        return true;
    }

    private static void accept(SharedPreferences preferences) {
        preferences.edit().putBoolean(PREFERENCE_EULA_ACCEPTED, true).commit();
    }

    private static void refuse(Activity activity) {
        activity.finish();
    }

    private static CharSequence readEula(Activity activity) {
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(activity.getAssets().open(ASSET_EULA)));
            String line;
            StringBuilder buffer = new StringBuilder();
            while ((line = in.readLine()) != null) buffer.append(line).append('\n');
            return buffer;
        } catch (IOException e) {
            return "";
        } finally {
            closeStream(in);
        }
    }

    /**
     * Closes the specified stream.
     *
     * @param stream The stream to close.
     */
    private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }
}

The Eula class needs to be customized as follows:
1. The actual text of the EULA needs to be put in a text file called EULA (as specified by the ASSET_EULA variable ) and placed in the assets/ directory of the Android project.This is loaded by the readEula() method of the Eula class.
2. There are few strings that need to be specified for the Acceptance dialog box.These
can be collected in the string’s resource file.

the strings.xml res/values/strings.xml

<resources>

    <string name="app_name">EULA</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_my_app">MyApp</string>
    
    

    <string name="hello">Welcome to MyApp</string>
    
    <string name="eula_title">License Agreement</string>
    <string name="eula_accept">Accept</string> 
    <string name="eula_refuse">Don\'t Accept</string> 

    

</resources>

the main activity class is as follows 

package com.jitesh.eula;



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

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







Android Working with Shared Preferences


Depending on the situation, different data storage methods are available to the
developer:
1) Shared Preferences for lightweight usage, such as saving application settings and the
user interface (UI) state
2) A built-in SQLite database for more complicated usage, such as saving application
records
3) The standard Java flat file storage methods: InputFileStream and
OutputFileStream


Shared Preferences
SharedPreferences is an interface that an application can use to quickly and efficiently
save data in name-values pairs, similar to a Bundle.The information is stored in an XML
file on the Android device. For example, if the application com.jitesh.datastorage
creates a shared preference, the Android system creates a new XML file under the
/data/data/com.jitesh.datastorage/shared_prefs directory. Shared preferences are
usually used for saving application settings such as user settings, theme, and other general
application properties. It can also save login information such as username, password,
auto-login flag and remember-user flag.The shared preferences data is accessible by every
component of the application which created it.

Creating and Retrieving Shared Preferences


The shared preferences for an activity can be accessed using the getPreferences()
method, which specifies the operating mode for the default preferences file. If instead
multiple preference files are needed, each can be specified using the
getSharedPreferences() method. If the shared preferences XML file exists in the data
directory, it is opened; otherwise, it is created.The operating mode provides control over
the different kinds of access permission to the preferences:
n MODE_PRIVATE—Only the calling application has access to the XML file.
n MODE_WORLD_READABLE—All applications can read the XML file.
n MODE_WORLD_WRITEABLE—All applications can write to the XML file.
After a SharedPreferences object is retrieved, an Editor object is needed to write the
name-value pairs to the XML file using the put() method. Currently, there are five
primitive types supported: int, long, float, String, and boolean.The following code
shows how to create and store shared preferences data:
SharedPreferences prefs = getSharedPreferences("myDataStorage",
MODE_PRIVATE);
Editor mEditor = prefs.edit();
mEditor.putString("username","datastorageuser1");
mEditor.putString("password","password1234");
mEditor.commit();
The following shows how to retrieve shared preferences data:
SharedPreferences prefs = getSharedPreferences("myDataStorage",
MODE_PRIVATE);
String username = prefs.getString("username", "");
String password = prefs.getString("password", "");


Using the Preferences Framework



Android provides a standardized framework for setting preferences across all applications.
The framework uses category preferences and screens to group related settings.
PreferenceCategory is used to declare a set of preferences into one category.
PreferenceScreen presents a group of preferences in a new screen.
This recipe uses the preferences defined in the XML file in Listing 9.1.A
PreferenceScreen is the root element with two EditTextPreference elements for
username and password. Other possible elements are CheckBoxPreference,
RingtonePreference, and DialogPreference.The Android system then generates a UI
to manipulate the preferences, as shown in Figure 9.1.These preferences are stored in
shared preferences, which means they can be retrieved by calling getPreferences().

res/xml/preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference android:title="User Name"
android:key="username"
android:summary="Please provide user
name"></EditTextPreference>
<EditTextPreference android:title="Password"
android:password="true"
android:key="password"
android:summary="Please enter your
password"></EditTextPreference>
</PreferenceScreen>

src/com/jitesh/datastorage/MyPreferences.java


package com.jitesh.datastorage;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class MyPreferences extends PreferenceActivity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   
    addPreferencesFromResource(R.xml.preferences);
  }
}


src/com/jitesh/datastorage/DataStorage.java

package com.jitesh.datastorage;


import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class DataStorage extends Activity {
 SharedPreferences myprefs;
 EditText userET, passwordET;
 Button loginBT;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myprefs = PreferenceManager.getDefaultSharedPreferences(this);
        final String username = myprefs.getString("username", null);
        final String password = myprefs.getString("password", null);
        if (username != null && password != null){
            setContentView(R.layout.main);
            userET = (EditText)findViewById(R.id.userText);
            passwordET = (EditText)findViewById(R.id.passwordText);
            loginBT = (Button)findViewById(R.id.loginButton);
            loginBT.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    try {
                        if(username.equals(userET.getText().toString())&&password.equals(passwordET.getText().toString())){
                        Toast.makeText(DataStorage.this, "login passed!!", Toast.LENGTH_SHORT).show();
                       
                        }
                        else{
                        Toast.makeText(DataStorage.this, "login failed!!", Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
            
        }
        else{
        Intent i = new Intent(this, MyPreferences.class);
        startActivity(i);
        }
    }
}


res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="username"
    />
    <EditText
    android:id="@+id/userText"
            android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:singleLine="true"
    />
    
    <TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="password"
    />
    <EditText
        android:id="@+id/passwordText"
            android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:password="true"
   android:singleLine="true"
    />
    <Button
   android:id="@+id/loginButton"
            android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="login"
    android:textSize="20dp"
    />
</LinearLayout>











Sunday, January 13, 2013

Android working with the RSS feed

make a project with the name Earthquake, create a main activity class with the name Earthquake.java with following code


package jitesh.example.earthquake;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class Earthquake extends Activity {
 
  ListView earthquakeListView;
  ArrayAdapter<Quake> aa;
  ArrayList<Quake> earthquakes = new ArrayList<Quake>();
     
  static final private int QUAKE_DIALOG = 1;
  Quake selectedQuake;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
   
    earthquakeListView = (ListView)this.findViewById(R.id.earthquakeListView);

    earthquakeListView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView _av, View _v, int _index, long arg3) {
          selectedQuake = earthquakes.get(_index);
          showDialog(QUAKE_DIALOG);
        }
      });
   
    int layoutID = android.R.layout.simple_list_item_1;
    aa = new ArrayAdapter<Quake>(this, layoutID , earthquakes);
    earthquakeListView.setAdapter(aa);
   
    refreshEarthquakes();
  }
 
  private void refreshEarthquakes() {
 // Get the XML
 URL url;
 try {
   String quakeFeed = getString(R.string.quake_feed);
   url = new URL(quakeFeed);
       
   URLConnection connection;
   connection = url.openConnection();
     
   HttpURLConnection httpConnection = (HttpURLConnection)connection;
   int responseCode = httpConnection.getResponseCode();

   if (responseCode == HttpURLConnection.HTTP_OK) {
     InputStream in = httpConnection.getInputStream();
       
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     DocumentBuilder db = dbf.newDocumentBuilder();

     // Parse the earthquake feed.
     Document dom = db.parse(in);    
     Element docEle = dom.getDocumentElement();
     
     // Clear the old earthquakes
     earthquakes.clear();
       
     // Get a list of each earthquake entry.
     NodeList nl = docEle.getElementsByTagName("entry");
     if (nl != null && nl.getLength() > 0) {
       for (int i = 0 ; i < nl.getLength(); i++) {
         Element entry = (Element)nl.item(i);
         Element title = (Element)entry.getElementsByTagName("title").item(0);
         Element g = (Element)entry.getElementsByTagName("georss:point").item(0);
         Element when = (Element)entry.getElementsByTagName("updated").item(0);
         Element link = (Element)entry.getElementsByTagName("link").item(0);

         String details = title.getFirstChild().getNodeValue();
         String hostname = "http://earthquake.usgs.gov";
         String linkString = hostname + link.getAttribute("href");

         String point = g.getFirstChild().getNodeValue();
         String dt = when.getFirstChild().getNodeValue();
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
         Date qdate = new GregorianCalendar(0,0,0).getTime();
         try {
           qdate = sdf.parse(dt);
         } catch (ParseException e) {
           e.printStackTrace();
         }

         String[] location = point.split(" ");
         Location l = new Location("dummyGPS");
         l.setLatitude(Double.parseDouble(location[0]));
         l.setLongitude(Double.parseDouble(location[1]));

         String magnitudeString = details.split(" ")[1];
         int end =  magnitudeString.length()-1;
         double magnitude = Double.parseDouble(magnitudeString.substring(0, end));
           
         details = details.split(",")[1].trim();
           
         Quake quake = new Quake(qdate, details, l, magnitude, linkString);

         // Process a newly found earthquake
         addNewQuake(quake);
       }
     }
   }
 } catch (MalformedURLException e) {
   e.printStackTrace();
 } catch (IOException e) {
   e.printStackTrace();
 } catch (ParserConfigurationException e) {
   e.printStackTrace();
 } catch (SAXException e) {
   e.printStackTrace();
 }
 finally {
 }
}

    private void addNewQuake(Quake _quake) {
 // Add the new quake to our list of earthquakes.
 earthquakes.add(_quake);

 // Notify the array adapter of a change.
 aa.notifyDataSetChanged();
}
   
    static final private int MENU_UPDATE = Menu.FIRST;
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
      super.onCreateOptionsMenu(menu);

      menu.add(0, MENU_UPDATE, Menu.NONE, R.string.menu_update);
                 
      return true;
    }
           
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      super.onOptionsItemSelected(item);
         
      switch (item.getItemId()) {
        case (MENU_UPDATE): {

          refreshEarthquakes();
          return true;
        }
      }
      return false;
    }
   
    @Override
    public Dialog onCreateDialog(int id) {
      switch(id) {
        case (QUAKE_DIALOG) :
          LayoutInflater li = LayoutInflater.from(this);
          View quakeDetailsView = li.inflate(R.layout.quake_details, null);

          AlertDialog.Builder quakeDialog = new AlertDialog.Builder(this);
          quakeDialog.setTitle("Quake Time");
          quakeDialog.setView(quakeDetailsView);
          return quakeDialog.create();
      }
      return null;
    }

    @Override
    public void onPrepareDialog(int id, Dialog dialog) {
      switch(id) {
        case (QUAKE_DIALOG) :
          SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
          String dateString = sdf.format(selectedQuake.getDate());
          String quakeText = "Magnitude " + selectedQuake.getMagnitude() +
                             "\n" + selectedQuake.getDetails()  + "\n" +
                             selectedQuake.getLink();

          AlertDialog quakeDialog = (AlertDialog)dialog;
          quakeDialog.setTitle(dateString);
          TextView tv = (TextView)quakeDialog.findViewById(R.id.quakeDetailsTextView);
          tv.setText(quakeText);

          break;
      }
    }
   
}

the main.xml is having the code as 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">
  <ListView
    android:id="@+id/earthquakeListView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
  />
</LinearLayout>

make a java class with name Quake.java with the given code


package jitesh.example.earthquake;

import java.util.Date;
import java.text.SimpleDateFormat;
import android.location.Location;

public class Quake {
  private Date date;
  private String details;
  private Location location;
  private double magnitude;
  private String link;

  public Date getDate() { return date; }
  public String getDetails() { return details; }
  public Location getLocation() { return location; }
  public double getMagnitude() { return magnitude; }
  public String getLink() { return link; }
 
  public Quake(Date _d, String _det, Location _loc, double _mag, String _link) {
    date = _d;
    details = _det;
    location = _loc;
    magnitude = _mag;
    link = _link;
  }

  @Override
  public String toString() {
    SimpleDateFormat sdf = new SimpleDateFormat("HH.mm");
    String dateString = sdf.format(date);
    return dateString + ": " + magnitude + " " + details;
  }
}





the quake_details.xml is having the layout as follows


<?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"
  android:padding="10dp">
  <TextView
    android:id="@+id/quakeDetailsTextView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:textSize="14sp"
    android:autoLink="all"
  />
</LinearLayout>

after it go through the strings.xml and copy the following lines


<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">Earthquake</string>
  <string name="quake_feed">
    http://earthquake.usgs.gov/eqcenter/catalogs/1day-M2.5.xml
  </string>
  <string name="menu_update">Refresh Earthquakes</string>
</resources>

beside this have a look on manifes


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="jitesh.example.earthquake"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Earthquake"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.INTERNET"/>
</manifest>






Android checking Internet Connection Availability

Sometimes it is good practise to know about the connection availability before the use. for this purpose make a class with name AppStatus



package jitesh.example.earthquake;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context){
        this._context = context;
    }

    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }

          }
          return false;
    }
}


and use it on your need with following code


ConnectionDetector cd;
  Boolean isInternetPresent = false;

inside the onCreate of main activity write the code
 cd = new ConnectionDetector(getApplicationContext());

finally check after a button click



isInternetPresent = cd.isConnectingToInternet();
       
            // check for Internet status
            if (isInternetPresent) {
                // Internet Connection is Present
                // make HTTP requests
                showAlertDialog(Earthquake.this, "Internet Connection",
                        "You have internet connection", true);
            } else {
                // Internet connection is not present
                // Ask user to connect to Internet
                showAlertDialog(Earthquake.this, "No Internet Connection",
                        "You don't have internet connection.", false);
            }


the showAlertDialog method is given below


    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting alert dialog icon
       // alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });