Thursday, February 16, 2012

Tab with ListView

In this sample we are going to create an application which includes two tabs under with two custom listview for each tabs.

import android.app.TabActivity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TabHost;

public class TabListActivity extends TabActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homescreen);
     
        TabHost mTabHost = getTabHost();
     
        final ListView one=(ListView)findViewById(R.id.listOne);
        final ListView two=(ListView)findViewById(R.id.listTwo);
     
        String[] listItemsone = new String[] {"one","two","three"};
        String[] listItemstwo = new String[] {"A","B","C"};
     
//Typed array which contains array values be stored in an separate xml file
        TypedArray itemsOneIcons = getResources().obtainTypedArray(R.array.listOneicons);
        TypedArray itemsTwoIcons = getResources().obtainTypedArray(R.array.listTwoicons);
       
         one.setAdapter(new ImageAndTextAdapter(getApplicationContext(), R.layout.listrow, listItemsone, itemsOneIcons));
         two.setAdapter(new ImageAndTextAdapter(getApplicationContext(), R.layout.listrow, listItemstwo, itemsTwoIcons));
     
        mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("Tab1").setContent(R.id.tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("Tab ").setContent(R.id.tab2));
     
        //Used to reduce the height of the Tabs
        mTabHost.getTabWidget().getChildAt(0).getLayoutParams().height /=2;
        mTabHost.getTabWidget().getChildAt(1).getLayoutParams().height /=2;   
  
        mTabHost.setCurrentTab(0);   
         one.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
           //Used to get selected Item
              String selectedFromList = (String) ( one.getItemAtPosition(myItemInt));           
             //Navigation
              Intent  selectedItem  = new Intent (CurrentActivity, Navigation Activity);
              //Sending value to next screen
               selectedItem.putExtra("Choice", selectedFromList);
              startActivity( selectedItem);
            }              
      }
        );     
         two.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {

                //Used to get selected Item
              String selectedFromList = (String) ( two.getItemAtPosition(myItemInt));
                //Navigation
               Intent  selectedItem  = new Intent (CurrentActivity, Navigation Activity);
              //Sending value to next screen
               selectedItem.putExtra("Choice", selectedFromList);
              startActivity( selectedItem);
            }              
      }
        );
    }
}

Custom Image and Text List adapter

import android.content.Context;
import android.content.res.TypedArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ImageAndTextAdapter extends ArrayAdapter<String> {

private LayoutInflater mInflater;
private String[] mStrings;
private TypedArray mIcons;
private int mViewResourceId;

public ImageAndTextAdapter(Context ctx, int viewResourceId,
String[] strings, TypedArray icons) {
super(ctx, viewResourceId, strings);

mInflater = (LayoutInflater)ctx.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);

mStrings = strings;
mIcons = icons;
mViewResourceId = viewResourceId;
}

@Override
public int getCount() {
return mStrings.length;
}

@Override
public String getItem(int position) {
return mStrings[position];
}

@Override
public long getItemId(int position) {
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);

ImageView iv = (ImageView)convertView.findViewById(R.id.option_icon);
iv.setImageDrawable(mIcons.getDrawable(position));

TextView tv = (TextView)convertView.findViewById(R.id.option_text);
tv.setText(mStrings[position]);

return convertView;
}
}

homescreen.xml file

<?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"
    android:background="@drawable/quickkal" >
 
 <RelativeLayout
        android:id="@+id/home_header"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="@drawable/background_gradient"
         >
        <Button
            android:id="@+id/map_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_margin="5dp"          
            android:padding="5dp"
            android:text="Map"
            android:textColor="#fff"
            android:background="@drawable/btn_custom" />     
        <ImageView
      android:id="@+id/maestro_header"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
            android:layout_margin="5dp"
            android:src="@drawable/header"
      />
 </RelativeLayout>


