Tuesday, December 2, 2014

What is a bundle in an Android


Bundle is generally used for passing data between various Activities of android. It depends on you what type of values you want to pass but bundle can hold all types of values and pass to the new activity.

You can use it like .....

Intent intent = new
Intent(getApplicationContext(),SecondActivity.class);
intent.putExtra("myKey",AnyValue);  
startActivity(intent);

Now you can get the passed values by...

Bundle extras = intent.getExtras(); 

String tmp = extras.getString("myKey");

Resources in Android

1.Strings
Its kept under values folder and strings.xml. There are different values folder based on language. Ex. values-en for english.
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">HelloWorld</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
</resources>

To add new resource file to eclipse. Right click on “Res” folder or any folder in which you want to add resource file.  Select “New” => “Other” => “Android” => “ Android XML values File” => Enter the file name and click on Next =>  Choose configuration Folder dialog will appear then  choose “Available Qualifiers” (If you want to choose the different language file use language as qualifier the choose the language code. Two letter language code is used.).  You can add region to distinguish UK english and US english.


{Even there is option for resources to the particular version. }

2. Layout
You can have two different layout for same layout.   Select “New” => “Other” => “Android” => “ Android XML Layout File” => Choose configuration Folder dialog will appear then  choose “Available Qualifiers” then Select “Orientation” . In this case  two folders will get created on for potrait and another for landscape.[ Landscape folder will be named “layout-land”  for Landscape use attribute “android:orientation”=“horizontal”].

You can specify the weight of particular view with attribute “android:layout_weight”=“1”;

3.Dimension
 You can create the dimens.xml and set the value in it

<resources>

    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

</resources>
4.Colors
You can specify the colors in colors.xml ex:-
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="TextViewBackground">#FFEE00CC</color>
</resources>


5. Styles

You can specify the styles  in styles.xml ex:-
<resources>
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>
    <style name="Theme.Default" parent="@android:style/Theme"></style>
<style name="Theme.NoTitle" parent="@android:style/Theme.NoTitleBar"></style>
<style name="Theme.FullScreen" parent="@android:style/Theme.NoTitleBar.Fullscreen"></style>

<style name= "temp">
    <item name="android:background">@color/TextviewBackground</item>
</style>
</resources>

Using the xml for view is similar to to html and css. layout xml is like the html and style,colors are like css.


Hierarchy Viewer in Android

Run app. Then go to eclipse => Window => “Open perspective” => “Other” =>  “Hierarchy View”
OR you can run from the command line also.

In every device there are multiple windows displayed. If you select one of window then you can see hierarchy view.
Then in “window”  you will able to see the connected devices + emulator. In window there are two icons i. Refresh ii. Load the view hierarchy into tree view.

In this one you can see the how much time one view / layout take to load it.

In tree view there is option i.to save the tree view as a PNG view. ii.Capture the window layer as a photoshop document (This feature is good for designer).


Mentioning Color in android

First way is #RGB here RGB in hex i.e Ex for red #F00 (Here one byte) .
Second way is #RGB here RGB in hex i.e Ex for red #FF0000 (Here two byte).
Third way is to use the standard color mention by android sdk itself. ex:- “@android:color/darker_gray” . 

In both case we can add alpha Eg #FFFF0000 or #FF00 .(i,e We can add(prepend)  the alpha . Bold the alpha).
We can specify the icon/image to be as background to the view in layout xml with value as “@drawable/fileNameInDrawableFolder”.


View Groups in Android

View groups can displayed more than one view. (Can contain more than one view). Its like container.
They do extend the view class and add methods that makes easier to work with multiple view contain within it.
Will nearly always be used via a subclass.
Some Viewgroups are named __Layout
Ex:- LinearLayout, RelativeLayout, FrameLayout,ListView etc.

1.LinearLayout :- lay out the views in order one after another with the orientation mentioned (Its mentioned as one of its attribute in layout xml file. android:orientation="Vertical” means all the view will be displayed in vertical order).
2.RelativeLayout:- There is no orientation in this layout . Need to provide the relative position in the view. If position not mentioned then all the view appear on one another. We can use the view’s position by specifying  in the view’s attribute ex.  android:layout_below=“@id/textview”.Here @id/textview is the id of the view below which this view will be get displayed.  there are multiple option like above, right, left etc.


Views in Android

Views is something that can be displayed.
Sometimes called as widgets (not the widget displayed on launcher screen) or components.
View can be subclassed or used alone.
Some view are named __view
Ex:-Imageview, Button, EditText,CheckBox.

Giving ID to view
we cab use “android:id” as attribute to mention id ex:-   “android:id” =“@+id/TextView”. here +id which means to create new fresh reference to this id. Here TextView is the name of id which is going to use in other places to refer this one.




Using fragment below honeycomb / Fragment below honeycomb or 3.0

1. Go to “Android SDK Manager” => “Extras” =>”Android Support package” and select and install it.
2. There are multiple ways to add and use the Android support Package into project 
i. Adding jar directly in project
ii. Referencing the library from project. (This option is best because  it is more portable because if you are working with multiple developers then do not have to worry about who has what version of support package.
To implement above (ii) approach go to file explorer got to sdk home then => “android-sdk” => “extras”=> “android” =>”support” under this folder you will find folder with respect to the android version to support it.
ex:- have folder v4 means support 1.4 . Go into the folder copy the .jar file  and add to project ,Normally create a folder (any name but lib is preferable) and jar to it. Then when go to eclipse refresh/F5 to make lib visible in project.
After making the jar visible in the eclipse right click on jar file then => “Build path” => “Add to build path”. After this you will be able to see the jar under the referenced library.

From Honecomb onwards the activity is activity is updated to working with the fragment manager. There is class FragmentActivity in support sdk which will help for fragment in below version.
To get FragmentManager there is method getSupportFragmentManager() (in honeycomb and above the method in which  no support keyword i.e. getFragmentManager() ) which returns the object of FragmentManager class.



Fragment LifeCycle Android

Like Activity , Fragment also has the lifecycle. It works in much same way like activity lifecycle.

  1. onAttach(Activity) called once the fragment is associated with its activity. telling that this fragment is attached to some activity. You can use that activity object to load resources because the activity is derived from context and Context can access the resource available.
  2. onCreate(Bundle) called to do initial creation of the fragment. Loading of fragment.
  3. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
  4. onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.onCreate().
  5. onViewStateRestored(Bundle) tells the fragment that all of the saved state of its view hierarchy has been restored.
  6. onStart() makes the fragment visible to the user (based on its containing activity being started).
  7. onResume() makes the fragment interacting with the user (based on its containing activity being resumed).
As a fragment is no longer being used, it goes through a reverse series of callbacks:
  1. onPause() fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity.
  2. onStop() fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity.
  3. onDestroyView() allows the fragment to clean up resources associated with its View.
  4. onDestroy() called to do final cleanup of the fragment's state.
  5. onDetach() called immediately prior to the fragment no longer being associated with its activity.


Fragment in android (available from 3.0)

It is essentially grouping of UI and the interaction the user can have with that. Here fragment is somewhat similar to model of MVC architecture.
It is not possible to show two activity at the same time because each activity have their own life cycle. If u have shown one that is active other will be inactive.



In above figure shown that two activity needed to display the list and details view . In phone needed two different activity because size is less. In tablet we can show two view in one time so There will be duplicasy of code if same thing used for phone and tablet.
In above case difficult two maintain two code.
The solution to above is fragment .  Fragment is essentially grouping of UI and interaction with user have with that. Fragment is similar to the model in mVC.
Here is solution for above problem.  List fragment is list and Detail fragment for detail view. In phone different activity uses fragment in Tablet one activity uses both fragment.



In phone list activity displays lis fragment and detail activity detail fragment. in tablet both fragment by one custom activity.
Fragment can be made up of one or more views. Fragment can save their own state. So will resume also. 

Om a single screen you can display any number of fragment. Fragment can be reusable. Fragment can be made up of one or more number of views. Fragments typically handle the configuration changes so they can save and restore the ROM state.
In android for view you can use the xml. Fragment may contain layout . 
Layout may also have multiple fragments. There is fragment manager which is     manages the back press.


Compatiablity SDK is there which takes the classes that are available in specific version and make some available to older version. So we can use the same SDK if we want to support the older sdk.

Example

1.Creating new Activity
Right click on package name => new => Class . Give name set base class of this is Activity.
Create the view by adding new xml in layout folder and call setContentView() from onCreate() of new activity.
Add the entry of this new activity in the androidmanifest.xml file.

2. Launching one activity from another
Use intent to launch one activity from another .
Ex:- Here NextActivity is class which belongs to new activity going to launch
Intent i = new Intent(this, NextActivity.class);
startActivity(i);

3.Getting click event
If the view is clickable then you can add method directly in layout ie.  android:onClick=“methodName”   Then the declaration of this method will be like this  public void methodName(View view) {}
Some view are by default clickable (button) but some them are not  (textview) to make them clickable add this property android:clickable="true"  


Some shortcut for android eclipse

Some shortcut (use command in mac instead of ctrl)
For inteliisance use ctrl + spacebar.
ctrl + shift + f for format the xml file.
ctrl + shift + O for orgnize the import 
Adding the override methods in class Right click in the class body  => Source => Override/Implement Methods…

Localisation in Android

in values folder you can add localise file by adding folder values-<Short code of language>.xml ex:- values-FR for french. 

To access the strings defined in strings.xml is accessed by “@string/<its id /name>”

Context in Android


its class , it contain information about the app  environment  for example context allows you to access the resources (which are added in the application). (like NSBundle in iOS).

Android Process lifecycle

Process lifecycle:-
in android needs to remove old process when there is low memory.So decision is made on the state of the activity. There are four states. As mentioned below with highest importance at top
i.Foreground activity considered as the most important.
ii.visible activity:-is considered extremely important and will not be killed unless that is required to keep the foreground activity running.
iii.background activity:- is no longer critical, so the system may safely kill its process to reclaim memory for other foreground or visible processes.
iv. empty process:- is one hosting no activities or other application components (such as Service or BroadcastReceiver classes).These are killed very quickly by the system as memory becomes low. For this reason, any background operation you do outside of an activity must be executed in the context of an activity


Permission in Android


In android there is no lengthy process of app review, so its easy to add app on appstore. but only things is developer has to mention the required permission in the manifest file.

Activity in Android / Activity lifecycle

1.Activity lifecycle:-  we are here look the way Activity represents one screen or one page in your app.
lets say activity start by click on launcher icon.(Activity with intent filter launch will be get launched).

Here is 

1.onCreate() :- its get called very first and only one time. In which we set the  content view of the activity. It is responsible for creation of activity , its view. Allocation of resources etc.This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
2.onStart():-Called when the activity is becoming visible to the user.
3.onResume() will get get called every time the the activity comes in foreground (like viewwillappear in ios).Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.
4.onPause() will be get called every time when the activity goes into background (like viewwilldisappear in ios).Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.
5.onStop() when activity is not visible or say phone call arrives so app goes in background , in this case onStop() gets called. Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one.
6.onDestroy() when back called on the activity. It can be skipped .The final call you receive before your activity is destroyed.


Android Project structure / Package explorer

1. src :- contains the all source files
2.gen :- contains the all generated class for us.
3. bin :- contain the binary or package. 
4.res :- contains the resource used like images, string , layout etc.( non code portion of project).
mdpi - is the original density of android devices.
layout is like xib in iOS .
values folder contain string values.
5.androidmanifest.xml:- table of content for the application. Android (os) system looks into the manifest file for checking the which package usages, android version code and name. Also contain the min sdk version. We also specify the icon , app label , starting activity to use for in manifest file. We specify the activity class name with prepended by . (dot)  (normally it took the package name specified in the same manifest file if we use dot in front of activity name). Activity class name is mentioned under the android:name attribute of Activity tag.
intent filter also mentioned with activity file which is used for purpose of the particular activity like main etc.
6.proguard.cfg:- it is config file for progaurd. Progaurd allows you to obfuscate (making unclear / encrypted) the apk in order to allow other to harder the decode and understand your code.
7.project.properties:- contain the target which you are going to use.

When emulator starts running then the there is one number associated with it , It is port number on which the emulator is running.

When you want to change the target if multiple devices connected then go to  . Run As => Run Configuration => Android Application => Essentials => target => select manual. So it will ask every time which device you want to choose when you want to run app.


Enable debug mode on device

go to Settings => Applications =>check the “unknown sources” then => Developement => check the usb debugging.

What is difference between target and min sdk in Android

Target is the version , eclipse building  and testing against means you can include the methods those are available in the target sdk version.
Min or minimum is lower than target. 
This thing allow us to use some of target version feature in the min sdk. But careful when using such feature. Let say having new feature in target version which are not in min sdk then it may crash in min sdk.

To avoid such things you can use reflection to check availability of method.

Android Some of APIs

1.Location manager:- app can register for the notification of the current location. You can register for particular location and will be notified when u are near to that place. It uses GPS. If device does not have GPS then uses cell tower id to fetch the location information. if he wifi the use its geographical location info.
2.XMPP service:-  It allow any app to send device to device data messages to other android users. Data messages are intents with name/value pair. No need of server to have communication between devices.   server sends the notification to the client.
3.Notification Manger:-  Application can add the notification to status bar. like push / local notification. Notification can have associated action (intent).
4. Views:- contian lots ui components i.e button, textfield, mapview, webview etc.


If you want to add new project to the existing project you can do this by choosing “Add project to workset” then create “new” then  Choose either “Resource” if it is resource or “Java” when add to jar or code.



Android Application Lifecycle

Every app runs in their  own processes (separate).
System process is always runs in background which are responsible for the storing the state of the activity when it goes in background and other come in foreground. eg page at particular scroll position.(This kind of data get stored in system process).
When there is no space for the new process then the most old process get killed. 

Even your app get killed when in background say due to less memory / space. then there entry for navigation stack remain there and this entry is kept in the system process which runs always in background.

Even though app is killed and through navigation we come to particular page then its process gets invoked with the same state.( as state is stored in the system process). App restore the same state. System process keep the data of each activity separately.

Android Application building blocks

Application building blocks:-
1.Activity:- It is UI component correspondence to a single UI Screen.(Like window in win32)
2.IntentReceiver:- Normally to responds to particular status change or notification for which you registered. Can be used for to wake up the process. Some external event can also trigger the your code. You can write some code and waken up by registering through xml when something happen eg when network gone, or network establish, or when phone rings. Intent is something like globally defined with system and when we want to invoke/ needed we just check with system and system chooses the best matching intent. eg. intent is “go to home screen”. You can replace existing intent also.
3.Service:-Its a task does not have UI . like demon process (runs in background).
4.Content Provider:- enable application to share the data with other processes / application. You can keep data in files or in SQlite also 



Android Architecture

Android :- It includes the OS+ middleware + applications. (Linux HAL , device driver ).

1.  Libraries are written in c/ c++.
i.Surface Manager:- Its responsible for the drawing window on the screen. It is responsible for the whole screen may be occupied by different/multiple process. 
ii. OpenGL ES /SGL are the graphics library which includes the s/w if device having 3D chip on it. SGL for 2D.
iii.Media framework :- provided by packet video. (By OMA) Contain all codecs.
iv. Freetypes:- Are for fonts.
v.SQlite:- For data storage.
vi. Webkit:- opensource browser engine.

2. Android runtime:- (Its has  Dalvik virtual machine +  Core Library ). written in c/c++
which executes the dex files. (.dex is equivalent to .class files). .dex contains bytecodes with more efficient way than .class files. bytecode also highly CPU optimised.
Multiple DVM instances are running at the same time.

  Core Library :- written in java. ex. collection , i/o  (utility)etc

3. Application framework:- all in java programming language. It is toolkit almost every app uses it.
1. Activity manager:- manages the lifecycle of the applications. Maintain common backstack like navigation controller stack( this is across the processes also)..
2.Package Manager:- keeps track of which app is installed on your device + with that applications capability.
3.window manager:- manages the window. Java code + little lower with surface manager.
4.Telephony manager :- to access the data related to telephony like network etc.
5.Content provider:- it is the used to share the data across the multiple process.
6.Resource manager :- is reponsible for to store the localizable ie string, bitmaps, layout file 
7. View system:- contain the UI components like button label etc.
8.Location manager:- location related
9. notification manager.:- like push, local notification.


Above all there is application layer. where you will find all the application like addressbook, camera etc.

Thursday, January 2, 2014

R.java files not generated in Android / r.java missing in android project in Android

Android will not generate the R.java after a clean if any of the XML files have errors in them. Check for any errors and fix them. R.java will then be built.
If that doesn't work, sometimes Eclipse looses track of the file. Click your project and hit F5 to Refresh the project.

if you run a clean on the project it should regenerate all the generated java files, namely R.
...and...

In Eclipse, under the Project menu, is an option build automatically. That would help you build the R.java file everytime modifications are made. The Clean... option is also there under Project.

Gridview in android / Gridview example in android / Grid layout in android

In res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:columnWidth="90dp" <!-- coloumn width  -->
    android:numColumns="auto_fit" <!-- number of coloumn will be automatically -->
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"

/>

Open HelloGridView.java and insert the following code for the onCreate() method:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this));

    gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
        }
    });
}

