TabLayout/TabHost Tutorial For Android (Reusing Layout)

Hi, hope you all are fine. My this tutorial is about using Tab Layout in Android.

 

Here its complete source code.

TabBarExample.java

In this class i take the reference of TabHost and pass it to setMyTabs Function to add Tabs at runtime.

public class TabBarExample extends TabActivity  {

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

        tabHost = (TabHost)findViewById(android.R.id.tabhost);
        AppTabs.setMyTabs(tabHost, this);
    }
}

AppTabs.java
First create the TabSpec objects, setting their ids, setting Display Text and Animation (for pressed and unpressed states), setting their contents then add add them into tabHost.

We can also implement OnTabChangedListener, and set backgrounds of tabs as required whose code is highlighted.

	public static void setMyTabs(TabHost tabHost, Context context){
        TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
        TabSpec secondTabSpec = tabHost.newTabSpec("tid1");

        firstTabSpec.setIndicator("Artists", context.getResources().getDrawable(R.anim.artists));
        secondTabSpec.setIndicator("Search", context.getResources().getDrawable(R.anim.search));

        firstTabSpec.setContent(new Intent(context, FirstTab.class));
        secondTabSpec.setContent(new Intent(context, SecondTab.class));

        tabHost.addTab(firstTabSpec);
        tabHost.addTab(secondTabSpec);

        tabHost.getTabWidget().setCurrentTab(1);
        tabHost.setOnTabChangedListener(MyOnTabChangeListener);

        // Setting BackGround
//      for(int i=0; i<tabHost.getTabWidget().getChildCount(); i++)
//      {
//      	tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.WHITE);
//      }
//
//      tabHost.getTabWidget().setCurrentTab(1);
//      tabHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.GRAY);

	}

	private static OnTabChangeListener MyOnTabChangeListener = new OnTabChangeListener(){
		@Override
		public void onTabChanged(String tabId) {
//			for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
//	        {
//	        	tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.WHITE);
//	        }
//
//			tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.GRAY);
		}
	};

}

Tab.xml

<TabHost android:layout_width="fill_parent"
	android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@android:id/tabhost">
	<LinearLayout android:id="@+id/LinearLayout01"
		android:orientation="vertical" android:layout_height="fill_parent"
		android:layout_width="fill_parent">
		<TabWidget android:id="@android:id/tabs"
			android:layout_height="wrap_content" android:layout_width="fill_parent"></TabWidget>
		<FrameLayout android:id="@android:id/tabcontent"
			android:layout_height="fill_parent" android:layout_width="fill_parent"></FrameLayout>
	</LinearLayout>
</TabHost>

FirstTab.java

public class FirstTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		TextView textView = new TextView(this);
		textView.setText("First Tab");
		setContentView(textView);
	}
}

Other Links

http://developer.android.com/resources/tutorials/views/hello-tabwidget.html

Posted in Android, Tutorials | Tagged , , , , | 7 Comments

Working with SQLite DB Tutorial

Creating SQLite DataBase using FireFox Pluggin “SQLite Manager”

First of all install the Firefox having version greater than 3.6.4.

Go to https://addons.mozilla.org/en-US/firefox/addon/5817/

Click on “Add to FireFox” botton and install the pluggin.

After installing go to “Tools->SQLite Manager” following window will open for you.

It is the UI interface for the SQLite DB manipulation.

Go to “Database->New Database”

Enter Database name.

Select Folder where you want to place your DB.

Now you can do what you want to do with your DB using SQLite Manager.

After creating DB structure you can copy the “dbname.sqlite ” database from your path and paste in the required project.

Posted in Android, Tutorials, Uncategorized | Tagged , | 3 Comments

DataBase-CRUD Tutorial for Android

Here is the DataBase CRUD Tutorial for Android.

First of all create the SQLite DB and paste in the assets folder.

See Blog for creation of SQLite DB http://mfarhan133.wordpress.com/2010/10/24/working-with-sqlite-db-tutorial/

Use DBAdapter Class for DB connectivity and CRUD manipulation.

Its functions details are commented in class itself.

You can download its complete source code from here.

Select

First of all on the start of application(Splash) call createDataBase() function to create and copy database from assets folder(Select in my case). After first time creation of DB used DB will be now on “/data/data/mypackagename/database/” path.

  public ArrayList getUsers(){

		DBAdapter dbAdapter=DBAdapter.getDBAdapterInstance(this);
		try {
			dbAdapter.createDataBase();
		} catch (IOException e) {
			Log.i("*** select ",e.getMessage());
		}
    	dbAdapter.openDataBase();
		String query="SELECT * FROM user;";
		ArrayList> stringList = dbAdapter.selectRecordsFromDBList(query, null);
		dbAdapter.close();

		ArrayList usersList = new ArrayList();
		for (int i = 0; i < stringList.size(); i++) {
			ArrayList list = stringList.get(i);
			UserBO user = new UserBO();
			try {
				user.id = Integer.parseInt(list.get(0));
				user.name = list.get(1);
				user.age = Long.parseLong(list.get(2));
			} catch (Exception e) {
				Log.i("***" + Select.class.toString(), e.getMessage());
			}
			usersList.add(user);
		}
		return usersList;
	}

Insert

DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(Insert.this);
dbAdapter.openDataBase();

ContentValues initialValues = new ContentValues();
initialValues.put("name", etName.getText().toString());
initialValues.put("age", etAge.getText().toString());
long n = dbAdapter.insertRecordsInDB("user", null, initialValues);
Toast.makeText(Insert.this, "new row inserted with id = " + n, Toast.LENGTH_SHORT).show();

Update

DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(Update.this);
dbAdapter.openDataBase();

ContentValues initialValues = new ContentValues();
initialValues.put("name", etName.getText().toString());
initialValues.put("age", etAge.getText().toString());
String id = etId.getText().toString();
String [] strArray = {""+id};
long n = dbAdapter.updateRecordsInDB("user", initialValues, "id=?", strArray);

Toast.makeText(Update.this, n+" rows updated", Toast.LENGTH_SHORT).show();

Delete

DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(Delete.this);
dbAdapter.openDataBase();

String id = etId.getText().toString();
String [] strArray = {""+id};
long n = dbAdapter.deleteRecordInDB("user", "id = ?", strArray);
Toast.makeText(Delete.this, n+" rows effected", Toast.LENGTH_SHORT).show();

DBAdapter.java

public class DBAdapter extends SQLiteOpenHelper {

	private static String DB_PATH = "";
	private static final String DB_NAME = "user.sqlite";
	private SQLiteDatabase myDataBase;
	private final Context myContext;

	private static DBAdapter mDBConnection;

	/**
	 * Constructor
	 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
	 * @param context
	 */
	private DBAdapter(Context context) {
		super(context, DB_NAME, null, 1);
		this.myContext = context;
		DB_PATH = "/data/data/"
				+ context.getApplicationContext().getPackageName()
				+ "/databases/";
		// The Android's default system path of your application database is
		// "/data/data/mypackagename/databases/"
	}

	/**
	 * getting Instance
	 * @param context
	 * @return DBAdapter
	 */
	public static synchronized DBAdapter getDBAdapterInstance(Context context) {
		if (mDBConnection == null) {
			mDBConnection = new DBAdapter(context);
		}
		return mDBConnection;
	}

	/**
	 * Creates an empty database on the system and rewrites it with your own database.
	 **/
	public void createDataBase() throws IOException {
		boolean dbExist = checkDataBase();
		if (dbExist) {
			// do nothing - database already exist
		} else {
			// By calling following method
			// 1) an empty database will be created into the default system path of your application
			// 2) than we overwrite that database with our database.
			this.getReadableDatabase();
			try {
				copyDataBase();
			} catch (IOException e) {
				throw new Error("Error copying database");
			}
		}
	}

