Saturday, September 28, 2013

Dynamic List-View Demo in Android | Dynamically Increase row of list-view in Android | Custom Dynamic list-view in Android

Hello Friends!

Today I am going to post a logical code for add item in list-view dynamically. And increase size of row dynamically.


1)CustomListView.java
package com.manish.customlistview;

import java.util.ArrayList;

import android.os.Bundle;
import android.widget.ListView;
import android.app.Activity;
/**
 *
 * @author manish
 *
 */

public class CustomListView extends Activity {
       ArrayList<Item> imageArry = new ArrayList<Item>();
       CustomImageAdapter adapter;

       @Override
       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              // add image and text in arraylist
              String Video[]={"xyz","abcd"};
              String Song[]={"xyz","abcd","pqerttt","yuioo"};
              String Movi[]={"xyz","abcd","qwer","yuioo","tyyuu","ggggggg","yuioo","tyyuu","ggggggg"};
             
              imageArry.add(new Item(R.drawable.facebook, Song));
              imageArry.add(new Item(R.drawable.outlook, Video));
              imageArry.add(new Item(R.drawable.google, Movi));
             
              // add data in contact image adapter
              adapter = new CustomImageAdapter(this, R.layout.list, imageArry);
              ListView dataList = (ListView) findViewById(R.id.list);
              dataList.setAdapter(adapter);

       }

}


2)CustomImageAdapter.java
package com.manish.customlistview;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
 *
 * @author manish
 *
 */

public class CustomImageAdapter extends ArrayAdapter<Item> {
       Context context;
       int layoutResourceId;
       LinearLayout linearMain;
       ArrayList<Item> data = new ArrayList<Item>();

       public CustomImageAdapter(Context context, int layoutResourceId,
                     ArrayList<Item> 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;

              if (row == null) {
                     LayoutInflater inflater = ((Activity) context).getLayoutInflater();
                     row = inflater.inflate(layoutResourceId, parent, false);

                     linearMain = (LinearLayout) row.findViewById(R.id.lineraMain);

                     Item myImage = data.get(position);
                     for (int j = 0; j < myImage.getName().length; j++) {
                           TextView label = new TextView(context);
                           label.setText(myImage.name[j]);
                           linearMain.addView(label);
                     }
                     ImageView image = new ImageView(context);
                     int outImage = myImage.image;
                     image.setImageResource(outImage);
                     linearMain.addView(image);
              }

              return row;

       }

}

3)Item.java
package com.manish.customlistview;
/**
 *
 * @author manish
 *
 */
public class Item {

       int image;
       String name[];
      
       public Item(int image, String[] name) {
              super();
              this.image = image;
              this.name = name;
       }
       public int getImage() {
              return image;
       }
       public void setImage(int image) {
              this.image = image;
       }
       public String[] getName() {
              return name;
       }
       public void setName(String[] name) {
              this.name = name;
       }

}

4)main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:cacheColorHint="#00000000"
        android:layout_weight="0.55" >
    </ListView>

</LinearLayout>

5)list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/lineraMain"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dp" >

</LinearLayout>

6)AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.manish.customlistview"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.manish.customlistview.CustomListView"
            android:label="@string/title_activity_custom_list_view" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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


</manifest>

Download Zip Code

Thanks!

Tuesday, September 24, 2013

Google account Integration in Android | Login with Gmail | Signup with Google in Android | Get Google Profile photo in Android

Hello Friends,
This is my post for Google account integration with your application,  login with gmail, signup with Google account. Some important step is given below-

Step 1- Create new project say GoogleProfileDemo.
Step 2- Add "Google play service" libray project.
Step 3 - Add needed permission in manifest.xml-

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




1)SplashActivity.java

package com.manish.google.profile;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.auth.GoogleAuthUtil;

/**
 * @author manish
 * 
 */
public class SplashActivity extends Activity {
	Context mContext = SplashActivity.this;
	AccountManager mAccountManager;
	String token;
	int serverCode;
	private static final String SCOPE = "oauth2:https://www.googleapis.com/auth/userinfo.profile";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Splash screen view
		setContentView(R.layout.activity_splash);
			syncGoogleAccount();
		

	}

	private String[] getAccountNames() {
		mAccountManager = AccountManager.get(this);
		Account[] accounts = mAccountManager
				.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
		String[] names = new String[accounts.length];
		for (int i = 0; i < names.length; i++) {
			names[i] = accounts[i].name;
		}
		return names;
	}

	private AbstractGetNameTask getTask(SplashActivity activity, String email,
			String scope) {
		return new GetNameInForeground(activity, email, scope);

	}

	public void syncGoogleAccount() {
		if (isNetworkAvailable() == true) {
			String[] accountarrs = getAccountNames();
			if (accountarrs.length > 0) {
				//you can set here account for login
				getTask(SplashActivity.this, accountarrs[0], SCOPE).execute();
			} else {
				Toast.makeText(SplashActivity.this, "No Google Account Sync!",
						Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(SplashActivity.this, "No Network Service!",
					Toast.LENGTH_SHORT).show();
		}
	}
	public boolean isNetworkAvailable() {

		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;
	}
}

2)HomeActivity.java


