20 Feb 2014

Passing object by Intent in android(Serializable,Parcelable)

In this post, I will show you an simple example of how to pass object by intent in Android application. Parcelable and Serialization are used for marshaling and unmarshaling Java objects.

Differences between Serialization and Parcelable:

1. In Parcelable, developers write custom code for marshaling and unmarshaling so it creates less garbage         objects in comparison to Serialization.
2. The performance of Parcelable over Serialization dramatically improves (around two times faster),                 because of this custom implementation.

Serialization is a marker interface, which implies the user cannot marshal the data according to their requirements. In Serialization, a marshaling operation is performed on a Java Virtual Machine (JVM) using the Java reflection API. This helps identify the Java objects member and behavior, but also ends up creating a lot of garbage objects. Due to this, the Serialization process is slow in comparison to Parcelable.

Step 1: main.xml for the layout

<?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="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center_horizontal"
        android:text="Serializable,Parcelable Example" />

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

        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Serializable" />

        <Button
            android:id="@+id/button2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:text="Parcelable" />
    </LinearLayout>

</LinearLayout>

Step 2: Create Person.java which implement serializable

import java.io.Serializable;  
public class Person implements Serializable 
{  
 private static final long serialVersionUID = -7060210544600464481L;   
 private String name;  
 private int age;  
 public String getName() {  
  return name;  
 }  
 public void setName(String name) {  
  this.name = name;  
 }  
 public int getAge() {  
  return age;  
 }  
 public void setAge(int age) {  
  this.age = age;  
 }
}

Step 3: Create Book.java which implement Parcelable

 import android.os.Parcel;  
 import android.os.Parcelable;  
 public class Book implements Parcelable {  
     private String bookName;  
     private String author;  
     private int publishTime;  

     public String getBookName() {  
  return bookName;  
     }  
     public void setBookName(String bookName) {  
  this.bookName = bookName;  
     }  
     public String getAuthor() {  
  return author;  
     }  
     public void setAuthor(String author) {  
  this.author = author;  
     }  
     public int getPublishTime() {  
  return publishTime;  
     }  
     public void setPublishTime(int publishTime) {  
  this.publishTime = publishTime;  
     }  

     public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() {  
  public Book createFromParcel(Parcel source) {  
      Book mBook = new Book();  
      mBook.bookName = source.readString();  
      mBook.author = source.readString();  
      mBook.publishTime = source.readInt();  
      return mBook;  
  }  
  public Book[] newArray(int size) {  
      return new Book[size];  
  }  
     };  

     public int describeContents() {  
  return 0;  
     }  
     public void writeToParcel(Parcel parcel, int flags) {  
  parcel.writeString(bookName);  
  parcel.writeString(author);  
  parcel.writeInt(publishTime);  
     }  
 }

Step 4: Create The MainActivity.java which is the main Activity class 

import hb.aa_serializableparcelable.bean.Book;
import hb.aa_serializableparcelable.bean.Person;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener 
{

    private Button sButton,pButton;  
    public  final static String SER_KEY = "ser";  
    public  final static String PAR_KEY = "par";
    
    public void onCreate(Bundle savedInstanceState) 
    {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);     
        setupViews();

    }  

    public void setupViews()
    {  
        sButton = (Button)findViewById(R.id.button1);  
        pButton = (Button)findViewById(R.id.button2);  
        sButton.setOnClickListener(this);  
        pButton.setOnClickListener(this);  
    }  

    public void SerializeMethod()
    {  
        Person mPerson = new Person();  
        mPerson.setName("Leon");  
        mPerson.setAge(25);  
        Intent mIntent = new Intent(this,ObjectPassDemo1.class);  
        Bundle mBundle = new Bundle();  
        mBundle.putSerializable(SER_KEY,mPerson);  
        mIntent.putExtras(mBundle);  

        startActivity(mIntent);  
    }  

    public void PacelableMethod()
    {  
        Book mBook = new Book();  
        mBook.setBookName("Android Developer Guide");  
        mBook.setAuthor("Leon");  
        mBook.setPublishTime(2014);  
        Intent mIntent = new Intent(this,ObjectPassDemo2.class);  
        Bundle mBundle = new Bundle();  
        mBundle.putParcelable(PAR_KEY, mBook);  
        mIntent.putExtras(mBundle);  

        startActivity(mIntent);  
    }  

    public void onClick(View v) 
    {  
        if(v == sButton)
        {  
            SerializeMethod();  
        }
        else
        {  
            PacelableMethod();  
        }  
    }  
}

Step 5: create 2 more activity classes: ObjectPassDemo1.java use for display person ObjectPassDemo2.java use for display book

