Tuesday, February 26, 2013

How to use Emulator camera and gallery in Android : Camera Capture and Gallery in Android Emulator :Enable camera in Android Emulator : Media Not found error in Android

Hello friends,
At the time of testing camera capture and  gallery in android emulator we got a message "Please insert a SD-Card". That mean we are not able to test camera and gallery functionality on emulator but no need to worry follow my blog step by step and it will help you.

1)Open you eclipse

2)Click on AVD Manager from the top of eclipse


3)Now create new AVD or Edit one from listed AVD.


4)First set SD-card size and after that click on create new Hardware


5)And now from property choose SD-card and camera if available in list


6)Run your project and enjoy :)


If it will help you please comment on my blog.
Thanks,

Tuesday, February 19, 2013

What is the life cycle of an Android activity? : Activity Life cycle in Android


Hello Friends,
          Today I am going to share my very Important research on Activity Life Cycle in Android. We all are good in development but sometimes we get  confused or get stucked in Activity Life Cycle, For that I have invested  lot of time and  i tested it manually and finally got some positive result, thats what I want share with you.
Hope it will help you.

You can refer below link also it will give you more detail-
http://developer.android.com/reference/android/app/Activity.html


---------------------------------------------------------------------
First Page:

-------------------------------------------------------------------------------------------
Second Page:

--------------------------------------------------------------------------

Activity Defnition: A single screen in an application, with supporting Java code.
Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity,the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.

When the Activity first time loads then following events are called:
onCreate()
onStart()
onResume()

When we move to next Activity then below events called:
onPause()
onStop()

When we back from Next Activity or press back button then below events called:
onRestart()
onStart()
onResume()

When we press Device Home button, application running in background and below events called:
onPause()
onStop()

When we launch, application from background then below events called:
onRestart()
onStart()
onResume()

When we click the back button OR try to finish the activity then below events are called:
onPause()
onStop()
onDestroy()

For more detail please copy below code and check your log step by step it will give you more help-
1)MainActivity.java

package com.example.activitylifecycle;

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

public class MainActivity extends Activity {
Button btnNext;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnNext = (Button) findViewById(R.id.button1);
Log.i("Activity Life Cycle Result:", "On Create call");
/**
* Next Button clicked
*/
btnNext.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, NextPage.class);
startActivity(intent);
}
});

}

@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.i("Activity Life Cycle Result:", "On start call");
}

@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.i("Activity Life Cycle Result:", "On Re-start call");
}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i("Activity Life Cycle Result:", "On resume call");
}

@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.i("Activity Life Cycle Result:", "On pause call");
}

@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.i("Activity Life Cycle Result:", "On stop call");
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i("Activity Life Cycle Result:", "On destroy call");
}
}


2)NextPage.java

package com.example.activitylifecycle;

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

public class NextPage extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.next);

}
}


3)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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp"
        android:padding="@dimen/padding_medium"
        android:text="Activity Life Cycle Testing"
        android:textSize="25sp"
        tools:context=".MainActivity" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="118dp"
        android:text="Next Page" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="18dp"
        android:padding="@dimen/padding_medium"
        android:text="Please check your Log"
        android:textSize="25sp"
        tools:context=".MainActivity" />

</RelativeLayout>

4)next.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" >

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

</LinearLayout>


Your  any Comments and Suggestions would be greatly appreciated.

Thanks,

Monday, February 18, 2013

Sign up with Facebook in Android | Getting Facebook user detail in Android | Facebook Integration In Android

Hello friends,
        Today I am going to share very important code for Signup/Login with facebook in our application(Getting Facebook access token, user-id, user-name, email-id, gender, birthday etc). For that I am using Facebook graph API. Step by step process is given below hope it will help some one-

1)Print Screen:
a)Main page:

b)After Facebook button clicked:


2)Second step go to Facebook developer web-sight and create an app from below url-
http://developers.facebook.com/

a)For new application click on Apps button first-

b)After that click on "+Create New App"-

c)Then fill App Name: button below and press continue button-

d)Finally copy App ID/API Key


3)Create a new android application
4)Create a new Activity class "MainActivity.java"and copy below code-

