Wednesday, April 24, 2013

Dynamic radio button demo in Android | Radio Group example in android in Java class

This is a simple tutorial for dynamic Radio button in Android. Copy paste below code and enjoy..



1)MainActivity.java
package com.manish.dynamicspinner;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class MainActivity extends Activity {

 String countryName[] = { "India", "Pakistan", "China", "Nepal",
   "Bangladesh" };

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

  LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
  for (int k = 1; k <= 20; k++) {
   //create text button
   TextView title = new TextView(this);
   title.setText("Question Number:" + k);
   title.setTextColor(Color.BLUE);
   mLinearLayout.addView(title);
   // create radio button
   final RadioButton[] rb = new RadioButton[5];
   RadioGroup rg = new RadioGroup(this);
   rg.setOrientation(RadioGroup.VERTICAL);
   for (int i = 0; i < 5; i++) {
    rb[i] = new RadioButton(this);
    rg.addView(rb[i]);
    rb[i].setText(countryName[i]);

   }
   mLinearLayout.addView(rg);
  }
 }
}
2)activity_main.xml


    
    

Tuesday, April 23, 2013

Google Cloud Messaging example in Android | C2DM in android | GCM in Android | Push notification demo with php back-end | Messaging in Android

Hello Friends,
Today I am going to share very Important code for GCM(Google Cloud Messaging) for Android. I worked with my php developer(Ankit Garg) for back end and it is working Okay for me.
My article have 3 category-

1)Creating a Google API Project
2)PHP Back-end
3)Android Front-end



                                                         Part-A  Google API Project

1)Open Google API console from here
2)If you have not created any project create new project for your application-
3)See your browser URL and note your project ID from above some thing like that-1080127563513
https://code.google.com/apis/console/#project:1080127563513
4)In the main Google APIs Console page, select Services.
5)Turn the Google Cloud Messaging toggle to ON.
6)In the Terms of Service page, accept the terms.
7)get API Key from main Google APIs Console page, select API Access. You will see a screen that resembles the following and click on Create new Server Key:


8)Now from below window choose create button:

9)From below window note your project id and api key:


Part-B PHP Back-end Side



Just copy below file and put into your  php server inside ws folder-

1)GCM.php
<?php
$regID=$_GET['regID'];
$registatoin_ids=array($regID);
$msg=array("message"=>'HI Manish');
$url='https://android.googleapis.com/gcm/send';
$fields=array
 (
  'registration_ids'=>$registatoin_ids,
  'data'=>$msg
 );
$headers=array
 (
  'Authorization: key=AIzaSyA46UE7bBWXCpHSD5sbNxbRwI1MAKVI-jg',
  'Content-Type: application/json'
 );
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fields));
$result=curl_exec($ch);
curl_close($ch);
echo $result;
?>

Part-C Android side
1)MainActivity.java
package com.manish.gcm.push;

import static com.manish.gcm.push.CommonUtilities.SENDER_ID;

import java.io.BufferedReader;
import java.io.InputStreamReader;

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.HttpParams;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.android.gcm.GCMRegistrar;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class MainActivity extends Activity {

 private String TAG = "** GCMPushDEMOAndroid**";
 private TextView mDisplay;
 String regId = "";

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  checkNotNull(SENDER_ID, "SENDER_ID");
  GCMRegistrar.checkDevice(this);
  GCMRegistrar.checkManifest(this);

  mDisplay = (TextView) findViewById(R.id.textView1);

  regId = GCMRegistrar.getRegistrationId(this);

  if (regId.equals("")) {
   GCMRegistrar.register(this, SENDER_ID);
  } else {
   Log.v(TAG, "Already registered");
  }
  /**
   * call asYnc Task
   */
  new sendIdOnOverServer().execute();
  mDisplay.setText("RegId=" + regId);
 }

 private void checkNotNull(Object reference, String name) {
  if (reference == null) {
   throw new NullPointerException(getString(R.string.error_config,
     name));
  }

 }

 @Override
 protected void onPause() {
  super.onPause();
  GCMRegistrar.unregister(this);
 }

 public class sendIdOnOverServer extends AsyncTask {

  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) {
   try {
    HttpResponse response = null;
    HttpParams httpParameters = new BasicHttpParams();
    HttpClient client = new DefaultHttpClient(httpParameters);
    String url = "http://10.0.0.30//parsing/GCM.php?" + "&regID="
      + regId;
    Log.i("Send URL:", url);
    HttpGet request = new HttpGet(url);

    response = client.execute(request);

    BufferedReader rd = new BufferedReader(new InputStreamReader(
      response.getEntity().getContent()));

    String webServiceInfo = "";
    while ((webServiceInfo = rd.readLine()) != null) {
     Log.d("****Status Log***", "Webservice: " + webServiceInfo);

    }
   } catch (Exception e) {
    e.printStackTrace();
   }
   return null;

  }

  @Override
  protected void onPostExecute(String result) {
   pd.dismiss();

  }

 }

}
2)GCMIntentService.java
package com.manish.gcm.push;