<TabHost
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_margin="10dip"
    android:foreground="@null">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:tabStripEnabled="false"/>
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginTop="10dp">
         
            <ListView android:id="@+id/animals"
               android:layout_width="fill_parent"
               android:layout_height="wrap_content"
               android:background="#000000"
               android:layout_weight="1"
               android:drawSelectorOnTop="false"/>

        <ListView android:id="@+id/birds"
               android:layout_width="fill_parent"
               android:layout_height="wrap_content"
               android:background="#000000"
               android:layout_weight="1"
               android:drawSelectorOnTop="false"/>
       
        </FrameLayout>
    </LinearLayout>
</TabHost>

</LinearLayout>

Icons.xml file ------- Used to store typed array


<?xml version="1.0" encoding="utf-8"?>

<resources>
    <array name=" listTwoicons">
        <item>@drawable/icon</item>
        <item>@drawable/icon</item>
        <item>@drawable/icon</item>
     
    </array>
    <array name=" listOneicons">
        <item>@drawable/icon</item>
        <item>@drawable/icon</item>
        <item>@drawable/icon</item>
     
    </array>
</resources>

listrow.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="@+id/option_icon"
android:layout_width="48dp"
android:layout_height="fill_parent"/>
<TextView
  android:id="@+id/option_text"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:padding="10dp"
   android:textSize="16dp" >
</TextView>
</LinearLayout>

Monday, February 13, 2012

Plist Android

Plist in Android:
             Plist is the property list files extension for MAC, iPhone OS programming frame works which has serialized objects that has been stored in it. Hence it is especially for iPhone application only, here we are going to use that files in our Android Application.The following is the sample application which used to read and display plist file values.

import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.widget.TextView;

public class PlistSample extends Activity {
    /** Called when the activity is first created. */
    int i=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView plistValues = (TextView)findViewById(R.id.TextView01);
        String plistXmlContent;
        try
        {
             plistXmlContent = getValuesFromAnPlistXML(this);
            myXmlContent.setText(stringXmlContent);
        }
        catch (XmlPullParserException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {   
            e.printStackTrace();
        }
    }
    private String  getValuesFromAnPlistXML (Activity activity) throws XmlPullParserException,IOException
    {
        StringBuffer stringBuffer = new StringBuffer();
        Resources res = activity.getResources();
        XmlResourceParser xpp = res.getXml(R.layout.plist);
        xpp.next();
        int eventType = xpp.getEventType();
        int flag1 = 0, flag2 = 0, flag3 = 0;
        while (eventType != XmlPullParser.END_DOCUMENT)
        {       
            if(eventType == XmlPullParser.START_TAG)
            {           
                String mainTag = xpp.getName().toString();
                if(mainTag.equals("dict"))
                {
                    if(flag1==0)
                    {
                    flag1 = 1;
                    i=i+1;
                    stringBuffer.append("\n Dict Tag Starts Number := "+i+"\n");
                    }
                    else
                    {
                        stringBuffer.append("Inner Dict Starts\n");
                        flag2 = 1;
                    }
                }           
                else if(mainTag.equals("key"))
                {
                    flag3 = 1;
                }           
                else
                {
                    flag3 = 2;
                }
            }         
            else if(eventType == XmlPullParser.END_TAG)
            {
                String g = xpp.getName().toString();           
                if(g.equals("dict"))
                {
                    if(flag1==1 && flag2!=1)
                    {               
                    stringBuffer.append("\n Main Dicts Ends\n");
                    flag1=0;
                    }
                    else
                    {
                        stringBuffer.append("\nInner Dicts Ends\n");
                        flag2=0;
                    }
                }
            }
            else if(eventType == XmlPullParser.TEXT)
            {
                if(flag3 == 1)
                {
                    stringBuffer.append("\nkey:="+xpp.getText());
                    flag3 = 0;
                }
                else if(flag3 == 2)
                {
                    stringBuffer.append("\nValue:="+xpp.getText());
                    flag3 = 0;
                }
            }         
           eventType = xpp.next();
        }
        stringBuffer.append("\n--- End XML ---");
        stringBuffer.append("\n--- Total Number Of Dictionaries Are ---"+i);     
        return stringBuffer.toString();
    }
}

Create an XML file named plist.XML and copy the following plist code.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Label</key>
        <string>com.google.keystone.user.agent</string>
        <key>LimitLoadToSessionType</key>
        <string>Aqua</string>
        <key>ProgramArguments</key>
        <array>
          <string>/Users/al//Library/Google/GoogleSoftwareUpdate/GoogleSoftwareUpdate.bundle/Contents/Resources/GoogleSoftwareUpdateAgent.app/Contents/MacOS/GoogleSoftwareUpdateAgent</string>
          <string>-runMode</string>
          <string>ifneeded</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>StartInterval</key>
        <integer>3523</integer>
        <key>StandardErrorPath</key>
        <string>/dev/null</string>
        <key>StandardOutPath</key>
        <string>/dev/null</string>
</dict>
<dict>
        <key>label</key>
        <string>com.devdaily.pingwebsites</string>

        <key>ProgramArguments</key>
        <array>
                <string>/Users/al/bin/crontab-test.sh</string>
        </array>
        <key>OnDemand</key>
        <false/>
        <key>Nice</key>
        <integer>1</integer>
        <key>StartInterval</key>
        <integer>60</integer>
        <key>StandardErrorPath</key>
        <string>/tmp/AlTest1.err</string>
        <key>StandardOutPath</key>
        <string>/tmp/AlTest1.out</string>
</dict>
</plist> <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>

Friday, February 3, 2012

Flurry Agent

When we launch our applications we want to know about our application in current market that how it works, users comment, error reports,etc... Its a kinda getting feedback from users how they are evaluating our applications.It can be done with the help of Flurry.
Flurry ( actually Flurry Analytics ) gives you a lot more statistics on the users and on how they use your application.


Integration of Flurry:
  • Go to flurry.com and register for your app, which will generate a unique tracking code.
  • Download and add the FlurryAgent jar to your project libraries. If you're using Eclipse, right-click your project folder, select properties, select Java Build Path, and choose Add External JARs
  • Add android.permission.INTERNET to your AndroidManifest.xml (Required)  --  Required to send analytic data back to the flurry servers.
  • Set android.permission.ACCESS_COARSE_LOCATION orandroid.permission.ACCESS_FINE_LOCATION (optional) – If your application has location permissions, analytics will track where your application is being used. Without this, only country level location information will be available. (To disable detailed location reporting even when your app has permission, call FlurryAgent.setReportLocation(false) before calling FlurryAgent.onStartSession() and no detailed location information will be sent.)                                                                  
  •  Add a call to the Flurry agent from the onStart() and onStop methods of your activities.

Tuesday, January 31, 2012

Android Interview Questions

What is meant by activity?

Activity provides a user interface for screens in our applications and able to interact with java codes to make our application components' design and its functions.

What is meant by Dalvik?

Dalvik is the virtual machine for android's operating systems.Each android applications runs with the help of Dalvik Virtual Machine.It runs classes complied by java language complier that have been transferred into .dex (Dalvik Executable) format so that Dalvik VM can executes files (Dalvik VM will executes files only in .dex format).

Describe Android Application Architecture?

Services - like Network Operation
Intent - To perform inter-communication between activities or services
Resource Externalization - such as strings and graphics
Notification signaling users - light,sound,icon,notification,dialog,etc.
Content Providers - They share data between applications.

What are the storage methods in Android?

Shared Preferences: Store private primitive data in key-value pairs
Internal Storage : Store private data on the device memory.
External Storage : Store public data on the shared external storage.
SQLite Databases: Store structured data in a private database.
Network Connection : Store data on the web with your own network server.

How will you record a phone call in Android?How to get a handle Audio Stream for a call in Android?

Permissions.PROCESS_OUTGOING_CALLS:
            Allows an application to monitor,modify or abort outgoing calls.

Describe a real time scenario where android can be used.

Imagine a situation that you are in a country where no one understand the language you speak and you cannot read or write.However if you have mobile phone with Android, the Google translator translates the data of one language inti another by using XMPP to transmit data.Like type in English and translates it according to that citizens and get the info you need.

What is APK format in Android?How to make an APK file?

