Thursday, 31 October 2013

Android 4.4 KitKat realesed

checkout the highlights:

Making Android for everyone
Android 4.4 is designed to run fast, smooth, and responsively on a much broader range of devices than ever before — including on millions of entry-level devices around the world that have as little as 512MB RAM.

New NFC capabilities through Host Card Emulation

  • Printing framework
  • Storage access framework
  • Low-power sensors
  • SMS provider
  • New ways to build beautiful apps
  • New media capabilities
Remaining i will update soon...

Tuesday, 29 October 2013

XML PullParser

 1.There are two key methods: next() and nextToken(). While next() provides access  to high level    
     parsing events, nextToken()  allows access to lower level tokens.

2.The current event state of the parser can be determined by calling the getEventType()   
    method.Initially, the parser is in the  START_DOCUMENT state 

3.The method next() advances the parser to the next event.

The following event types are seen by next()
START_TAG: An XML start tag was read.
TEXT: Text content was read; the text content can be retrieved using the getText() method.
END_TAG: An end tag was read

END_DOCUMENT: No more events are available


Example:
public class SimpleXmlPullApp
 {

     public static void main (String args[])
         throws XmlPullParserException, IOException
     {
         XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
         factory.setNamespaceAware(true);
         XmlPullParser xpp = factory.newPullParser();

         xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) );
         int eventType = xpp.getEventType();
         while (eventType != XmlPullParser.END_DOCUMENT) {
          if(eventType == XmlPullParser.START_DOCUMENT) {
              System.out.println("Start document");
          } else if(eventType == XmlPullParser.START_TAG) {
              System.out.println("Start tag "+xpp.getName());
          } else if(eventType == XmlPullParser.END_TAG) {
              System.out.println("End tag "+xpp.getName());
          } else if(eventType == XmlPullParser.TEXT) {
              System.out.println("Text "+xpp.getText());
          }
          eventType = xpp.next();
         }
         System.out.println("End document");
     }
 }



Example Application:

activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>


MainActivity.java:
package com.ram.xmlpullparser;

import java.io.IOException;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;

@SuppressLint("NewApi")
public class MainActivity extends Activity {
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);

        text = (TextView) findViewById(R.id.textView1);

        try {
            parse();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    void parse() throws IOException, XmlPullParserException {

        URL url = new URL("http://www.w3schools.com/xml/note.xml");

        // Create a new instance of a PullParserFactory that can be used to
        // create XML pull parsers

        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();

        // Specifies that the parser produced by this factory will provide
        // support for XML namespaces. By default the value of this is set to
        // false.

        factory.setNamespaceAware(true);

        // Creates a new instance of a XML Pull Parser using the currently
        // configured factory features

        XmlPullParser xpp = factory.newPullParser();

        // Sets the input stream the parser is going to process. This call
        // resets the parser state and sets the event type to the initial value
        // START_DOCUMENT.

        xpp.setInput(url.openStream(), null);

        // Returns the type of the current event (START_TAG, END_TAG, TEXT,
        // etc.)

        int eventType = xpp.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {

               //  text.append(xpp.getName());
            } else if (eventType == XmlPullParser.TEXT) {

                text.append(xpp.getText());
            } else if (eventType == XmlPullParser.END_TAG) {

                // text.append(xpp.getName());
            }
            eventType = xpp.next();
        }
    }
}


AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ram.xmlpullparser"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ram.xmlpullparser.MainActivity"
            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>

</manifest>


ScreenShot:

 



XML processing in Android

The Java programming language provides several standard libraries for processing XML files.

 The SAX and the DOM XML parsers are also available on Android.

 The SAX and DOM parsers API is on Android the same as in standard Java.

SAX and DOM have their limitations, therefore it is not recommended to use them on Android.

On Android it is recommended to use the XmlPullParser. It has a relatively simple API compared to SAX and DOM and is fast and requires less memory then the DOM API.

Monday, 21 October 2013

StrictMode in Android

Within an Android application you should avoid performing long running operations on the user interface thread. This includes file and network access.

StrictMode allows to setup policies in your application to avoid doing incorrect things. As of Android 3.0 (Honeycomb) StrictMode is configured to crash with a NetworkOnMainThreadException exception, if network is accessed in the user interface thread.

While you should do network access in a background thread, this code will avoid this to allow the user to learn network access independent from background processing.

If you are targeting Android 3.0 or higher, you can turn this check off via the following code at the beginning of your onCreate() method of your activity.

StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 

Thursday, 17 October 2013

AlertDialog with List

Here i'm giving example how to display list of items in AlertDialog.

ScreenShots:



activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button_alertDialogList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="98dp"
        android:text="Dialog List" />

</RelativeLayout>

strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">AlertDialog with List</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="names">Mobile Platforms</string>
    <string-array name="mobileplatforms">
        <item >Android</item>
        <item >iPhone</item>
        <item >BlackBerry</item>
    </string-array>
    
</resources>

MainActivity.java:
package com.ram.alertdialogwithlist;

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

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button showDialog = (Button) findViewById(R.id.button_alertDialogList);

showDialog.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final String[] names = getResources().getStringArray(
R.array.mobileplatforms);

AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);

builder.setTitle(R.string.names);

builder.setItems(R.array.mobileplatforms,
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface arg0, int index) {
// TODO Auto-generated method stub
switch (index) {
case 0:
Toast.makeText(getApplicationContext(),
names[index] + " Selected",
Toast.LENGTH_LONG).show();
break;

case 1:
Toast.makeText(getApplicationContext(),
names[index] + " Selected",
Toast.LENGTH_LONG).show();
break;
case 2:
Toast.makeText(getApplicationContext(),
names[index] + " Selected",
Toast.LENGTH_LONG).show();
break;
}

}
});

AlertDialog alertList = builder.create();

alertList.show();

}
});
}

}

Monday, 7 October 2013

Fragment Lifecycle

Managing the lifecycle of a fragment is a lot like managing the lifecycle of an activity. Like an activity, a fragment can exist in three states:



Resumed
The fragment is visible in the running activity.

Paused
Another activity is in the foreground and has focus, but the activity in which this fragment lives is still visible (the foreground activity is partially transparent or doesn't cover the entire screen).

Stopped
The fragment is not visible. Either the host activity has been stopped or the fragment has been removed from the activity but added to the back stack. A stopped fragment is still alive (all state and member information is retained by the system). However, it is no longer visible to the user and will be killed if the activity is killed

Also like an activity, you can retain the state of a fragment using a Bundle, in case the activity's process is killed and you need to restore the fragment state when the activity is recreated. You can save the state during the fragment'sonSaveInstanceState() callback and restore it during either onCreate(), onCreateView(), or onActivityCreated().

Coordinating with the activity lifecycle
The lifecycle of the activity in which the fragment lives directly affects the lifecycle of the fragment, such that each lifecycle callback for the activity results in a similar callback for each fragment. For example, when the activity receives onPause(), each fragment in the activity receives onPause().
Fragments have a few extra lifecycle callbacks, however, that handle unique interaction with the activity in order to perform actions such as build and destroy the fragment's UI. These additional callback methods are:

onAttach()
Called when the fragment has been associated with the activity (the Activity is passed in here).

onCreateView()

Called to create the view hierarchy associated with the fragment.

onActivityCreated()
Called when the activity's onCreate() method has returned.

onDestroyView()
Called when the view hierarchy associated with the fragment is being removed.

onDetach()
Called when the fragment is being disassociated from the activity.

Here i'm giving example app that shows you Fragment Lifecycle call back methods in Logcat:
Application Name:FragmentLifecycle
PackageName:com.ram.fragmentlifecycle
Layout xml files:activity_main.xml,samplefragment.xml
Java Fiels:MainActivity.java,SampleFragment.java

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="sample fragment"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <fragment
        android:id="@+id/fragment1"
        android:name="com.ram.fragmentlifecycle.SampleFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="14dp"
        android:layout_marginTop="16dp" />

</RelativeLayout>

SampleFragment.java:
package com.ram.fragmentlifecycle;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

@SuppressLint("NewApi")
public class SampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        Log.d("Fragment Lifecycle", "onCreateView()");

        View v = inflater.inflate(R.layout.samplefragment, container, false);
        return v;
    }

   
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

        Log.d("Fragment Lifecycle", "onActivityCreated()");
    }

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);

        Log.d("Fragment Lifecycle", "onAttach()");

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        Log.d("Fragment Lifecycle", "onCreate()");

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        Log.d("Fragment Lifecycle", "onDestroy()");

    }

    @Override
    public void onDetach() {
        // TODO Auto-generated method stub
        super.onDetach();

        Log.d("Fragment Lifecycle", "onDetach()");

    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();

        Log.d("Fragment Lifecycle", "onPause()");

    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        Log.d("Fragment Lifecycle", "onResume()");

    }
   
   

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);

        Log.d("Fragment Lifecycle", "onSaveInstanceState()");

    }

    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();

        Log.d("Fragment Lifecycle", "onStart()");

    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();

        Log.d("Fragment Lifecycle", "onStop()");

    }

    @Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();

        Log.d("Fragment Lifecycle", "onDestroyView()");

    }
}

MainActivity.java:
package com.ram.fragmentlifecycle;

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

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        Log.i("Activity lifecycle", "onCreate()");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
       
        Log.i("Activity lifecycle", "onSaveInstanceState()");

    }
   
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
       
        Log.i("Activity lifecycle", "onStart()");

    }
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
       
        Log.i("Activity lifecycle", "onStop()");

    }
   
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
       
        Log.i("Activity lifecycle", "onPause()");

    }
   
    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
       
        Log.i("Activity lifecycle", "onRestart()");

    }
   
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
       
        Log.i("Activity lifecycle", "onResume()");

    }
   
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
       
        Log.i("Activity lifecycle", "onDestroy()");

    }
}







Friday, 4 October 2013

Running Activity only in portrait mode

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ram.devicemode"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ram.devicemode.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>









Running Activity only in Landscape mode

If you want to run your Activity only in Landscape mode just define one attribute in your AndroidManifest.xml file as follows

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ram.devicemode"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ram.devicemode.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="landscape" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>









ScreenShot: