Monthly Archives: November 2012

How to create Swiping Windows in Android from Android 2.1 onwards?

Have you seen the Google Play application in your Android phone. Wondered about how they implemented swiping windows in it.
Don’t Worry, Here is an example which implements it.

Swipe Fragments in Android

Swipe Fragments in Android

Swipe Fragments in Android

Here we will create three pages which can be swiped to access it.

These are the three layouts for the three sections.

section1.xml


    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Layout 1" />

    </LinearLayout>

section2.xml


    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Layout 2" />

    </LinearLayout>

section3.xml


    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Layout 3" />

    </LinearLayout>

Now the java for these layouts. These are also similar , only change is the layout.

Page1.java

package com.example.swipewindows;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Page1 extends Fragment {
	Context c;

        public Page1(){
		
	}
	public Page1(Context c) {
		this.c = c;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.section1, null);
		return       v;
	}
}

Page2.java

package com.example.swipewindows;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Page2 extends Fragment {
	Context c;

        public Page2(){
		
	}
	public Page2(Context c) {
		this.c = c;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.section2, null);

		return v;
	}
}

Page3.java

package com.example.swipewindows;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Page3 extends Fragment {
	Context c;

        public Page3(){
		
	}
	public Page3(Context c) {
		this.c = c;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.section3, null);

		return v;
	}
}

Now the MainActivity.java that uses these sections to join together.