import static com.manish.gcm.push.CommonUtilities.SENDER_ID;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {

 public GCMIntentService() {
  super(SENDER_ID);
 }

 private static final String TAG = "===GCMIntentService===";

 @Override
 protected void onRegistered(Context arg0, String registrationId) {
  Log.i(TAG, "Device registered: regId = " + registrationId);
 }

 @Override
 protected void onUnregistered(Context arg0, String arg1) {
  Log.i(TAG, "unregistered = " + arg1);
 }

 @Override
 protected void onMessage(Context context, Intent intent) {
  Log.i(TAG, "new message= ");
  String message = intent.getExtras().getString("message");
  generateNotification(context, message);
 }

 @Override
 protected void onError(Context arg0, String errorId) {
  Log.i(TAG, "Received error: " + errorId);
 }

 @Override
 protected boolean onRecoverableError(Context context, String errorId) {
  return super.onRecoverableError(context, errorId);
 }

 /**
  * Issues a notification to inform the user that server has sent a message.
  */
 private static void generateNotification(Context context, String message) {
  int icon = R.drawable.ic_launcher;
  long when = System.currentTimeMillis();
  NotificationManager notificationManager = (NotificationManager) context
    .getSystemService(Context.NOTIFICATION_SERVICE);
  Notification notification = new Notification(icon, message, when);
  String title = context.getString(R.string.app_name);
  Intent notificationIntent = new Intent(context, MainActivity.class);
  notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
    | Intent.FLAG_ACTIVITY_SINGLE_TOP);
  PendingIntent intent = PendingIntent.getActivity(context, 0,
    notificationIntent, 0);
  notification.setLatestEventInfo(context, title, message, intent);
  notification.flags |= Notification.FLAG_AUTO_CANCEL;
  notificationManager.notify(0, notification);
 }
}

3)CommonUtilities .java
package com.manish.gcm.push;

public final class CommonUtilities {
//put here your sender Id
static final String SENDER_ID = "311451115764";

}

4)activity_main.xml


    


5)manifest.xml


    

    

    
    
    
    
    

    
        
            
                

                
            
        

        
            
                
                

                
            
        

        
    


6)Download Zip Code

Thanks,
Please write your comment and feedback below:

Sunday, April 14, 2013

SqLite Example in Android | Add Image from Gallery and Camera into SqLite Database | ADD Image in SqLite | Delete Image In SqLite

Hello Friends,
On many demands today I am writing a very Important post on Take Image from Camera/Gallery and save it into SqLite database and display it in a List-View. After that on select one image it will take you second detail page and from here you can delete this image from SqLite. Follow my blog step by step-
Screen Shot:





1)SQLiteDemoActivity.java

