Registering android App with facebook

Hello Friends,

First of all you might be thinking that what is the need of registering your android application with facebook? Then I want to clarify that If you want to integrate Android application with facebook then  you need to register your android app with the facebook.

Today I am going to explain you how to register your android application with facebook.

Following are two  easy steps to do this.

Step: 1   Generating App Signature for Facebook Settings

You can generate your application signature (keyhash) using keytool that comes with java. But to generate signature you need openssl installed on your pc. If you don’t have one download openssl from here and set it in your system environment path.

Open your command prompt (CMD) and run the following command to generate your keyhash. While generating hashkey it should ask you password. Give password as android. If it don’t ask for password and don’t give you app signature then your keystore path is incorrect.

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Indies\.android\debug.keystore" | openssl sha1 -binary | openssl base64

Step: 2    Registering your Facebook Application

After generating your app signature successfully, register your facebook application by going to create new facebook   application and fill out all the information needed. And select Native Android App and give your hashkey there which you generated previously using keytool.


fbId

See the following image which shows application Id which you have to use in your application for accessing facebook:
2013-01-05_122015

Expandable ListView in Android

Hello Friends,

Today,I will explain you about Expandable listview in android that what is actually Expandable Listview and how it works with simple example.

ExpandableListView is very useful when you want to sort lists into categories.
Like: If you want to make an app for downloading movies and  you might want to categories them by genre, so you can navigate through them easier using ExpandableListView.

A view that shows items in a vertically scrolling two-level list. This differs from the ListView by allowing two levels: groups which can individually be expanded to show its children. The items come from the  ExpandableListAdapter associated with this view.

Now, We will go through one simple example so you can get some idea.

1)  Lets first create a new Android project and name it “indies.expandListViewDemo”
and the build target for Android 2.2, and next set the following:
Application name: Movie expListView
Package name: com.indies.expandListView
Create Activity (Checked): MovieActivity
Then press Finish.

2)Basic Layout:

The layout is fairly simple.
Go to res->layout and open the file main.xml
There you’ll only find a LinearLayout and a TextView.
Remove the TextView and add the following

<ExpandableListView
android:id="@+id/ExpListview"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:groupIndicator="@null" />

So now, the code should look like this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android=<i>"http://schemas.android.com/apk/res/android"</i>
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#000000"
android:paddingLeft="5dip"
android:paddingRight="5dip"
android:paddingTop="5dip">

<ExpandableListView
android:id="@+id/ExpListView"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:cacheColorHint="#000000"
android:groupIndicator="@null"/>
</LinearLayout>

3)  Creating  classes for handle the data

Let’s start out by creating a new package in the src-folder and name com.indies.expandListView.Classes
In this package we are going to create 2 class-files, one named ExpandListGroup.java, and the other name ExpandListChild.java.
In this code we will only get and set the values.

The ExpandListChild.java is going to hold 1 value  Name :

package com.indies.expandListView.Classes;

public class ExpandListChild {

private String Name;
public String getName() {
return Name;
}

public void setName(String Name) {
this.Name = Name;
}}

And the ExpandListGroup.java is going to hold 2 values called Name and Items

package com.indies.expandListView.Classes;

import java.util.ArrayList;

public class ExpandListGroup {

private String Name;
private ArrayList<ExpandListChild> Items;

public String getName() {
return Name;
}

public void setName(String name) {
this.Name = name;
}

public ArrayList<ExpandListChild> getItems() {
return Items;
}
}

4) The Adapter: Here is the somewhat tricky part. the ExpandListAdapter, this is the code that will handle the Items so they can be displayed. For this part we are going to create a new package, and we are naming it com.indies.expandListView.Adapter In this package we are going to create a new class called ExpandListAdapter.java Here is the code for that class

package com.indies.expandListView.Adapter;

import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import com.indies.expandListView.Classes.ExpandListGroup;
import com.indies.expandListView.Classes.ExpandListChild;
import com.indies.expandListView.R;

public class ExpandListAdapter extends BaseExpandableListAdapter {

private Context context;
private ArrayList<ExpandListGroup> groups;
private ExpandableListView mExpandableListView;
private int[] groupStatus;

public ExpandListAdapter(Context context,ExpandableListView pExpandableListView, ArrayList<ExpandListGroup> groups) {

this.context = context;
this.groups = groups;
mExpandableListView=pExpandableListView;
groupStatus = new int[groups.size()];
setListEvent();
}

private void setListEvent() {
mExpandableListView.setOnGroupExpandListener(new OnGroupExpandListener() {

@Override
public void onGroupExpand(int arg0) {
groupStatus[arg0] = 1;
}
});

mExpandableListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {

@Override
public void onGroupCollapse(int arg0) {
groupStatus[arg0] = 0;
}
});
}

public void addItem(ExpandListChild item, ExpandListGroup group) {

if (!groups.contains(group)) {
groups.add(group);
}

int index = groups.indexOf(group);
ArrayList<ExpandListChild> ch = groups.get(index).getItems();
ch.add(item);
groups.get(index).setItems(ch);
}

public Object getChild(int groupPosition, int childPosition) {

ArrayList<ExpandListChild> chList = groups.get(groupPosition).getItems();
return chList.get(childPosition);
}

public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}

public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view,

ViewGroup parent) {
ExpandListChild child = (ExpandListChild) getChild(groupPosition, childPosition);

if (view == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view = infalInflater.inflate(R.layout.<i>expandlist_child_item</i>, null);
}

TextView tv = (TextView) view.findViewById(R.id.<i>item_title);
tv.setText(child.getName().toString());
return view;
}

public int getChildrenCount(int groupPosition) {

ArrayList<ExpandListChild> chList = groups.get(groupPosition).getItems();
return chList.size();
}

public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}

public int getGroupCount() {
return groups.size();
}

public long getGroupId(int groupPosition) {
return groupPosition;
}

public View getGroupView(int arg0, boolean arg1, View arg2, ViewGroup arg3)  {

GroupHolder groupHolder;

if (arg2 == null) {
arg2 = LayoutInflater.from(this.context).inflate(R.layout.expandlist_group_item,null);

groupHolder = new GroupHolder();
groupHolder.img = (ImageView) arg2.findViewById(R.id.tag_img);
groupHolder.title = (TextView) arg2.findViewById(R.id.group_title);
arg2.setTag(groupHolder);
}
else
{
groupHolder = (GroupHolder) arg2.getTag();
}

if (groupStatus[arg0] == 0) {

groupHolder.img.setImageResource(R.drawable.down_arrow);
}
else {

groupHolder.img.setImageResource(R.drawable.up_arrow);
}

groupHolder.title.setText(groups.get(arg0).getName());
return arg2;
}

class GroupHolder {
ImageView img;
TextView title;
}

public boolean hasStableIds() {
return true;
}

public boolean isChildSelectable(int arg0, int arg1) {
return true;
}

}

Above code gets each group and draws it on the screen in the correct order. Then, when you expand one of them, it gets the Childs and draws them on the screen in the correct order. Above code also sets the displayed text for each group and child.

5)  Group and child layout Lets go into the res->layout and add 2 new xml files named expandlist_child_item.xml and expandlist_group_item.xml The code for each of them are very  simple. For the expandlist_group_item.xml

<?xml version=<i>"1.0"</i> encoding=<i>"utf-8"</i>?>
<RelativeLayout xmlns:android=<i>"http://schemas.android.com/apk/res/android"</i>

android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:paddingTop="5dip">

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="70dp"
android:background="#13a0d5"
android:gravity="center_vertical">

<TextView
android:id="@+id/group_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="15dip"
android:textColor="#ffffff"
android:textSize="25dip"
android:textStyle="bold"/>
</LinearLayout>

<ImageView
android:id="@+id/tag_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_alignParentRight="true"
android:src="@drawable/down_arrow"/>

</RelativeLayout>

Now, For the expandlist_child_item.xml

<?xml version=<i>"1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=<i>"http://schemas.android.com/apk/res/android"</i>

android:id="@+id/groupItem"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#0b5c7a"
android:clickable="true" >

<TextView
android:id="@+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="15dip"
android:layout_marginLeft="15dip"
android:text="sample"
android:textColor="#ffffff"
android:textSize="20sp"/>
</LinearLayout>

6)  Activity: Go in to src->com.indies.expandListView and open the MainActivity.java This is the code you’ll see.


package com.indies.expandListView;

import java.util.ArrayList;
import com.indies.expandListView.Adapter.ExpandListAdapter;
import com.indies.expandListView.Classes.*;

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

public class MovieActivity extends Activity {
    /** Called when the activity is first created. */
	private ExpandListAdapter ExpAdapter;
	private ArrayList<ExpandListGroup> ExpListItems;
	private ExpandableListView ExpandList;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ExpandList = (ExpandableListView) findViewById(R.id.ExpListView);
        ExpListItems = SetStandardGroups();
        ExpAdapter=new ExpandListAdapter(getApplicationContext(),ExpandList,ExpListItems);
        ExpandList.setAdapter(ExpAdapter);
    }

    public ArrayList<ExpandListGroup> SetStandardGroups() {
    	ArrayList<ExpandListGroup> list = new ArrayList<ExpandListGroup>();
    	ArrayList<ExpandListChild> list2 = new ArrayList<ExpandListChild>();
        ExpandListGroup gru1 = new ExpandListGroup();
        gru1.setName("Action Movies");
        ExpandListChild ch1_1 = new ExpandListChild();
        ch1_1.setName("The Dark night");

        list2.add(ch1_1);
        ExpandListChild ch1_2 = new ExpandListChild();
        ch1_2.setName("Ghayal");
        list2.add(ch1_2);
        ExpandListChild ch1_3 = new ExpandListChild();
        ch1_3.setName("Sigham");
        list2.add(ch1_3);
        gru1.setItems(list2);
        list2 = new ArrayList<ExpandListChild>();

        ExpandListGroup gru2 = new ExpandListGroup();
        gru2.setName("Commmedy");
        ExpandListChild ch2_1 = new ExpandListChild();
        ch2_1.setName("Heraferi");
        list2.add(ch2_1);
        ExpandListChild ch2_2 = new ExpandListChild();
        ch2_2.setName("Chupke Chupke");
        list2.add(ch2_2);
        ExpandListChild ch2_3 = new ExpandListChild();
        ch2_3.setName("HouseFull-2");
        list2.add(ch2_3);
        gru2.setItems(list2);
        list.add(gru1);
        list.add(gru2);

        return list;
    }
}
 

Now we set some default items to a list, load the list to the Adapter, and apply the adapter to the ExpandableListView The finished product of this tutorial will look like this

image

Hope it helps.HaPpY Coding. 🙂

Android Activity Lifecycle

Hello, Everyone Today I am going to describe you about Activity Lifecycle of Android. Activity means nothing but it is simply a Screen or a page.When I first started programming for the Android I was quite confused about the life-cycle of activities. It seemed almost strange how the application started, stopped, and paused without seemingly any logical reasoning. The activity would be destroyed and re-created when the screen was rotated and paused when other applications were started. Now come to the point, seven methods are called during android activity lifecycle.

1)    OnCreate()

2)    OnStart()

3)    OnResume()

4)    OnPause()

5)    OnStop()

6)    OnRestart()

7)    OnDestroy()

I will explain all this methods and also how they work and their usefulness  in this post.

First of all see below Image for getting some idea about how activity lifecycle works.

mdtqE

1) onCreate ():- This method is called when the activity is first created. In this method you have to do all of your normal static set up: create views, bind data to lists, etc. Always followed by onStart ().

2) onStart ():-This method is called when the activity is becoming visible to the user. This is followed by onResume () if the activity comes to the foreground, or   onStop () if it becomes hidden.

3) onResume():-This method is 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. This method is always followed by onPause().

