Wednesday, 1 January 2014

Android pass Object from one activity to another

Passing Java Objects in Android is made easy by implementing the Parcelable interface. The With the help of the parcelable interface your can write your object to a parcel or read from a parcel, that way you can easily pass it around when calling the activity using bundles. In this example we have a ArrayList of Country objects that we use to display a ListView, so when the user taps on a given row in the List we pass the complete object to the new activity where the user can update the information and send the object back to the ListView for display. Most important thing is, if you look at the source for the Country.java, that you must maintain the same sequence as in the method writeToParcel as when reading them back in the createFromParcel routine.







Android pass Object from one activity to another Android pass Object to new activity Android return object to the calling activity
Layout Resource for the Main Activity - 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"
    tools:context=".MainActivity"
    android:padding="10dp">

    <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="How to pass object from one activity to another?"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:paddingBottom="20dp"/>
     
    <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/textView1" />
    
</RelativeLayout>

Layout Resource for the ListView Row - row_data.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=".MainActivity" >

    <TextView
        android:id="@+id/code"
        android:layout_width="50sp"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Code"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@+id/code"
        android:text="Name: "
        android:textAppearance="?android:attr/textAppearanceMedium" />
    
</RelativeLayout>

Layout Resource for the Object Edit Activity - country_edit.xml


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

    <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="Country Code"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/code"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView2"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@+id/textView1"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="26dp"
        android:layout_toLeftOf="@+id/code"
        android:text="Name"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView2"
        android:layout_alignLeft="@+id/code"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="15dp"
        android:layout_toLeftOf="@+id/code"
        android:text="Continent"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/continent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/name"
        android:layout_below="@+id/name"
        android:ems="10" />
     
    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="15dp"
        android:layout_toLeftOf="@+id/code"
        android:text="Region"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/region"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/name"
        android:layout_below="@+id/continent"
        android:ems="10" />
     
    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView4"
        android:layout_marginTop="15dp"
        android:layout_toLeftOf="@+id/code"
        android:text="Popuation"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/population"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView5"
        android:layout_alignLeft="@+id/region"
        android:ems="10"
        android:inputType="number" />

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/population"
        android:layout_below="@+id/population"
        android:text="Save" />

    <Button
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/population"
        android:layout_below="@+id/population"
        android:text="Cancel" />
     
</RelativeLayout>

Country Object source implementing Parcelable interface - Country.java

package com.as400samplecode;

import android.os.Parcel;
import android.os.Parcelable;

public class Country implements Parcelable {
  
 String code = "";
 String name = "";
 String continent = "";
 String region = "";
 int population = 0;
 int listPosition = 0;
  
 public Country(String code, String name, String continent, String region, int population) {
  super();
  this.code = code;
  this.name = name;
  this.continent = continent;
  this.region = region;
  this.population = population;
 }
  
 public String getCode() {
  return code;
 }
 public void setCode(String code) {
  this.code = code;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getContinent() {
  return continent;
 }
 public void setContinent(String continent) {
  this.continent = continent;
 }
 public String getRegion() {
  return region;
 }
 public void setRegion(String region) {
  this.region = region;
 }
 public int getPopulation() {
  return population;
 }
 public void setPopulation(int population) {
  this.population = population;
 }
  

 public int getListPosition() {
  return listPosition;
 }

 public void setListPosition(int listPosition) {
  this.listPosition = listPosition;
 }

 @Override
 public int describeContents() {
  return 0;
 }

 @Override
 public void writeToParcel(Parcel dest, int flags) {
   
  dest.writeString(this.code);
  dest.writeString(this.name);
  dest.writeString(this.region);
  dest.writeString(this.continent);
  dest.writeInt(this.population);
  dest.writeInt(this.listPosition);
  
 }
  
 public static final Parcelable.Creator<Country> CREATOR
 = new Parcelable.Creator<Country>() {
  public Country createFromParcel(Parcel in) {
   return new Country(in);
  }

  public Country[] newArray(int size) {
   return new Country[size];
  }
 };
  
 private Country(Parcel in) {
  this.code = in.readString();
  this.name = in.readString();
  this.region = in.readString();
  this.continent = in.readString();
  this.population = in.readInt();
  this.listPosition = in.readInt();
    }
  
}

Main Activity displaying country in ListView - MainActivity.java
package com.as400samplecode;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