package com.manish.sqlite;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class SQLiteDemoActivity extends Activity {
Button addImage;
ArrayList<Contact> imageArry = new ArrayList<Contact>();
ContactImageAdapter imageAdapter;
private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;
ListView dataList;
byte[] imageName;
int imageId;
Bitmap theImage;
DataBaseHandler db;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dataList = (ListView) findViewById(R.id.list);
/**
* create DatabaseHandler object
*/
db = new DataBaseHandler(this);
/**
* Reading and getting all records from database
*/
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "ID:" + cn.getID() + " Name: " + cn.getName()
+ " ,Image: " + cn.getImage();

// Writing Contacts to log
Log.d("Result: ", log);
// add contacts data in arrayList
imageArry.add(cn);

}
/**
* Set Data base Item into listview
*/
imageAdapter = new ContactImageAdapter(this, R.layout.screen_list,
imageArry);
dataList.setAdapter(imageAdapter);
/**
* go to next activity for detail image
*/
dataList.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
imageName = imageArry.get(position).getImage();
imageId = imageArry.get(position).getID();

Log.d("Before Send:****", imageName + "-" + imageId);
// convert byte to bitmap
ByteArrayInputStream imageStream = new ByteArrayInputStream(
imageName);
theImage = BitmapFactory.decodeStream(imageStream);
Intent intent = new Intent(SQLiteDemoActivity.this,
DisplayImageActivity.class);
intent.putExtra("imagename", theImage);
intent.putExtra("imageid", imageId);
startActivity(intent);

}
});
/**
* open dialog for choose camera/gallery
*/

final String[] option = new String[] { "Take from Camera",
"Select from Gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Select Option");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.e("Selected Item", String.valueOf(which));
if (which == 0) {
callCamera();
}
if (which == 1) {
callGallery();
}

}
});
final AlertDialog dialog = builder.create();

addImage = (Button) findViewById(R.id.btnAdd);

addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});

}

/**
* On activity result
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;

switch (requestCode) {
case CAMERA_REQUEST:

Bundle extras = data.getExtras();

if (extras != null) {
Bitmap yourImage = extras.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Android", imageInByte));
Intent i = new Intent(SQLiteDemoActivity.this,
SQLiteDemoActivity.class);
startActivity(i);
finish();

}
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();

if (extras2 != null) {
Bitmap yourImage = extras2.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Android", imageInByte));
Intent i = new Intent(SQLiteDemoActivity.this,
SQLiteDemoActivity.class);
startActivity(i);
finish();
}

break;
}
}

/**
* open camera method
*/
public void callCamera() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 200);
cameraIntent.putExtra("outputY", 150);
startActivityForResult(cameraIntent, CAMERA_REQUEST);

}

/**
* open gallery method
*/

public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);

}

}


2)DataBaseHandler.java
package com.manish.sqlite;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "imagedb";

// Contacts table name
private static final String TABLE_CONTACTS = "contacts";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_IMAGE = "image";

public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

// Create tables again
onCreate(db);
}

/**
* All CRUD(Create, Read, Update, Delete) Operations
*/

public// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_NAME, contact._name); // Contact Name
values.put(KEY_IMAGE, contact._image); // Contact Phone

// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}

// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_IMAGE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getBlob(2));

// return contact
return contact;

}

// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT  * FROM contacts ORDER BY name";

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setImage(cursor.getBlob(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// close inserting data from database
db.close();
// return contact list
return contactList;

}

// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_IMAGE, contact.getImage());

// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });

}

// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}

// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();

// return count
return cursor.getCount();
}

}

3)ContactImageAdapter.java

package com.manish.sqlite;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ContactImageAdapter extends ArrayAdapter<Contact>{
Context context;
   int layoutResourceId;
  // BcardImage data[] = null;
   ArrayList<Contact> data=new ArrayList<Contact>();
   public ContactImageAdapter(Context context, int layoutResourceId, ArrayList<Contact> 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;
       ImageHolder holder = null;
   
       if(row == null)
       {
           LayoutInflater inflater = ((Activity)context).getLayoutInflater();
           row = inflater.inflate(layoutResourceId, parent, false);
       
           holder = new ImageHolder();
           holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
           holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
           row.setTag(holder);
       }
       else
       {
           holder = (ImageHolder)row.getTag();
       }
   
       Contact picture = data.get(position);
       holder.txtTitle.setText(picture._name);
       //convert byte to bitmap take from contact class
     
       byte[] outImage=picture._image;
       ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
       Bitmap theImage = BitmapFactory.decodeStream(imageStream);
       holder.imgIcon.setImageBitmap(theImage);
      return row;
   
   }

   static class ImageHolder
   {
       ImageView imgIcon;
       TextView txtTitle;
   }
}