package com.manish.google.profile;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * @author manish
 * 
 */
public class HomeActivity extends Activity {
	ImageView imageProfile;
	TextView textViewName, textViewEmail, textViewGender, textViewBirthday;
	String textName, textEmail, textGender, textBirthday, userImageUrl;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		imageProfile = (ImageView) findViewById(R.id.imageView1);
		textViewName = (TextView) findViewById(R.id.textViewNameValue);
		textViewEmail = (TextView) findViewById(R.id.textViewEmailValue);
		textViewGender = (TextView) findViewById(R.id.textViewGenderValue);
		textViewBirthday = (TextView) findViewById(R.id.textViewBirthdayValue);

		/**
		 * get user email using intent
		 */

		Intent intent = getIntent();
		textEmail = intent.getStringExtra("email_id");
		System.out.println(textEmail);
		textViewEmail.setText(textEmail);

		/**
		 * get user data from google account
		 */

		try {
			System.out.println("On Home Page***"
					+ AbstractGetNameTask.GOOGLE_USER_DATA);
			JSONObject profileData = new JSONObject(
					AbstractGetNameTask.GOOGLE_USER_DATA);

			if (profileData.has("picture")) {
				userImageUrl = profileData.getString("picture");
				new GetImageFromUrl().execute(userImageUrl);
			}
			if (profileData.has("name")) {
				textName = profileData.getString("name");
				textViewName.setText(textName);
			}
			if (profileData.has("gender")) {
				textGender = profileData.getString("gender");
				textViewGender.setText(textGender);
			}
			if (profileData.has("birthday")) {
				textBirthday = profileData.getString("birthday");
				textViewBirthday.setText(textBirthday);
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public class GetImageFromUrl extends AsyncTask<String, Void, Bitmap> {
		@Override
		protected Bitmap doInBackground(String... urls) {
			Bitmap map = null;
			for (String url : urls) {
				map = downloadImage(url);
			}
			return map;
		}

		// Sets the Bitmap returned by doInBackground
		@Override
		protected void onPostExecute(Bitmap result) {
			imageProfile.setImageBitmap(result);
		}

		// Creates Bitmap from InputStream and returns it
		private Bitmap downloadImage(String url) {
			Bitmap bitmap = null;
			InputStream stream = null;
			BitmapFactory.Options bmOptions = new BitmapFactory.Options();
			bmOptions.inSampleSize = 1;

			try {
				stream = getHttpConnection(url);
				bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
				stream.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return bitmap;
		}

		// Makes HttpURLConnection and returns InputStream
		private InputStream getHttpConnection(String urlString)
				throws IOException {
			InputStream stream = null;
			URL url = new URL(urlString);
			URLConnection connection = url.openConnection();

			try {
				HttpURLConnection httpConnection = (HttpURLConnection) connection;
				httpConnection.setRequestMethod("GET");
				httpConnection.connect();

				if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
					stream = httpConnection.getInputStream();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return stream;
		}
	}
}

3)AbstractGetNameTask.java


/*
 * Copyright 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.manish.google.profile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;

import com.google.android.gms.auth.GoogleAuthUtil;

import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

/**
 * Display personalized greeting. This class contains boilerplate code to
 * consume the token but isn't integral to getting the tokens.
 */
public abstract class AbstractGetNameTask extends AsyncTask<Void, Void, Void> {
	private static final String TAG = "TokenInfoTask";
	protected SplashActivity mActivity;
   public static String GOOGLE_USER_DATA="No_data";
	protected String mScope;
	protected String mEmail;
	protected int mRequestCode;

	AbstractGetNameTask(SplashActivity activity, String email, String scope) {
		this.mActivity = activity;
		this.mScope = scope;
		this.mEmail = email;
	}

	@Override
	protected Void doInBackground(Void... params) {
		try {
			fetchNameFromProfileServer();
			
		} catch (IOException ex) {
			onError("Following Error occured, please try again. "
					+ ex.getMessage(), ex);
		} catch (JSONException e) {
			onError("Bad response: " + e.getMessage(), e);
		}
		return null;
	}

	protected void onError(String msg, Exception e) {
		if (e != null) {
			Log.e(TAG, "Exception: ", e);
		}
	}

	/**
	 * Get a authentication token if one is not available. If the error is not
	 * recoverable then it displays the error message on parent activity.
	 */
	protected abstract String fetchToken() throws IOException;

	/**
	 * Contacts the user info server to get the profile of the user and extracts
	 * the first name of the user from the profile. In order to authenticate
	 * with the user info server the method first fetches an access token from
	 * Google Play services.
	 * @return 
	 * @return 
	 * 
	 * @throws IOException
	 *             if communication with user info server failed.
	 * @throws JSONException
	 *             if the response from the server could not be parsed.
	 */
	private void fetchNameFromProfileServer() throws IOException, JSONException {
		String token = fetchToken();
		URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token="+ token);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		int sc = con.getResponseCode();
		if (sc == 200) {
			InputStream is = con.getInputStream();
			GOOGLE_USER_DATA = readResponse(is);
			is.close();
			
			Intent intent=new Intent(mActivity,HomeActivity.class);
			intent.putExtra("email_id", mEmail);
			mActivity.startActivity(intent);
			mActivity.finish();
			return;
		} else if (sc == 401) {
			GoogleAuthUtil.invalidateToken(mActivity, token);
			onError("Server auth error, please try again.", null);
			//Toast.makeText(mActivity, "Please try again", Toast.LENGTH_SHORT).show();
			//mActivity.finish();
			return;
		} else {
			onError("Server returned the following error code: " + sc, null);
			return;
		}
	}

	/**
	 * Reads the response from the input stream and returns it as a string.
	 */
	private static String readResponse(InputStream is) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] data = new byte[2048];
		int len = 0;
		while ((len = is.read(data, 0, data.length)) >= 0) {
			bos.write(data, 0, len);
		}
		return new String(bos.toByteArray(), "UTF-8");
	}

	
}

4)GetNameInForeground.java