APK termed as Application package file is a format that is used to distribute and install the application software for android and middleware on the the android operating systems. To make an APK file, first android is complied and than all of its part are grouped in one file termed as package.The package consists of entire program's code, resources,manifest file, etc.The file is saved with .apk extension

How the nine-patch image different from a regular bitmap? what is the difference between nine-patch image vs regular Bitmap Image?

It is one of a resizable bitmap resource which is being used as backgrounds or other images on the device.The NinePatch class in Android allows drawing a bitmap in nine sections.The four corners are unscaled, the middle of the image is scaled in both axes,the four edges are scaled into one axis.

What is an DDMS?

Dalvik Debug Monitor Service, a GUI debugging application shipped with the SDK.It provides screen capture, log cat and process examination capabilities.

What is Drawable?

A complied visual resource that can be used as a background, title or other part of the screen. It is complied into an android.graphics.drawable subclass.

What is an adb?

Android Debug Bridge, a command-line debugging application shipped with the SDK. It provides tools to browse the device, copy tools on the device and forward ports for debugging.

What is a Content Provider?

It makes a specific set of the application's data available to other applications. The content provider extends the ContentProvider base class to implement a standard set of methods that enable other applications to retrieve and store data of the type it controls. However, applications do not call these methods directly. Rather they use a ContentResolver object and call its methods instead.

What are the exceptions in Android?

The following exceptions are mostly occur and that are supported by Android
InflateException : When an error conditions are occurred, this exception is thrown.
Surface.OutOfResourceException : When a surface is not created or resized, this exception is thrown.
SurfaceHolder.BadsurfaceTypeexception : This exception is thrown from the lockCanvas() method, when invoked on a surface whose is SURFACE_TYPE_PUSH_BUFFERS.
WindowManager.BadTokenException : This execption is thrown at the time of tying to add view an invalid WindowManager.LayoutParamstoken.

Why ListView not recommended to have Active components?

Clicking on the active text box will pop up the software keyboard but this will resize the list, removing focus from the clicked element.

What is meant by Manifest file in Android?

An XML file associated with each Android Application, it describes the component of the applications like activities, intent filter,services, broadcast receiver and content providers. It also describes which activity will host the application and describes about the permissions that need to be accessed by application for android protected APIs like for internet access, to access storage devices, Google maps, etc...,

What's the difference between class, file and activity in android?
Class - The Class file is complied from .java file. Android will use this .class file to produce the executable apk.
File - It is a block of resources, arbitrary information. It can be any file type.
Activity - An activity is the equivalent of a Frame/Window in GUI toolkits. It is not a file or a file type it is just a class that can be extended in Android for loading UI elements on view.



What are the features of Android?
   Components can be reused and replaced by the application framework.
   Optimized DVM for mobile devices
   SQLite enables to store the data in a structured manner.
   Supports GSM telephone and Bluetooth, WiFi, 3G and EDGE technologies
  The development is a combination of a device emulator, debugging tools, memory profiling and plug-in for Eclipse IDE.


What is a service?
A service doesn’t have a visual user interface, but rather runs in the background for an indefinite period of time.
For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate
something and provide the result to activities that need it.
Each service extends the Service base class.
What is a Broadcast receivers?
A broadcast receiver is a component that does nothing but receive and react to broadcast announcements.
For example, announcements that the timezone has changed, that the battery is low or that the user changed a language preference.
All receivers extend the BroadcastReceiver base class.
Broadcast receivers do not display a user interface. However, they may start an activity in response to the information they receive,
or they may use the NotificationManager to alert the user like(flashing the backlight, vibrating the device, playing a sound)

Key Features Need to Know in Android:

  • GUI layer in Android doesn't request data directly from the web but reads it from a local database
  • The service layer is used to periodically update the very same database
  • The GUI layer doesn't talk directly to the service layer (and vice versa) either
  • Risks of blocking the Main thread with e.g. heavy computation or lengthy operations like heave database queries, web access etc (blocking the main thread forces the system to throw an Application Not Responding exception for the given application, which will then "crash" and restart).
  • Regarding downloading of data, data sent over the Internet is not sent in a single chunk but rather in smaller packages, reading the first package isn't equal to have read all data sent by the server.
  • The background service, used for updating the database, is preferably killed by itself, not necessarily waiting for the system to kill it.