4)Contact.java
package com.manish.sqlite;

public class Contact {

// private variables
int _id;
String _name;
byte[] _image;

// Empty constructor
public Contact() {

}

// constructor
public Contact(int keyId, String name, byte[] image) {
this._id = keyId;
this._name = name;
this._image = image;

}

public Contact(int keyId) {
this._id = keyId;

}

// getting ID
public int getID() {
return this._id;
}

// setting id
public void setID(int keyId) {
this._id = keyId;
}

// getting name
public String getName() {
return this._name;
}

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

// getting phone number
public byte[] getImage() {
return this._image;
}

// setting phone number
public void setImage(byte[] image) {
this._image = image;
}
}

5)DisplayImageActivity.java
package com.manish.sqlite;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
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;

public class DisplayImageActivity extends Activity {
Button btnDelete;
ImageView imageDetail;
int imageId;
Bitmap theImage;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
btnDelete = (Button) findViewById(R.id.btnDelete);
imageDetail = (ImageView) findViewById(R.id.imageView1);
/**
* getting intent data from search and previous screen
*/
Intent intnt = getIntent();
theImage = (Bitmap) intnt.getParcelableExtra("imagename");
imageId = intnt.getIntExtra("imageid", 20);
Log.d("Image ID:****", String.valueOf(imageId));
imageDetail.setImageBitmap(theImage);
btnDelete.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
/**
* create DatabaseHandler object
*/
DataBaseHandler db = new DataBaseHandler(
DisplayImageActivity.this);
/**
* Deleting records from database
*/
Log.d("Delete Image: ", "Deleting.....");
db.deleteContact(new Contact(imageId));
// /after deleting data go to main page
Intent i = new Intent(DisplayImageActivity.this,
SQLiteDemoActivity.class);
startActivity(i);
finish();
}
});

}
}

6)main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#000000"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="fill_parent"
        android:layout_height="60dp"
        android:text="Add Image" />

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

</LinearLayout>

7)screen_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/imgIcon"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:layout_weight="0.71"
        android:gravity="center_vertical" />
    
    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:textSize="14dp"
        android:text="@string/hello"
        android:textColor="#ffffff"
        android:layout_marginLeft="7dp" />
      
</LinearLayout>

8)display.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#000000"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnDelete"
        android:layout_width="fill_parent"
        android:layout_height="60dp"
        android:text="Delete Image" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/facebook" />

</LinearLayout>

9) DOWNLOAD ZIP CODE

Your comments and suggestion requested!
Thanks,

You can refer my other blog for database in android-
1)Simple SqLite Data base Demo with Log
2)Image In SqLite Database from Drawable

Happy Coding :)

Android Hub 4 You Team

Wednesday, April 10, 2013

Android Child Group Activity | Android TabActivity | Tab Host Activity Example in Android | Activity inside Activity in Android | Animated Activity in Android

Hello Friends,
 Today I am going to share very Important post for Child Group Activity, means activity open inside Tab Group. For this I use Animated Activity. This logic I picked from stackoverflow.com. Hope it will help some one.

Print Screen:






1)Create a new project, name TabGroupChildDemo.
2)Create an  TabHostActivity and extend it to TabActivity.
3)Create 3 other activity name-HomeActivity, AboutActivity, ContactActivity.
4)Create 3 group activity name-HomeGroupActivity, AboutGroupActivity, ContactGroupActivity.
5)Create an other Activity ChildActivity.java.
6)Create 4 layout for Home, About, Contact, Child Activity, name activity_home, activity_about, activity_contact, activity_child.
7)Create 3 other layout for display tabs- home_tab,about_tab,contact_tab.
8)Add activity and group activity in manifest.xml
9)7)Add images - home.png, about.png, contact.png,ic_tab_background in drawable folder, download below images-

 My Code:

1)TabHostActivity.java

package com.manish.tabdemo;

import android.app.TabActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import android.widget.TextView;



@SuppressWarnings("deprecation")
public class TabHostActivity extends TabActivity implements OnTabChangeListener
{
private static final String[] TABS = { "HomeGroupActivity", "AboutGroupActivity", "ContactGroupActivity" };
private static final String[] TAB_NAMES = { "Home", "About", "Contact"};
public static TabHost tabs ;
    public static TabWidget tabWidget ;    
protected Bitmap roundedImage;
    public boolean checkTabsListener = false;

    
    public void onCreate(Bundle icicle)
    {        
    super.onCreate(icicle);
        setContentView(R.layout.activity_tab_host);
      
        Bitmap roundedImage = BitmapFactory.decodeResource(getResources(),R.drawable.ic_tab_background);
        roundedImage = getRoundedCornerBitmap(roundedImage,3);
       
        tabs = getTabHost();
 
        tabWidget = tabs.getTabWidget();
                      
   tabs.setOnTabChangedListener(this);
        
   for (int i = 0; i < TABS.length; i++)
        {
        TabHost.TabSpec tab = tabs.newTabSpec(TABS[i]);
       
        //Asociating Components
        ComponentName oneActivity = new ComponentName("com.manish.tabdemo", "com.manish.tabdemo." + TABS[i]);
        Intent intent = new Intent().setComponent(oneActivity);          
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        tab.setContent(intent);        
        //Setting the Indicator
        MyTabIndicator myTab = new MyTabIndicator(this, TAB_NAMES[i],(i+1), roundedImage); 
        tab.setIndicator(myTab);
        tabs.addTab(tab);
        }
        
   checkTabsListener = true;
   
        for(int i=0;i<tabs.getTabWidget().getChildCount();i++)
        {
        tabs.getTabWidget().getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
        }
        
     
tabs.getTabWidget().getChildAt(0).setBackgroundResource(R.drawable.ic_tab_background);  

//Maintaining Clicks

// Home Tab Click

tabWidget.getChildAt(0).setOnClickListener(new OnClickListener()
        {
@Override
public void onClick(View v)
{  
if(HomeGroupActivity.HomeGroupStack != null && HomeGroupActivity.HomeGroupStack.mIdList.size()>1)
{  
HomeGroupActivity.HomeGroupStack.getLocalActivityManager().removeAllActivities();
HomeGroupActivity.HomeGroupStack.mIdList.clear();
HomeGroupActivity.HomeGroupStack.mIntents.clear();
HomeGroupActivity.HomeGroupStack.mAnimator.removeAllViews();
HomeGroupActivity.HomeGroupStack.startChildActivity("CareGroupActivity", new Intent(HomeGroupActivity.HomeGroupStack, HomeActivity.class));
finish();
}
 
tabWidget.setCurrentTab(0);
tabs.setCurrentTab(0);
tabs.getTabWidget().getChildAt(0).setBackgroundResource(R.drawable.ic_tab_background);  
}
        });


// About tab Click

tabWidget.getChildAt(1).setOnClickListener(new OnClickListener()
        {
public void onClick(View v)
{  
if(AboutGroupActivity.AboutGroupStack != null && AboutGroupActivity.AboutGroupStack.mIdList.size()>0)
{
AboutGroupActivity.AboutGroupStack.getLocalActivityManager().removeAllActivities();
AboutGroupActivity.AboutGroupStack.mIdList.clear();  
AboutGroupActivity.AboutGroupStack.mIntents.clear();
AboutGroupActivity.AboutGroupStack.mAnimator.removeAllViews();  
AboutGroupActivity.AboutGroupStack.startChildActivity("TrackingGroupActivity", new Intent(AboutGroupActivity.AboutGroupStack, AboutActivity.class));
}  

tabWidget.setCurrentTab(1);
tabs.setCurrentTab(1);
tabs.getTabWidget().getChildAt(1).setBackgroundResource(R.drawable.ic_tab_background);  
}
        });

// Contact tab click

tabWidget.getChildAt(2).setOnClickListener(new OnClickListener()
        {
public void onClick(View v)
{  
if(ContactGroupActivity.ContactGroupStack != null && ContactGroupActivity.ContactGroupStack.mIdList.size()>0)
{
 
ContactGroupActivity.ContactGroupStack.getLocalActivityManager().removeAllActivities();
ContactGroupActivity.ContactGroupStack.mIdList.clear();  
ContactGroupActivity.ContactGroupStack.mIntents.clear();
ContactGroupActivity.ContactGroupStack.mAnimator.removeAllViews();  
ContactGroupActivity.ContactGroupStack.startChildActivity("DashboardGroupActivity", new Intent(ContactGroupActivity.ContactGroupStack, ContactActivity.class));
}  

tabWidget.setCurrentTab(2);
tabs.setCurrentTab(2);
tabs.getTabWidget().getChildAt(2).setBackgroundResource(R.drawable.ic_tab_background);  
}
        });


    }

    
    public class MyTabIndicator extends LinearLayout 
    {
public MyTabIndicator(Context context, String label, int tabId, Bitmap bgImg)
{
super(context);
LinearLayout tab = null;
TextView tv;
this.setGravity(Gravity.CENTER);

if(tabId == 1)
{
tab = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.home_tab, null);
tv = (TextView)tab.findViewById(R.id.tab_label);
tv.setText(label);
}



else if(tabId == 2)
{
tab = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.about_tab, null);
tv = (TextView)tab.findViewById(R.id.tab_label);
tv.setText(label);
}
else if(tabId == 3)
{
tab = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.contact_tab, null);
tv = (TextView)tab.findViewById(R.id.tab_label);
tv.setText(label);
}