ImageAdapter class which will feed the data to the gridview.

//here we have added a.jpg,b.jpg,c.jpg,d.jpg,e.jpg,f.jpg,g.jpg,h.jpg in the res/drawable folder

package com.example.test;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {

private Context mContext;
private Integer[] mThumbIds = {
           R.drawable.a, R.drawable.b,
           R.drawable.c, R.drawable.d,
           R.drawable.e, R.drawable.f,
           R.drawable.g, R.drawable.h
   };

    public ImageAdapter(Context c) {
        mContext = c;
    }
@Override
public int getCount() {
// TODO Auto-generated method stub
        return mThumbIds.length;

}

@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}

@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView;
        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setImageResource(mThumbIds[position]);
        return imageView;
}

}

Wednesday, January 1, 2014

match_parent vs fill_parent android / what is the difference between match_parent and fill_parent property in android

FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which means that the view wants to be as big as its parent (minus padding)


fill_parent: The view should be as big as its parent (minus padding). This constant is deprecated starting from API Level 8 and is replaced by match_parent.

how to remove title bar in android / How to hide the title bar for an Activity in XML / Remove Android App Title Bar


1. By XML

You need to modify the style.xml file
Inside values/styles.xml
<style name="Theme.Default" parent="@android:style/Theme"></style>
<style name="Theme.NoTitle" parent="@android:style/Theme.NoTitleBar"></style>
<style name="Theme.FullScreen" parent="@android:style/Theme.NoTitleBar.Fullscreen"></style>

Inside values-v11/styles.xml
<style name="Theme.Default" parent="@android:style/Theme.Holo"></style>
<style name="Theme.NoTitle" parent="@android:style/Theme.Holo.NoActionBar"></style>
<style name="Theme.FullScreen" parent="@android:style/Theme.Holo.NoActionBar.Fullscreen"></style>

Inside values-v14/styles.xml
<style name="Theme.Default" parent="@android:style/Theme.Holo.Light"></style>
<style name="Theme.NoTitle" parent="@android:style/Theme.Holo.Light.NoActionBar"></style>
<style name="Theme.FullScreen" parent="@android:style/Theme.Holo.Light.NoActionBar.Fullscreen"></style>

In the application tag of the Manifest file I have added an attribute of:

android:theme="@android:style/Theme.NoTitleBar"

2. By Coding

You can archive the same via coding. Here is a corresponding snippet
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // hide titlebar of application
    // must be before setting the layout
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    // hide statusbar of Android
    // could also be done later
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.main);
    text = (EditText) findViewById(R.id.EditText01);


}