ObjectPassDemo2.java
import hb.aa_serializableparcelable.bean.Person;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ObjectPassDemo1 extends Activity 
{  
 @Override  
 public void onCreate(Bundle savedInstanceState) 
 {  
  super.onCreate(savedInstanceState);  

  TextView mTextView = new TextView(this);  
  Person mPerson = (Person)getIntent().getSerializableExtra(MainActivity.SER_KEY);  
  mTextView.setText("You name is: " + mPerson.getName() + "/n"+ "You age is: " + mPerson.getAge());  

  setContentView(mTextView);  
 }  
}

ObjectPassDemo2.java
import hb.aa_serializableparcelable.bean.Book;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ObjectPassDemo2 extends Activity 
{  

 public void onCreate(Bundle savedInstanceState) 
 {  
  super.onCreate(savedInstanceState);  
  TextView mTextView = new TextView(this);  
  Book mBook = (Book)getIntent().getParcelableExtra(MainActivity.PAR_KEY);  
  mTextView.setText("Book name is: " + mBook.getBookName()+"/n"+ 
    "Author is: " + mBook.getAuthor() + "/n" +  
    "PublishTime is: " + mBook.getPublishTime());  
  setContentView(mTextView);  
 }  
}


pass arraylist between activities android

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

28 Jan 2014

Rate Us : Rating application feature in Android

Hello friends,

Today i am going post rate your Android application.it allows you to prompt a user to rate your Android application. Ratings are determined by Google Play users. Your application’s rating is one of the most important factors influencing its ranking in the various lists and search results in Google Play. We will create an activity, and after the application launches twice the user will be prompted to rate the application. So lets start…


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

public class MainActivity extends Activity
{
 @Override
 protected void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  // Launch RateApp.java class
  RateApp.app_launched(this);

  // Your Codes...
 }
}

//Here is the Rate app class
RateApp.java

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class RateApp
{
 // Insert your Application Title
 private final static String TITLE = "My Application";

 // Insert your Application Package Name
 private final static String PACKAGE_NAME = "hb.rateapptutorial";

 // Day until the Rate Us Dialog Prompt(Default 2 Days)
 private final static int DAYS_UNTIL_PROMPT = 0;

 // Rate Us Dialog Prompt when user launch app second time
 private final static int LAUNCHES_UNTIL_PROMPT = 2;

 public static void app_launched(Context mContext)
 {
  SharedPreferences prefs = mContext.getSharedPreferences("rateapp", 0);
  if (prefs.getBoolean("dontshowagain", false))
  {
   return;
  }

  SharedPreferences.Editor editor = prefs.edit();

  // Increment launch counter
  long launch_count = prefs.getLong("launch_count", 0) + 1;
  editor.putLong("launch_count", launch_count);

  // Get date of first launch
  Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
  if (date_firstLaunch == 0)
  {
   date_firstLaunch = System.currentTimeMillis();
   editor.putLong("date_firstlaunch", date_firstLaunch);
  }

  // Wait at least n days before opening
  if (launch_count >= LAUNCHES_UNTIL_PROMPT)
  {
   if (System.currentTimeMillis() >= date_firstLaunch
     + (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000))
   {
    showRateDialog(mContext, editor);
   }
  }

  editor.commit();
 }

 public static void showRateDialog(final Context mContext,final SharedPreferences.Editor editor)
 {
  final Dialog dialog = new Dialog(mContext);
  // Set Dialog Title
  dialog.setTitle("Rate " + TITLE);

  LinearLayout ll = new LinearLayout(mContext);
  ll.setOrientation(LinearLayout.VERTICAL);

  TextView tv = new TextView(mContext);
  tv.setText("If you like " + TITLE + ", please give Rating");
  tv.setWidth(240);
  tv.setPadding(4, 0, 4, 10);
  ll.addView(tv);

  // First Button
  Button btnRate = new Button(mContext);
  btnRate.setText("Rate " + TITLE);
  btnRate.setOnClickListener(new OnClickListener()
  {
   public void onClick(View v)
   {
    mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri
      .parse("market://details?id=" + PACKAGE_NAME)));
    dialog.dismiss();
   }
  });
  ll.addView(btnRate);

  // Second Button
  Button btnLater = new Button(mContext);
  btnLater.setText("Remind me later");
  btnLater.setOnClickListener(new OnClickListener()
  {
   public void onClick(View v)
   {
    dialog.dismiss();
   }
  });
  ll.addView(btnLater);

  // Third Button Stop Bugging me
  Button btnNoRating = new Button(mContext);
  btnNoRating.setText("No rating");
  btnNoRating.setOnClickListener(new OnClickListener()
  {
   public void onClick(View v)
   {
    if (editor != null)
    {
     editor.putBoolean("dontshowagain", true);
     editor.commit();
    }
    dialog.dismiss();
   }
  });
  ll.addView(btnNoRating);

  dialog.setContentView(ll);

  // Show Dialog
  dialog.show();
 }
}

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)