this.addView(tab, new LinearLayout.LayoutParams(320/4,55));
}
    }

    
    
public void onTabChanged(String tabId) 
{  
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(tabs.getApplicationWindowToken(), 0);
       
        for(int i=0; i<tabs.getTabWidget().getChildCount(); i++)
{                        
        if(tabId.equalsIgnoreCase(TABS[i]))
{
tabs.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.ic_tab_background);  
}
else
{
tabs.getTabWidget().getChildAt(i).setBackgroundColor((Color.TRANSPARENT));
}  
  }
}

public static Bitmap getRoundedCornerBitmap(Bitmap bitmap,float roundPxRadius)
{
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx =roundPxRadius;
     
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
     
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
     
        return output;
}

public void onResume()
{
super.onResume();


//ReConstructing TabViews
reDesignTabViews();
}

public void onPause()
{
super.onPause();
}




/**
* Method used to re constructing the Views at tab bar. This solves tabs disappearing issue.
*/
public void reDesignTabViews()
{
MyTabIndicator myIndicator;


//Construction of tab views....
for(int i=0 ; i< tabWidget.getChildCount() ; i++)
{
myIndicator = (MyTabIndicator) tabWidget.getChildAt(i);
myIndicator.removeAllViews();

switch (i) 
{

case 0:
myIndicator.addView((LinearLayout) LayoutInflater.from(getApplicationContext()).inflate(R.layout.home_tab, null));
break;
case 1:
myIndicator.addView((LinearLayout) LayoutInflater.from(getApplicationContext()).inflate(R.layout.about_tab, null));
break;
case 2:
myIndicator.addView((LinearLayout) LayoutInflater.from(getApplicationContext()).inflate(R.layout.contact_tab, null));
break;

}
}
}

}

2)HomeActivity.java

package com.manish.tabdemo;

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

import com.manish.util.AnimatedActivity;

public class HomeActivity extends Activity {
Button button1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

AnimatedActivity pActivity = (AnimatedActivity) HomeActivity.this
.getParent();
Intent intent = new Intent(HomeActivity.this,
ChildActivity.class);
pActivity.startChildActivity("home_screen", intent);
}
});
}

@Override
public void onBackPressed() {
System.out.println("***back*");
HomeActivity.super.onBackPressed();
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
System.out.println("****event****" + event + "****" + keyCode);
if (keyCode == KeyEvent.KEYCODE_BACK) {

finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}

3)HomeGroupActivity.java