package com.example.signupwithfacebook;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class MainActivity extends Activity {
Button btnFacebook;
Context context = MainActivity.this;
// please put your APP-ID below
String Facebook_APP_ID = "YOUR-APP-KEY";// don't forget most important
Facebook facebook = new Facebook(Facebook_APP_ID);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
private SharedPreferences mPrefs;
String access_token;
Boolean Connectiontimeout = false;
String imageURL = "";
Bitmap profilePic;
ImageView userImage;
TextView textName;
TextView textUserName;
TextView textGender;
String name = "";
String userName = "";
String gender = "";

@Override
/**
* @author manish
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnFacebook = (Button) findViewById(R.id.btn_facebook);
userImage = (ImageView) findViewById(R.id.imageView1);
textName = (TextView) findViewById(R.id.textView2);
textUserName = (TextView) findViewById(R.id.textView4);
textGender = (TextView) findViewById(R.id.textView6);
/**
* on click facebook button
*/
btnFacebook.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
/**
* check for network connectivity
*/
if (isNetworkAvailable(context) == true) {
accessTokenFacebook();

} else {
Toast.makeText(MainActivity.this, "No Network Connection",
Toast.LENGTH_SHORT).show();
}

}
});
}

/**
* Network testing method you can put it into Helper/Utility class also
*/
public static boolean isNetworkAvailable(Context mContext) {

ConnectivityManager cm = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
Log.e("Network Testing", "***Available***");
return true;
}
Log.e("Network Testing", "***Not Available***");
return false;
}

/**
* Function to get facebook Access token
* */

public void accessTokenFacebook() {

mPrefs = getPreferences(MODE_PRIVATE);
access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
// Log.e("Facebook token", access_token);

if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}

/**
* Only call authorize if the access_token has expired.
*/
if (!facebook.isSessionValid()) {

facebook.authorize(this, new String[] {}, new DialogListener() {
public void onComplete(Bundle values) {
try {
JSONObject me = new JSONObject(facebook.request("me"));
SharedPreferences.Editor editor = mPrefs.edit();
String id = me.getString("id");
System.out
.println("******facebook.getAccessToken()****"
+ facebook.getAccessToken());
editor.putString("userid", id);
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
new getFacebookData().execute();
} catch (Exception e) {
// TODO: handle exception
}
}

public void onFacebookError(FacebookError error) {
}

public void onError(DialogError e) {
}

public void onCancel() {
}
});
} else {
new getFacebookData().execute();
}

}

/**
* Async class for getting facebook data in background thread
*
* @author manish
*
*/

public class getFacebookData extends AsyncTask<String, Void, String> {

ProgressDialog pd = null;

@Override
protected void onPreExecute() {
pd = ProgressDialog.show(MainActivity.this, "Please wait",
"Loading please wait..", true);
pd.setCancelable(true);

}

@Override
protected String doInBackground(String... params) {
fbUserProfile();
return null;
}

@Override
protected void onPostExecute(String result) {
pd.dismiss();
if (Connectiontimeout != true) {
textName.setText(name);
textUserName.setText(userName);
textGender.setText(gender);
userImage.setImageBitmap(profilePic);
} else {
Toast.makeText(MainActivity.this, "Connection Time out",
Toast.LENGTH_SHORT).show();
}
}

}

/**
* getting user facebook data from facebook server
*/
public void fbUserProfile() {

try {
access_token = mPrefs.getString("access_token", null);
JSONObject jsonObj = null;
JSONObject jsonObjData = null;
JSONObject jsonObjUrl = null;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 50000);
HttpConnectionParams.setSoTimeout(httpParameters, 50000);

HttpClient client = new DefaultHttpClient(httpParameters);

String requestURL = "https://graph.facebook.com/me?fields=picture,id,name,gender,username&access_token="
+ access_token;
Log.i("Request URL:", "---" + requestURL);
HttpGet request = new HttpGet(requestURL);

HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String webServiceInfo = "";

while ((webServiceInfo = rd.readLine()) != null) {
Log.i("Service Response:", "---" + webServiceInfo);
jsonObj = new JSONObject(webServiceInfo);
jsonObjData = jsonObj.getJSONObject("picture");
jsonObjUrl = jsonObjData.getJSONObject("data");
name = jsonObj.getString("name");
userName = jsonObj.getString("username");
gender = jsonObj.getString("gender");
imageURL = jsonObjUrl.getString("url");
profilePic = BitmapFactory.decodeStream((InputStream) new URL(
imageURL).getContent());
}

} catch (Exception e) {
Connectiontimeout = true;
}
}

}


5)Create a layout "activity_main.xml" and copy below code-

<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"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btn_facebook"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@drawable/ic_launcher" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/textView"
        android:layout_marginTop="20dp"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/textView1"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="20dp"
            android:text="user name:" />

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/textView3"
            android:layout_alignLeft="@+id/textView2" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/textView3"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="20dp"
            android:text="your gender:" />

        <TextView
            android:id="@+id/textView6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/textView5"
            android:layout_alignLeft="@+id/textView4" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignRight="@+id/textView3"
            android:layout_marginTop="5dp"
            android:text="your name:" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/textView1"
            android:layout_alignBottom="@+id/textView1"
            android:layout_centerHorizontal="true" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_alignLeft="@+id/textView6"
            android:layout_below="@+id/textView6"
            android:layout_marginTop="17dp"
            android:scaleType="fitXY"
            android:src="@drawable/camera_image" />
    </RelativeLayout>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/btn_facebook"
        android:layout_alignBottom="@+id/btn_facebook"
        android:layout_centerHorizontal="true"
        android:text="Click facebok button"
        android:textSize="20sp" />