	/**
	 * Check if the database already exist to avoid re-copying the file each time you open the application.
	 * @return true if it exists, false if it doesn't
	 */
	private boolean checkDataBase() {
		SQLiteDatabase checkDB = null;
		try {
			String myPath = DB_PATH + DB_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null,
					SQLiteDatabase.OPEN_READONLY);

		} catch (SQLiteException e) {
			// database does't exist yet.
		}
		if (checkDB != null) {
			checkDB.close();
		}
		return checkDB != null ? true : false;
	}

	/**
	 * Copies your database from your local assets-folder to the just created
	 * empty database in the system folder, from where it can be accessed and
	 * handled. This is done by transfering bytestream.
	 * */
	private void copyDataBase() throws IOException {
		    // Open your local db as the input stream
		InputStream myInput = myContext.getAssets().open(DB_NAME);
		    // Path to the just created empty db
		String outFileName = DB_PATH + DB_NAME;
		    // Open the empty db as the output stream
		OutputStream myOutput = new FileOutputStream(outFileName);
		    // transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}
		    // Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();
	}

	/**
	 * Open the database
	 * @throws SQLException
	 */
	public void openDataBase() throws SQLException {
		String myPath = DB_PATH + DB_NAME;
		myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
	}

	/**
	 * Close the database if exist
	 */
	@Override
	public synchronized void close() {
		if (myDataBase != null)
			myDataBase.close();
		super.close();
	}

	/**
	 * Call on creating data base for example for creating tables at run time
	 */
	@Override
	public void onCreate(SQLiteDatabase db) {
	}

	/**
	 * can used for drop tables then call onCreate(db) function to create tables again - upgrade
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}

	// ----------------------- CRUD Functions ------------------------------

	/**
	 * This function used to select the records from DB.
	 * @param tableName
	 * @param tableColumns
	 * @param whereClase
	 * @param whereArgs
	 * @param groupBy
	 * @param having
	 * @param orderBy
	 * @return A Cursor object, which is positioned before the first entry.
	 */
	public Cursor selectRecordsFromDB(String tableName, String[] tableColumns,
			String whereClase, String whereArgs[], String groupBy,
			String having, String orderBy) {
		return myDataBase.query(tableName, tableColumns, whereClase, whereArgs,
				groupBy, having, orderBy);
	}

	/**
	 * select records from db and return in list
	 * @param tableName
	 * @param tableColumns
	 * @param whereClase
	 * @param whereArgs
	 * @param groupBy
	 * @param having
	 * @param orderBy
	 * @return ArrayList>
	 */
	public ArrayList> selectRecordsFromDBList(String tableName, String[] tableColumns,
			String whereClase, String whereArgs[], String groupBy,
			String having, String orderBy) {

		ArrayList> retList = new ArrayList>();
	      ArrayList list = new ArrayList();
	      Cursor cursor = myDataBase.query(tableName, tableColumns, whereClase, whereArgs,
					groupBy, having, orderBy);
	      if (cursor.moveToFirst()) {
	         do {
	        	 list = new ArrayList();
	        	 for(int i=0; i 0;
	}

	/**
	 * This function used to update the Record in DB.
	 * @param tableName
	 * @param initialValues
	 * @param whereClause
	 * @param whereArgs
	 * @return 0 in case of failure otherwise return no of row(s) are updated
	 */
	public int updateRecordsInDB(String tableName,
			ContentValues initialValues, String whereClause, String whereArgs[]) {
		return myDataBase.update(tableName, initialValues, whereClause, whereArgs);
	}

	/**
	 * This function used to delete the Record in DB.
	 * @param tableName
	 * @param whereClause
	 * @param whereArgs
	 * @return 0 in case of failure otherwise return no of row(s) are deleted.
	 */
	public int deleteRecordInDB(String tableName, String whereClause,
			String[] whereArgs) {
		return myDataBase.delete(tableName, whereClause, whereArgs);
	}

	// --------------------- Select Raw Query Functions ---------------------

	/**
	 * apply raw Query
	 * @param query
	 * @param selectionArgs
	 * @return Cursor
	 */
	public Cursor selectRecordsFromDB(String query, String[] selectionArgs) {
		return myDataBase.rawQuery(query, selectionArgs);
	}

	/**
	 * apply raw query and return result in list
	 * @param query
	 * @param selectionArgs
	 * @return ArrayList>
	 */
	public ArrayList> selectRecordsFromDBList(String query, String[] selectionArgs) {
	      ArrayList> retList = new ArrayList>();
	      ArrayList list = new ArrayList();
	      Cursor cursor = myDataBase.rawQuery(query, selectionArgs);
	      if (cursor.moveToFirst()) {
	         do {
	        	 list = new ArrayList();
	        	 for(int i=0; i<cursor.getColumnCount(); i++){
	        		 list.add( cursor.getString(i) );
	        	 }
	        	 retList.add(list);
	         } while (cursor.moveToNext());
	      }
	      if (cursor != null && !cursor.isClosed()) {
	         cursor.close();
	      }
	      return retList;
	   }

}

Related Blog http://www.screaming-penguin.com/node/7742

Posted in Android, Tutorials | Tagged , , | 21 Comments

Manipulating Incoming & Outgoing Calls Tutorial For Android

This code simply implement PhoneStateListener. When call state changed onCallStateChanged function call and toast will appear on screen showing status. You can write your own code instead of toast for what you want to do.

You can download complete source code from here.

IncomingCallReciever.java

public class IncomingCallReciever extends BroadcastReceiver {

	private Context mContext;
	private Intent mIntent;

	@Override
	public void onReceive(Context context, Intent intent) {
		mContext = context;
		mIntent = intent;
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		int events = PhoneStateListener.LISTEN_CALL_STATE;
		tm.listen(phoneStateListener, events);
	}

	private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			String callState = "UNKNOWN";
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE:
				callState = "IDLE";
				break;
			case TelephonyManager.CALL_STATE_RINGING:
				// -- check international call or not.
				if (incomingNumber.startsWith("00")) {
					Toast.makeText(mContext,"International Call- " + incomingNumber,Toast.LENGTH_LONG).show();
					callState = "International - Ringing (" + incomingNumber+ ")";
				} else {
					Toast.makeText(mContext, "Local Call - " + incomingNumber, Toast.LENGTH_LONG).show();
					callState = "Local - Ringing (" + incomingNumber + ")";
				}
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				String dialingNumber = mIntent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
				if (dialingNumber.startsWith("00")) {
					Toast.makeText(mContext,"International - " + dialingNumber,Toast.LENGTH_LONG).show();
					callState = "International - Dialing (" + dialingNumber+ ")";
				} else {
					Toast.makeText(mContext, "Local Call - " + dialingNumber,Toast.LENGTH_LONG).show();
					callState = "Local - Dialing (" + dialingNumber + ")";
				}
				break;
			}
			Log.i(">>>Broadcast", "onCallStateChanged " + callState);
			super.onCallStateChanged(state, incomingNumber);
		}
	};

}

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.geniteam.broadcast" android:versionCode="1"
	android:versionName="1.0">
	<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
	<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
	<application android:icon="@drawable/icon" android:label="@string/app_name"
		android:debuggable="true">
		<receiver android:name=".IncomingCallReciever"
			android:enabled="true">
			<intent-filter>
				<action android:name="android.intent.action.PHONE_STATE"></action>
				<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
			</intent-filter>
		</receiver>
	</application>
	<uses-sdk android:minSdkVersion="4" />