 private MyCustomAdapter dataAdapter = null;
 private View currentView = null;
  
 private static final int COUNTRY_EDIT = 1;

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

  //Generate list View from ArrayList
  displayListView();

 }

 private void displayListView() {

  //Array list of countries
  ArrayList<Country> countryList = new ArrayList<Country>();
  Country country = new Country("AFG","Afghanistan","Asia",
    "Southern and Central Asia", 101010);
  countryList.add(country);
  country = new Country("ALB","Albania","Europe","Southern Europe", 202020);
  countryList.add(country);
  country = new Country("DZA","Algeria","Africa","Northern Africa", 303030);
  countryList.add(country);
  country = new Country("ASM","American Samoa","Oceania","Polynesia", 404040);
  countryList.add(country);
  country = new Country("AND","Andorra","Europe","Southern Europe", 505050);
  countryList.add(country);
  country = new Country("AGO","Angola","Africa","Central Africa", 606060);
  countryList.add(country);
  country = new Country("AIA","Anguilla","North America","Caribbean", 707070);
  countryList.add(country);

  //create an ArrayAdaptar from the String Array
  dataAdapter = new MyCustomAdapter(this,
    R.layout.row_data, countryList);
  ListView listView = (ListView) findViewById(R.id.listView1);
  // Assign adapter to ListView
  listView.setAdapter(dataAdapter);

  listView.setOnItemClickListener(new OnItemClickListener() {
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {

    currentView = view;
     
    //get reference to the country Object
    Country country = (Country) view.getTag();
    Toast.makeText(getApplicationContext(),
      country.getCode(), Toast.LENGTH_SHORT).show();

    Intent countryEdit = new Intent(MainActivity.this,CountryEdit.class);
    Bundle b = new Bundle();
    //pass the country object as a parcel
    b.putParcelable("country", country);
    countryEdit.putExtras(b);
    startActivityForResult(countryEdit, COUNTRY_EDIT);

   }
  });

 }
  
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data){

  switch(requestCode) {
   
  case COUNTRY_EDIT:
   if (resultCode == RESULT_OK) {

    //read the bundle and get the country object
    Bundle bundle = data.getExtras();
    Country country = bundle.getParcelable("country");
     
    //update the country object in the ArrayAdapter
    int listPosition = country.getListPosition();
    dataAdapter.setCountry(country, listPosition);
     
    //update the country name in the ListView
    currentView.setTag(country);
    TextView name = (TextView) currentView.findViewById(R.id.name);
    name.setText(country.getName());
    
   }
   break;

  }

 }   

 private class MyCustomAdapter extends ArrayAdapter<Country> {

  private ArrayList<Country> countryList;

  public MyCustomAdapter(Context context, int textViewResourceId,
    ArrayList<Country> countryList) {

   super(context, textViewResourceId, countryList);
   this.countryList = new ArrayList<Country>();
   this.countryList.addAll(countryList);
  }
   
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {

   TextView code = null;
   TextView name = null;

   if (convertView == null) {
    LayoutInflater vi = (LayoutInflater)getSystemService(
      Context.LAYOUT_INFLATER_SERVICE);
    convertView = vi.inflate(R.layout.row_data, null);

    code  = (TextView) convertView.findViewById(R.id.code);
    name = (TextView) convertView.findViewById(R.id.name);
   } 

   Country country = countryList.get(position);
   country.setListPosition(position);
   code.setText(country.getCode());
   name.setText(country.getName());
   convertView.setTag(country);

   return convertView;
  }
   
  public void setCountry(Country country, int position){
   this.countryList.set(position, country);
  }

 }


 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

}

Activity editing country information - CountryEdit.java
package com.as400samplecode;

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


public class CountryEdit extends Activity implements OnClickListener{