/*
 * Copyright 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.manish.google.profile;

import java.io.IOException;

import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException;
import com.google.android.gms.auth.UserRecoverableAuthException;

/**
 * This example shows how to fetch tokens if you are creating a foreground task/activity and handle
 * auth exceptions.
 */
public class GetNameInForeground extends AbstractGetNameTask {

  public GetNameInForeground(SplashActivity activity, String email, String scope) {
      super(activity, email, scope);
  }


  /**
   * Get a authentication token if one is not available. If the error is not recoverable then
   * it displays the error message on parent activity right away.
   */
  @Override
  protected String fetchToken() throws IOException {
      try {
          return GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
      } catch (GooglePlayServicesAvailabilityException playEx) {
          // GooglePlayServices.apk is either old, disabled, or not present.
      } catch (UserRecoverableAuthException userRecoverableException) {
          // Unable to authenticate, but the user can fix this.
          // Forward the user to the appropriate activity.
          mActivity.startActivityForResult(userRecoverableException.getIntent(), mRequestCode);
      } catch (GoogleAuthException fatalException) {
          onError("Unrecoverable error " + fatalException.getMessage(), fatalException);
      }
      return null;
  }
}

5)activity_splash.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"
    tools:context=".SplashActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Please wait..."
        android:textSize="25sp" />

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="10dp"
        android:text="By:Manish Srivastava" />

</RelativeLayout>

6)activity_home.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:layout_margin="7dp" >

    <TextView
        android:id="@+id/textViewTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Home Page"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/textViewNameLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textViewTitle"
        android:layout_marginTop="15dp"
        android:text="Name:"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/textViewNameValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textViewTitle"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="15dp"
        android:layout_toRightOf="@id/textViewNameLabel"
        android:text="Name:"
        android:textSize="18sp" />
    
      <TextView
        android:id="@+id/textViewEmailLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/textViewNameLabel"
        android:layout_marginTop="15dp"
        android:text="Email:"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/textViewEmailValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textViewNameValue"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="15dp"
        android:layout_toRightOf="@id/textViewEmailLabel"
        android:text="Email:"
        android:textSize="18sp" />
    
     <TextView
        android:id="@+id/textViewGenderLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/textViewEmailLabel"
        android:layout_marginTop="15dp"
        android:text="Gender:"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/textViewGenderValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textViewGenderLabel"
        android:layout_alignLeft="@+id/textViewNameValue"
        android:text="Gender:"
        android:textSize="18sp" />
    
     <TextView
        android:id="@+id/textViewBirthdayLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/textViewGenderLabel"
        android:layout_marginTop="15dp"
        android:text="Birthday:"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/textViewBirthdayValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textViewBirthdayLabel"
        android:layout_alignBottom="@+id/textViewBirthdayLabel"
        android:layout_toRightOf="@+id/textViewBirthdayLabel"
        android:text="Birthday:"
        android:textSize="18sp" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_toRightOf="@+id/textViewTitle"/>
   
</RelativeLayout>

7)AndroidManifest.xml


<manifest android:versioncode="1" android:versionname="1.0" package="com.manish.google.profile" xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-sdk android:minsdkversion="8" android:targetsdkversion="16">

    <uses-permission android:name="android.permission.INTERNET">
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">
    <uses-permission android:name="android.permission.GET_ACCOUNTS">
    <uses-permission android:name="android.permission.NETWORK">
    <uses-permission android:name="android.permission.USE_CREDENTIALS">

    <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme">
        <activity android:label="@string/app_name" android:name="com.manish.google.profile.SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN">

                <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
        </activity>
        <activity android:name="com.manish.google.profile.HomeActivity">
    </activity></application>

</uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-sdk></manifest>

Download Zip Code


Please post your feedback :)
Thanks!