</manifest>

Other Links:

http://www.krvarma.com/posts/android/detecting-incoming-and-outgoing-calls-in-android/

http://www.krvarma.com/posts/android/android-network-connectivity-broadcastreceiver/

free counters

Posted in Android, Tutorials | Tagged , , , , | Leave a comment

List View Tutorial For Android

List View Tutorial is used to show data in tabular form as shown in picture.

Here is the complete source code.

list_item.xml

In list_item.xml i simply designed a cell of list which contains two text views(name & description) and imageview(forward arrow).

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent" android:padding="6px"
	android:layout_height="67px" android:id="@+id/rlt_main"
	android:background="#000000">
	<TextView android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:id="@+id/tv_name"
		android:text="Name" android:layout_centerVertical="true"></TextView>
	<TextView android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:text="Description"
		android:id="@+id/tv_description" android:layout_centerVertical="true"
		android:layout_toRightOf="@+id/tv_name" android:layout_marginLeft="10px"></TextView>
	<ImageView android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:layout_centerVertical="true"
		android:id="@+id/iv_forward" android:background="@drawable/forward_arrow"
		android:layout_alignParentRight="true"></ImageView>
</RelativeLayout>

main.xml

In main.xml i designed the layout contain header and footer(relative layout) having height 50 px. In between them there is relative layout containing list view used to show items list.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/RelativeLayout01"
	android:layout_width="fill_parent" android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<RelativeLayout android:id="@+id/RelativeLayout02"
		android:layout_height="50px" android:layout_width="fill_parent"
		android:background="#ffffff"></RelativeLayout>
	<RelativeLayout android:id="@+id/RelativeLayout03"
		android:layout_width="fill_parent" android:layout_height="fill_parent"
		android:background="#808080" android:layout_above="@+id/RelativeLayout04"
		android:layout_below="@+id/RelativeLayout02">
		<ListView android:layout_width="wrap_content"
			android:layout_height="wrap_content" android:id="@+id/list_view"></ListView>
	</RelativeLayout>
	<RelativeLayout android:id="@+id/RelativeLayout04"
		android:layout_height="50px" android:layout_width="fill_parent"
		android:layout_alignParentBottom="true" android:background="#ffffff"></RelativeLayout>
</RelativeLayout>

Splash.java

In Splash activity i bind the itemslist coming from itemBO getItems() method.

In order to bind list i have to make ArrayAdapter Class ArrayList<ItemBO>, Context attributes and Constructor and getView() methods.