4) onPause ():-This method is called when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A’s onPause () returns, so be sure to not do anything lengthy here.

5) onStop ():-This method is called when you are no longer visible to the user. You will next receive either onRestart (), onDestroy (), or nothing, depending on later user activity.

Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity’s process running after its onPause () method is called.

6) onRestart ():-This method is called after your activity has been stopped. It is called just before your activity start again. Always followed by onStart()

7) onDestroy():-The final call you receive before your activity is destroyed. This can happen either because the activity is finishing .someone called finish () on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing () method.

When the Activity first time loads the events are called as below:

i)   onCreate()

ii)  onStart()

iii) onResume()

 When you click on Phone button the Activity goes to the background & below events are called:

i)  onPause ()

ii) onStop ()

 Exit the phone dialer & below events will be called:

i)   onRestart()

ii)  onStart()

iii) onResume()

 When you click the back button OR try to finish () the activity the events are called as below:

i)   onPause()

ii)  onStop()

iii) onDestroy()

 Hope it helps in understanding Activity Lifecycle of android. Happy Coding 🙂

 

GCM(Google Cloud Messaging) Configuration for using in Android

GCM(Google Cloud Messaging)

Hello friends,

Today I will explain you how to use GCM(Google Cloud Messaging) service which is provided by Google. Google Cloud Messaging for Android (GCM) is a service which allows you to send data from your server to your users’ Android-device. This could be a lightweight message telling your app there is new data to be fetched from the server, or it could be a message containing up to 4kb of payload data. This is very helpful if you want to send instant notification to your User after some event(action).

The GCM service handles all aspects of queueing of messages and delivery to the target Android application running on the target device. GCM is completely free no matter how big your messaging needs are. For using this service ,you need to register to google for getting API key .

Follow the below steps to register.

1)    Open  Google API Registration Page

2) If you haven’t created an API project yet, this page will prompt you to do so:

gcm-create-api-proj

3)    Click Create project. Your browser URL will change to something like:

https://code.google.com/apis/console/#project:4815162342
4)    Note Down the  value after #project: (4815162342 in this example). This is your project number, and it will be used later on in your android code as the GCM sender ID.

 

Getting API KEY

  1. In the main Google APIs Console page, select API Access. You will see a screen following screen:

gcm-api-access

2)    Click Create new Server key. Either a server key or a browser key should work. The advantage to using a server key is that it allows you to whitelist IP addresses

After that click on Create button which will display following screen:

gcm-api-key

API key value (YourKeyWillBeShownHere) in this example, as it will be used later on.

Now,How to use this API key in Android??.For that you have to do some  configuaration.

See the following steps..

1)    From the SDK Manager, install Extras > Google Cloud Messaging for Android   Library.

After Installing go to the path: YOUR_SDK_ROOT\extras\google\gcm\gcm-client\dist

My path is: C:\Users\MYPC\android-sdks\extras\google\gcm\gcm-client\dist

2)    From this folder copy the JAR file gcm.jar to your application’s classpath.Remember one thing GCM requires Android 2.2 or later

3)    Declare and use a custom permission in your application’s  Manifest file so  only this application can receive GCM messages:

<permission android:name="my_app_package.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="my_app_package.permission.C2D_MESSAGE" />

4)    Add the following Permissions in Manifest file:


!-- App receives GCM messages. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- GCM connects to Google Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" /></pre>
</div>

5)    Add the following broadcast receiver in Manifest file:

<receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="my_app_package" />
</intent-filter>
</receiver>

6)    Add the following intent service:

<service android:name=".GCMIntentService" />

Atlast One Important thing,For using or testing your App in Emulator you need to test it on Google API device only.For that you have to create Emulator with Google API.

Second thing you need to create or  sign In with your google account in Emulator.

For that,After launching emulator press Menu button goto Settings. Select Accounts & Sync. And then press Add Account button and add a Google account

That’s it.After following above steps you can able to use GCM in your android application.

Hope it helps.Thanks.

Your Queries are always welcomed 🙂