package com.manish.tabdemo;

import android.content.Intent;
import android.os.Bundle;

import com.manish.util.AnimatedActivity;

public class HomeGroupActivity extends AnimatedActivity {
public static HomeGroupActivity HomeGroupStack;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
HomeGroupStack = HomeGroupActivity.this;

startChildActivity("HomeGroupActivity", new Intent(this,
HomeActivity.class));
}
}

4)AboutActivity.java

package com.manish.tabdemo;

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

public class AboutActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
}
}

5)AboutGroupActivity.java

package com.manish.tabdemo;

import android.content.Intent;
import android.os.Bundle;

import com.manish.util.AnimatedActivity;

public class AboutGroupActivity extends AnimatedActivity {
public static AboutGroupActivity AboutGroupStack;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AboutGroupStack = AboutGroupActivity.this;

startChildActivity("AboutGroupActivity", new Intent(this,
AboutActivity.class));
}
}

6)ContactActivity.java

package com.manish.tabdemo;

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

public class ContactActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
}
}

7)ContactGroupActivity.java

package com.manish.tabdemo;

import android.content.Intent;
import android.os.Bundle;

import com.manish.util.AnimatedActivity;

public class ContactGroupActivity extends AnimatedActivity {
public static ContactGroupActivity ContactGroupStack;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContactGroupStack = ContactGroupActivity.this;

startChildActivity("ContactGroupActivity", new Intent(this,
ContactActivity.class));
}
}

8)ChildActivity.java

package com.manish.tabdemo;

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

public class ChildActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_child);
}
}

9)activity_tab_host.xml

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1" />

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="-4dp"
            android:layout_weight="0" />
    </LinearLayout>

</TabHost>

10)activity_home.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#0099CC" >

    <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="Home Tab"
        android:textColor="#ffffff"
        android:textSize="35sp" />

    <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:text="Open Child" />

</RelativeLayout>

11)home_tab.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="1dip"
        android:layout_marginTop="2dip"
        android:background="@drawable/home" >
    </TextView>

    <TextView
        android:id="@+id/tab_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Home"
        android:textColor="#0099CC" />

</LinearLayout>

12)activity_about.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#808080" >

    <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="About Tab"
        android:textColor="#ffffff"
        android:textSize="35sp" />

</RelativeLayout>

13)about_tab.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="1dip"
        android:layout_marginTop="2dip"
        android:background="@drawable/about" >
    </TextView>

    <TextView
        android:id="@+id/tab_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="About"
        android:textColor="#0099CC" />

</LinearLayout>

14)activity_contact.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffdddd" >

    <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="Contact Tab"
        android:textColor="#000000"
        android:textSize="35sp" />

</RelativeLayout>

15)contact_tab.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="1dip"
        android:layout_marginTop="2dip"
        android:background="@drawable/contact" >
    </TextView>

    <TextView
        android:id="@+id/tab_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Contact"
        android:textColor="#0099CC" />

</LinearLayout>

16)activity_child.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:background="#0099CC"
    android:layout_height="fill_parent" >

    <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="Child Activity"
        android:textSize="35sp"
        android:textColor="#ffffff" />

</RelativeLayout>

17)manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.manish.tabdemo"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.manish.tabdemo.HomeActivity" />
        <activity android:name="com.manish.tabdemo.AboutActivity" />
        <activity android:name="com.manish.tabdemo.ContactActivity" />
        <activity android:name="com.manish.tabdemo.ChildActivity" />
        <activity android:name="com.manish.tabdemo.AboutGroupActivity" />
        <activity android:name="com.manish.tabdemo.ContactGroupActivity" />
        <activity android:name="com.manish.tabdemo.HomeGroupActivity" />
    </application>

</manifest>




18)DOWNLOAD ZIP CODE



Please leave your comment and suggestion below-

Thanks,

you can refer below post for simple tab host activity- http://www.androidhub4you.com/2013/04/android-tabactivity-tab-layout-demo-tab.html