In getView() method i inflate the list_item layout and implement onClickListner to ListCell to apply action when user clicks on list cell which starts new Activity and pass ItemName to it in Intent.

public class Splash extends Activity implements OnClickListener {

	private ListView listview;
	private ArrayList mListItem;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		listview = (ListView) findViewById(R.id.list_view);
		mListItem = ItemBO.getItems();
		listview.setAdapter(new ListAdapter(Splash.this, R.id.list_view,
				mListItem));
	}

	@Override
	public void onClick(View v) {
	}

	// ***ListAdapter***
	private class ListAdapter extends ArrayAdapter { //--CloneChangeRequired
		private ArrayList mList; //--CloneChangeRequired
		private Context mContext;

		public ListAdapter(Context context, int textViewResourceId,
				ArrayList list) { //--CloneChangeRequired
			super(context, textViewResourceId, list);
			this.mList = list;
			this.mContext = context;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			try {
				if (view == null) {
					LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = vi.inflate(R.layout.list_item, null); //--CloneChangeRequired(list_item)
				}
				final ItemBO listItem = mList.get(position); //--CloneChangeRequired
				if (listItem != null) {
					// setting list_item views
					((TextView) view.findViewById(R.id.tv_name))
							.setText(listItem.getName());
					view.setOnClickListener(new OnClickListener() {
						public void onClick(View arg0) { //--clickOnListItem
							Intent myIntent = new Intent(Splash.this,
									Activity2.class);
							myIntent.putExtra("NAME", listItem.getName());
							startActivity(myIntent);
							finish();
						}
					});
				}
			} catch (Exception e) {
				Log.i(Splash.ListAdapter.class.toString(), e.getMessage());
			}
			return view;
		}
	}
}

Activity2.java

In Activity2 i just show that which item of items list is clicked and allow to go back.

public class Activity2 extends Activity {
	private Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		RelativeLayout relativeLayout = new RelativeLayout(this);
		Button button = new Button(this);
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			button.setText("Item name = " + bundle.getString("NAME")
					+ " --- Go Back ");
		} else {
			button.setText("Go Back");
		}
		context = this;
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(context, Splash.class));
				finish();
			}
		});
		relativeLayout.addView(button);
		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		setContentView(relativeLayout, params);
	}

}

ItemBO.java

It is the itemBO class containing name, description attributes and getItems() method.

public class ItemBO {
	private String name;
	private String description;
	public String getName() { return name;	}
	public void setName(String name) { this.name = name; }
	public String getDescription() { return description; }
	public void setDescription(String description) { this.description = description; }
	// / --------------------
	public static ArrayList getItems() {
		ArrayList list = new ArrayList();
		ItemBO item;

		item = new ItemBO();
		item.setName("item 1");
		item.setDescription("desc 1");
		list.add(item);

		item = new ItemBO();
		item.setName("item 2");
		item.setDescription("desc 2");
		list.add(item);

		item = new ItemBO();
		item.setName("item 3");
		item.setDescription("desc 3");
		list.add(item);

		return list;
	}
}

Here is the complete source code.

You can also extend ListView Class and make your own Generic List. Here its source code.

Other Links

http://ykyuen.wordpress.com/2010/01/03/android-simple-listview-using-simpleadapter/

free counters

Posted in Android, Tutorials | Tagged , , , | 5 Comments

Custom Dialog Tutorial for Android

Purpose

We can also make custom dialog in Android by extending class from Dialog class. In custom dialog we can make a dialog as required layout which is not possible in AlertDialog.

You can download the complete source code from here.

InfoDialog.java

public class InfoDialog extends Dialog implements android.view.View.OnClickListener{
	private TextView tvTitle;
	private TextView tvDescription;
	private ImageView ivEnterMain;
	private Context context;
	private String title;
	private String description;
	private String URL;
	private Intent intent;

	public InfoDialog(Context context, String title, String description,String URL, Intent intent){
	    super(context);
    	    this.context = context;
	    this.title = title;
	    this.description = description;
	    this.URL = URL;
	    this.intent = intent;
	}

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.infodialog);
	tvTitle = (TextView) findViewById(R.id.tv_titleMain);
	tvDescription = (TextView) findViewById(R.id.tv_descriptionMain);
	ivEnterMain = (ImageView) findViewById(R.id.iv_EnterMain);
	tvTitle.setText(title);
        tvDescription.setText(description);
        ivEnterMain.setOnClickListener(this);
    }

    public void onClick(View v) {
        context.startActivity(intent);
        dismiss();
    }
}

infodialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayoutMain"
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_height="wrap_content" android:layout_width="wrap_content">
	<LinearLayout android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:id="@+id/llh_dialogbox_infoMain"
		android:orientation="horizontal" android:background="#808080">
		<LinearLayout android:layout_width="wrap_content"
			android:layout_height="wrap_content" android:id="@+id/llv_tvTitleDetailsMain"
			android:orientation="vertical">
			<TextView android:text="TextView01" android:layout_width="wrap_content"
				android:layout_height="wrap_content" android:id="@+id/tv_titleMain"></TextView>
			<TextView android:text="TextView02" android:layout_width="wrap_content"
				android:layout_height="wrap_content" android:id="@+id/tv_descriptionMain"
				android:textSize="10px"></TextView>
		</LinearLayout>
		<ImageView android:layout_width="wrap_content"
			android:layout_height="wrap_content" android:id="@+id/iv_EnterMain"
			android:layout_gravity="center_vertical" android:src="@drawable/forward_arrow"></ImageView>
	</LinearLayout>
</LinearLayout>

Splash.java

public class Splash extends Activity implements OnClickListener{
    private InfoDialog infoDialog;
    private Button btnShowDialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnShowDialog = (Button) findViewById(R.id.btn_dialog);
        btnShowDialog.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
 	Intent myIntent = new Intent(this, Activity2.class);
	infoDialog = new InfoDialog(this, "Title", "Description", "http://www.google.com", myIntent);
	infoDialog.show();
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<TextView android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:text="@string/hello" />
	<Button android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:id="@+id/btn_dialog"
		android:text="Show Dialog"></Button>
</LinearLayout>

Activity2.java

public class Activity2 extends Activity {
	private Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		RelativeLayout relativeLayout = new RelativeLayout(this);
		Button button = new Button(this);
		button.setText("Go Back");
		context = this;
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(context, Splash.class));
				finish();
			}
		});
		relativeLayout.addView(button);
		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		setContentView(relativeLayout, params);
	}

}
Posted in Android, Tutorials | Tagged , , , , | 3 Comments

Progress Bar Tutorial For Android

Purpose of Progress Bar

Progress Bar is used when app required some progressing behind or require some procesing which take time to show the user app is busy and will take time. Here is the source code to show progerss bar on android.

splash.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:background="@drawable/splash" android:layout_height="fill_parent"
	android:layout_width="fill_parent">
	<LinearLayout android:layout_alignParentBottom="true"
		android:layout_centerHorizontal="true" android:layout_marginBottom="58px"
		android:layout_height="45px" android:layout_width="200px"
		android:id="@+id/lin_progress_bar" android:visibility="invisible">
		<ProgressBar android:id="@+id/ProgressBar01"
			android:layout_width="wrap_content" android:layout_height="wrap_content"></ProgressBar>
		<TextView android:id="@+id/TextView01" android:layout_height="fill_parent"
			android:layout_width="fill_parent" android:gravity="center_vertical"
			android:textStyle="bold" android:text="Loading..."
			android:layout_marginLeft="10px" android:textSize="23px"
			android:textColor="#808080"></TextView>
	</LinearLayout>
</RelativeLayout>

Progress Bar is used under the linear layout tag to simply hide and show the layout as required.
Splash.java

public class Splash extends Activity {

	private LinearLayout linProgressBar;
	private final Handler uiHandler=new Handler();
	private boolean isUpdateRequired=false;

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

		basicInitializations();
	}

	public void basicInitializations(){

		linProgressBar = (LinearLayout) findViewById(R.id.lin_progress_bar);
		linProgressBar.setVisibility(View.VISIBLE);

		try{
			new Thread(){
				public void run() {
					initializeApp();
					uiHandler.post( new Runnable(){
						@Override
						public void run() {
							if(isUpdateRequired){
								//TODO:
							}else{
								linProgressBar.setVisibility(View.GONE);
								startActivity( new Intent(WMXSplash.this, WMXLogin.class) );
								finish();
							}
						}
					} );
				}
				public void initializeApp(){
					// Initialize application data here
				}
		}.start();
		}catch (Exception e) {}
	}

Thread starts when processing starts and when processing completes dialog box dismissed and layout gone.

Loading Progress Bar

see the blog.   http://huuah.com/android-progress-bar-and-thread-updating/

Posted in Android, Tutorials | Tagged , , , , | 1 Comment