</RelativeLayout>

6)And now open your manifest.xml file and give below two permission-

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

7)Last and Important step run your application and enjoy :)

Thanks,

             


Wednesday, February 6, 2013

Multi Touch List View : Multi Click List View Demo in Android : Click button in List View in Android

Hello friends,

Today I am going to share very Important code for Multi-Clickable  Listview in Android.
Suppose you want perform multiple task on click of Listview like- edit, delete, share and go to another activity etc in this case my blog will help you. For this I am using custom Array-adapter. Screen shot and code is given below step by step-

1-Print Screen:

a)Normal view-

b)Main List View Clicked-

c)Edit Button Clicked-

d)Delete Button Clicked-


  2) Create MainActivity.java class
package com.example.multitouchlistview;


import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
ListView userList;
UserCustomAdapter userAdapter;
ArrayList<User> userArray = new ArrayList<User>();

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

/**
* add item in arraylist
*/
userArray.add(new User("Mumer", "Spain", "Spain"));
userArray.add(new User("Jon", "EW", "USA"));
userArray.add(new User("Broom", "Span", "SWA"));
userArray.add(new User("Lee", "Aus", "AUS"));
userArray.add(new User("Jon", "EW", "USA"));
userArray.add(new User("Broom", "Span", "SWA"));
userArray.add(new User("Lee", "Aus", "AUS"));
/**
* set item into adapter
*/
userAdapter = new UserCustomAdapter(MainActivity.this, R.layout.row,
userArray);
userList = (ListView) findViewById(R.id.listView);
userList.setItemsCanFocus(false);
userList.setAdapter(userAdapter);
/**
* get on item click listener
*/
userList.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
Log.i("List View Clicked", "**********");
Toast.makeText(MainActivity.this,
"List View Clicked:" + position, Toast.LENGTH_LONG)
.show();
}
});

}

}


  3)Create UserCustomAdapter.java for custom view

package com.example.multitouchlistview;

import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class UserCustomAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
ArrayList<User> data = new ArrayList<User>();

public UserCustomAdapter(Context context, int layoutResourceId,
ArrayList<User> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;

if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.textName = (TextView) row.findViewById(R.id.textView1);
holder.textAddress = (TextView) row.findViewById(R.id.textView2);
holder.textLocation = (TextView) row.findViewById(R.id.textView3);
holder.btnEdit = (Button) row.findViewById(R.id.button1);
holder.btnDelete = (Button) row.findViewById(R.id.button2);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
User user = data.get(position);
holder.textName.setText(user.getName());
holder.textAddress.setText(user.getAddress());
holder.textLocation.setText(user.getLocation());
holder.btnEdit.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Toast.makeText(context, "Edit button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnDelete.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Delete Button Clicked", "**********");
Toast.makeText(context, "Delete button Clicked",
Toast.LENGTH_LONG).show();
}
});
return row;

}

static class UserHolder {
TextView textName;
TextView textAddress;
TextView textLocation;
Button btnEdit;
Button btnDelete;
}
}


4)Create User.java class

package com.example.multitouchlistview;

public class User {
String name;
String address;
String location;

public String getName() {
return name;
}

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

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getLocation() {
return location;
}

public void setLocation(String location) {
this.location = location;
}

public User(String name, String address, String location) {
super();
this.name = name;
this.address = address;
this.location = location;
}

}

5)Create 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:background="#0099CC"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Multi Touch Listview"
        android:textColor="#FFFFFF"
        android:textSize="25sp" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/textView"
        android:layout_marginTop="5dp"
        android:cacheColorHint="#00000000" />

</RelativeLayout>

6)Create custom layout for view row.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:padding="5dp"
    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:text="User Name"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="5dp"
        android:text="Address"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="16sp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="80dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:background="#FFFFFF"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:text="Edit Data"
        android:textColor="#0099CC" />

    <Button
        android:id="@+id/button2"
        android:layout_width="80dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="3dp"
        android:background="#FFFFFF"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:text="Delete"
        android:textColor="#0099CC" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="5dp"
        android:text="Location" />

</RelativeLayout>

Note- Don't forget to add below line in Button View-
  android:focusable="false"
  android:focusableInTouchMode="false"