package com.example.swipewindows;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity {

	/**
	 * The android.support.v4.view.PagerAdapter that will provide fragments for
	 * each of the sections. We use a
	 * android.support.v4.app.FragmentPagerAdapter derivative, which will keep
	 * every loaded fragment in memory. If this becomes too memory intensive, it
	 * may be best to switch to a
	 * android.support.v4.app.FragmentStatePagerAdapter.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The ViewPager that will host the section contents.
	 */
	ViewPager mViewPager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_act);
		// Create the adapter that will return a fragment for each of the three
		// primary sections
		// of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(this,
				getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

	}

	/**
	 * A FragmentPagerAdapter that returns a fragment corresponding to one of
	 * the primary sections of the app.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		Context c;

		public SectionsPagerAdapter(Context c, FragmentManager fm) {
			super(fm);
			this.c = c;
		}

		@Override
		public Fragment getItem(int i) {
			Fragment fragment = null;
			if (i == 0) {
				fragment = new Page1(c);
			}
			if (i == 1) {
				fragment = new Page2(c);
			}
			if (i == 2) {
				fragment = new Page3(c);
			}
			return fragment; 
		}

		@Override
		public int getCount() {
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			switch (position) {
			case 0:
				return getString(R.string.title_section1).toUpperCase();
			case 1:
				return getString(R.string.title_section2).toUpperCase();
			case 2:
				return getString(R.string.title_section3).toUpperCase();
			}
			return null;
		}
	}

}

Now the Strings.xml that contains the section titles.

<resources>

    <string name="app_name">SwipeWindows</string>
    <string name="title_section3">Section 3</string>
    <string name="title_section2">Section 2</string>
    <string name="title_section1">       Section 1      </string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">     Settings   </string>
    <string name="title_activity_main">SwipeActivity</string>

</resources>

Download the complete source from here.

How to load a spinner with values from SQlite Database in android?

Here is a simple example showing how to load a database values in a spinner in android.

Spinner from SQLite

OK we will start.

This is the layout for the spinner row.
spinner_row.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation     =      "vertical"
    android:id="@+id/tv"
    android:layout_margin="10dp">   
</TextView>

This is the layout for the interface.

activity_main.xml

<LinearLayout 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:orientation="vertical" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textStyle="bold"
        android:text="Load DB values into Spinner"
         >
    </TextView>

    <Spinner
        android:id="@+id/spinner1"
        android:layout_below="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

</LinearLayout>

Now this is the MainActivity.java file that uses the spinner and the database.

package com.coderzheaven.loadspinnerfromdb;

import   java  .util  .ArrayList;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {

	SQLiteDatabase mydb;
	private   static String DBNAME = "PERSONS.db";
	private static String TABLE = "MY_TABLE";

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

		createTable();
		insertIntoTable();

		ArrayList<String> my_array = new ArrayList<String>();
		my_array = getTableValues();

		Spinner My_spinner = (Spinner) findViewById(R.id.spinner1);
		ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner_row,
				my_array);
		My_spinner.setAdapter(my_Adapter);
	}

	// CREATE TABLE IF NOT EXISTS
	public void createTable() {
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			mydb.execSQL("CREATE TABLE IF  NOT EXISTS " + TABLE
					+ " (ID INTEGER PRIMARY KEY, NAME TEXT, PLACE TEXT);");
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error in creating table",
					Toast.LENGTH_LONG);
		}
	}

	// THIS FUNCTION INSERTS DATA TO THE DATABASE
	public void insertIntoTable() {
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('CODERZHEAVEN','GREAT INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('ANTHONY','USA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('SHUING','JAPAN')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('JAMES','INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('SOORYA','INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('MALIK','INDIA')");
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(),
					"Error in inserting into table", Toast.LENGTH_LONG);
		}
	}

	// THIS FUNCTION SHOWS DATA FROM THE DATABASE
	public ArrayList<String> getTableValues() {

		ArrayList<String> my_array = new ArrayList<String>();
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor allrows = mydb.rawQuery("SELECT * FROM " + TABLE, null);
			System.out.println("COUNT : " + allrows.getCount());

			if (allrows.moveToFirst()) {
				do {

					String ID = allrows.getString(0);
					String NAME = allrows.getString(1);
					String PLACE = allrows.getString(2);
					my_array.add(NAME);

				} while (allrows.moveToNext());
			}
			allrows.close();
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error encountered.",
					Toast.LENGTH_LONG);
		}
		return my_array;
	}

}

Join the Forum discussion on this post

Note : Please remove the “span” tags from the post when you copy it.

Download the complete source code for this example from here.

How to Get Contact Image in Android.

This simple example gets the image from contacts in android.

private void getContactsDetails() {

		Cursor phones = getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
				null, null);
		while (phones.moveToNext()) {
			String Name = phones
					.getString(phones
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
			String Number = phones
					.getString(phones
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

			String image_uri = phones
					.getString(phones
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));

			System.out.println("Contact1 : " + Name + ", Number " + Number
					+ ", image_uri " + image_uri);
 
			
			if (image_uri != null) {
			     image.setImageURI(Uri.parse(image_uri));
		        }
			

		}

Please leave your valuable comments.

How to pass an Object from One Activity to another in Android.

Hello all

This is a simple post that shows How to pass an Object from One Activity to another in Android.

I am going to pass the following object from One Activity to another.

MyObject{
String name;
String website;
}

This is the class that defines the Object.

package com.coderzheaven.passarraylist;

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

public class MyObject implements Parcelable{

	String name,website;
	
	public MyObject(){
		
	}
	
	private MyObject(Parcel in){
              this.name = in.readString();
              this.website = in.readString();
        }
	
	public String getWebsite() {
		return website;
	}

	public void setWebsite(String website) {
		this.website = website;
	}

	public String getName() {
		return name;
	}

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

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

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeString(this.name);
		dest.writeString(this.website);
	}
	
	public static final MyObject.Creator<MyObject> CREATOR = new MyObject.Creator<MyObject>() {
        public MyObject createFromParcel(Parcel in) {
            return new MyObject(in);
        }

        public MyObject[] newArray(int size) {
            return new MyObject[size];
        }
    };  
}

This is the first activity that sends the object to second activity.

package com.coderzheaven.passarraylist;

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

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        this.setTitle("Main Activity");
        
        final MyObject myobj = new MyObject();
        myobj.setName("Coderz");
        myobj.setWebsite("CoderzHeaven.com");
        
        TextView name = (TextView)findViewById(R.id.name);
        name.setText("Name : " + myobj.getName());
        
        TextView website = (TextView)findViewById(R.id.website);
        website.setText("Website : " + myobj.getWebsite());
        
        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, Second.class);
				intent.putExtra("myobject", myobj);
				startActivity(intent);				
			}
		});
        
    }
}

This is the second Activity.

package com.coderzheaven.passarraylist;

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

public class Second extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);
        this.setTitle("Second Activity");
        
        Bundle b = getIntent().getExtras();
        
        if(b!=null){
        	MyObject myobj = (MyObject)getIntent().getExtras().getParcelable("myobject");
        	
        	 TextView name = (TextView)findViewById(R.id.name);
             name.setText("Name : " + myobj.getName());
             
             TextView website = (TextView)findViewById(R.id.website);
             website.setText("Website : " + myobj.getWebsite());
        }
    }
}

activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/website"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:layout_margin="5dp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/website"
        android:text="Pass Object to Next Activity" />

</RelativeLayout>

second_activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/website"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:layout_margin="5dp"
        android:textStyle="bold" />

</RelativeLayout>

PassObject

PassObject

You can download the tutorial PDF from here.
PLease leave your comments.