 private Country country;
 private TextView code;
 private EditText name, region, continent, population;
  
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.country_edit);
   
  Bundle bundle = this.getIntent().getExtras();
  country = bundle.getParcelable("country");

  Button save = (Button) findViewById(R.id.save);
  Button cancel = (Button) findViewById(R.id.cancel);
  save.setOnClickListener(this);
  cancel.setOnClickListener(this);
   
  code = (TextView) findViewById(R.id.code);
  name = (EditText) findViewById(R.id.name);
  region = (EditText) findViewById(R.id.region);
  continent = (EditText) findViewById(R.id.continent);
  population = (EditText) findViewById(R.id.population);
   
  code.setText(country.getCode());
  name.setText(country.getName());
  region.setText(country.getRegion());
  continent.setText(country.getContinent());
  population.setText(String.valueOf(country.getPopulation()));
   

 }


 public void onClick(View v) {

  Intent intent = new Intent();
   
  switch (v.getId()) {
  case R.id.save:
    
   country.setName(name.getText().toString());
   country.setRegion(region.getText().toString());
   country.setContinent(continent.getText().toString());
   country.setPopulation(Integer.parseInt(population.getText().toString()));
    
   Bundle b = new Bundle();
   b.putParcelable("country", country);
   intent.putExtras(b);
            setResult(RESULT_OK,intent); 
   finish();
   break;

  case R.id.cancel:
   setResult(RESULT_CANCELED,intent); 
   finish();
   break;

  }
   
 }
  


}

Tuesday, 31 December 2013

Android ADB shell Command Device interaction

ADB Stands for Android Debug Bridge , ADB is a command line tool which lets you to communicate with emulator or any android device which is connected to your computer . 

ADB command line tool utility is included in android SDK , so firstly you must install android SDK in your computer to work with ADB Command .

After Installing SDK ,for accessing ADB Command through command line you need to make android sdk tools available to systems environment variable 

Lets See some of ADB Commands

1. The adb devices command


The adb devices command on execution displays the number of  Android devices connected to your computer with name and id , this cmd is mainly used to make ensure the communication between your computer and android devices

Command
        adb devices



2. adb shell input text


The adb shell input text command is used for sending text from computer to android device , this command takes text as a parameter to it and passes it on android device which is in connected  

Note : Have focus on edittext ui component ,before executing this cmd , because the edittext ui component receives the text send by this command.

Command
            adb shell input text "yout_text_goes_here"

Here is an sample scenario of inputing text into edittext component

 adb shell input text "http://rudrakrishna.blogspot.in" 



3. adb shell input swipe


The adb shell input swipe command is used for swiping on to android device , this command takes four parameter which are grouped into two forms ,specifes start and end co-ordinates. 

         swipe start point co-ordinates  :  x1  y1
         swipe End Point  co-ordinates :  x2  y2 

Command 
             adb shell input swipe x1 y1 x2 y2

Here is an useful scenario of swipe command for opening and closing notification


Note : This command is tested with HTC Desire X Device , the co-ordinates may vary from device to device , make ensure you use co-ordinates points according to the one

 > Opening Notification

     adb shell input swipe 10 10 10 1000 




> Closing Notification

     adb shell input swipe 10 1000 10 10 


Monday, 30 December 2013

Android JSON Parsing Tutorial

In this tutorial we are going to learn how to parse JSON in android.

JSON is very light weight, structured, easy to parse and much human readable. JSON is best alternative to XML when your android app needs to interchange data with your server


The Sample JSON

Following is the sample JSON that we are going to parse in this tutorial. This is very simple JSON which gives us list of contacts where each node contains contact information like name, email, address, gender and phone numbers.

{
    "contacts": [
        {
                "id": "c200",
                "name": "Ravi Tamada",
                "email": "ravi@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c201",
                "name": "Johnny Depp",
                "email": "johnny_depp@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        .
        .
        .
        .
  ]
}

The difference between [ and { - (Square brackets and Curly brackets)

In general all the JSON nodes will start with a square bracket or with a curly bracket. The difference between [ and { is, the square bracket ([) represents starting of an JSONArray node whereas curly bracket ({) represents JSONObject. So while accessing these nodes we need to call appropriate method to access the data.
If your JSON node starts with [, then we should use getJSONArray() method. Same as if the node starts with {, then we should use getJSONObject() method.