What's the difference between file, class and activity in android?
File - It is a block of arbitrary information, or resource for storing information. It can be of any type.
Class - Its a compiled form of .Java file . Android finally used this .class files to produce an executable apk
Activity - An activity is the equivalent of a Frame/Window in GUI toolkits. It is not a file or a file type it is just a class that can be extended in Android for loading UI elements on view.
What are the dialog boxes that are supported in android? Explain.
Android supports 4 dialog boxes:

AlertDialog : An alert dialog box supports 0 to 3 buttons and a list of selectable elements, including check boxes and radio buttons. Among the other dialog boxes, the most suggested dialog box is the alert dialog box.

ProgressDialog: This dialog box displays a progress wheel or a progress bar. It is an extension of AlertDialog and supports adding buttons.

DatePickerDialog: This dialog box is used for selecting a date by the user.

TimePickerDialog: This dialog box is used for selecting time by the user.

What is needed to make a multiple choice list with a custom view for each row?

Multiple choice list can be viewed by making the CheckBox android:id value be “@android:id /text1". That is the ID used by Android for the CheckedTextView in simple_list_item_multiple_choice.

Explain IP datagram, Fragmentation and MTU ?

IP datagram can be used to describe a portion of IP data. Each IP datagram has set of fields arranged in an order. The order is specific which helps to decode and read the stream easily. IP datagram has fields like Version, header length, Type of service, Total length, checksum, flag, protocol, Time to live, Identification, source and destination ip address, padding, options and payload.
MTU:- Maximum Transmission Unit is the size of the largest packet that a communication protocol can pass. The size can be fixed by some standard or decided at the time of connection
Fragmentation is a process of breaking the IP packets into smaller pieces. Fragmentation is needed when the datagram is larger than the MTU. Each fragment becomes a datagram in itself and transmitted independently from source. When received by destination they are reassembled.

What is a Sticky Intent?

sendStickyBroadcast() performs a sendBroadcast (Intent) known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver (BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent).
One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When you call registerReceiver() for that action -- even with a null BroadcastReceiver -- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.
Is there anyway to determine if an Intent passed into a BroadcastReceiver's onReceive is the result of a sticky Boradcast Intent, or if it was just sent?

Example for sticky broadcast

When you call registerReceiver() for that action -- even with a null BroadcastReceiver -- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.





Thursday, January 26, 2012

Android Basics

Lets starts with the basic of Android i.e Activity life cycle. Each android java class extends with Activity class and it should be with proper implementation of each step need to be done to provide a complete and full life cycle of that activity and it also gives seamless running of the application.At the same time we can also write our application without all the steps involved in life cycle of activity but it will not give proper structure of code and also sometimes leads to exception of the application.

Activity Life Cycle

Activity Launched -- onCreate() -- onResume() -- onPause() -- onDestroy()

Apart from above methods, start and stop, onRestart methods are also available but it is not much as important as above methods.

Each class in Android must extend Activity class to create an application.When activity gets started the first method onCreate() will be called in that we need to set the content view with the XML layout for UI design components.

Then onResume() method will be called when activity is again invoked i.e. navigate to previously opened activity.

onPause() method will be invoked when the activity gets navigation action, the current activity will be in pause state without doing any performance.

onDestroy() method is used to destroy the current activity.

Wednesday, January 25, 2012

Android Introduction

Android is the leading mobile OS around the world in many countries and here are the concepts that are explained with real time situation which i have obtained during my application creation.

Lets starts with the basic requirements which are need to be done before starting the application in android.

Following components are need to be downloaded initially
  • Java latest version along with JDK.
  • Eclipse tool.It should be Eclipse 3.6(Helios) 0r greater.
  • SDK latest version from Android's developer site.
After installed all those downloads need to update Eclipse along with ADT plugin to create and run Android applications.