Tag Archives: Toast

How to write a custom content provider in android? with a sample application using our own custom content provider.

Hello all

we all know what are content providers right?
Those who are unaware of content providers please visit this link http://developer.android.com/guide/topics/providers/content-providers.html

Custom Content Provider

Custom Content Provider

In a breif content Providers are

Content providers manage access to a structured set of data. They encapsulate the data, and provide mechanisms for defining data security. Content providers are the standard interface that connects data in one process with code running in another process.

When you want to access data in a content provider, you use the ContentResolver object in your application’s Context to communicate with the provider as a client. The ContentResolver object communicates with the provider object, an instance of a class that implements ContentProvider. The provider object receives data requests from clients, performs the requested action, and returns the results.

This sample Demo is creating custom content provider using SQLite Database.

Now we will see how we can create our own custom content provider.

Tn this example I have three classes.
1. MainActivity.java
2. NotesContentProvider.java
3. NotesMetaData.java

At first we will look at “NotesMetaData.java”.

package com.coderzheaven.custom_contentproviderdemo;

import android.net.Uri;
import android.provider.BaseColumns;

public class NotesMetaData {

	public NotesMetaData() {

	}

	// A content URI is a URI that identifies data in a provider. Content URIs
	// include the symbolic name of the entire provider (its authority)
	public static final String AUTHORITY = "com.coderzheaven.custom_contentproviderdemo.Notes";
	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
			+ "/notes");

	public static final String DATABASE_NAME = "notes.db";
	public static final int DATABASE_VERSION = 1;

	public static final String CONTENT_TYPE_NOTES_ALL = "vnd.android.cursor.dir/vnd.coderz.notes";
	public static final String CONTENT_TYPE_NOTES_ONE = "vnd.android.cursor.item/vnd.coderz.notes";

	public class NotesTable implements BaseColumns {

		private NotesTable() {

		}

		public static final String TABLE_NAME = "tbl_notes";

		public static final String ID = "_id";
		public static final String TITLE = "title";
		public static final String CONTENT = "content";
	}

}

NotesMetaData class defines some required constant values to use:

+ AUTHORITY: this is the name of your content provider

+ CONTENT_URI: is your content provider URI for other applications to access data from it.

Let’s say if you want to get all notes, it would be like:

content://”com.coderzheaven.custom_contentproviderdemo.Notes/notes”

To retrieve a specific note:

content://com.coderzheaven.custom_contentproviderdemo.Notes/notes/5″

Now the “NotesContentProvider.java”

package com.coderzheaven.custom_contentproviderdemo;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class NotesContentProvider extends ContentProvider {

	private static final UriMatcher sUriMatcher;

	private static final int NOTES_ALL = 1;
	private static final int NOTES_ONE = 2;

	static {
		sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		sUriMatcher.addURI(NotesMetaData.AUTHORITY, "notes", NOTES_ALL);
		sUriMatcher.addURI(NotesMetaData.AUTHORITY, "notes/#", NOTES_ONE);
	}

	// Map table columns
	private static final HashMap<String, String> sNotesColumnProjectionMap;
	static {
		sNotesColumnProjectionMap = new HashMap<String, String>();
		sNotesColumnProjectionMap.put(NotesMetaData.NotesTable.ID,
				NotesMetaData.NotesTable.ID);
		sNotesColumnProjectionMap.put(NotesMetaData.NotesTable.TITLE,
				NotesMetaData.NotesTable.TITLE);
		sNotesColumnProjectionMap.put(NotesMetaData.NotesTable.CONTENT,
				NotesMetaData.NotesTable.CONTENT);
	}

	private static class NotesDBHelper extends SQLiteOpenHelper {

		public NotesDBHelper(Context c) {
			super(c, NotesMetaData.DATABASE_NAME, null,
					NotesMetaData.DATABASE_VERSION);
		}

		private static final String SQL_QUERY_CREATE = "CREATE TABLE "
				+ NotesMetaData.NotesTable.TABLE_NAME + " ("
				+ NotesMetaData.NotesTable.ID
				+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
				+ NotesMetaData.NotesTable.TITLE + " TEXT NOT NULL, "
				+ NotesMetaData.NotesTable.CONTENT + " TEXT NOT NULL" + ");";

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(SQL_QUERY_CREATE);
		}

		private static final String SQL_QUERY_DROP = "DROP TABLE IF EXISTS "
				+ NotesMetaData.NotesTable.TABLE_NAME + ";";

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer) {
			db.execSQL(SQL_QUERY_DROP);
			onCreate(db);
		}
	}

	// create a db helper object
	private NotesDBHelper mDbHelper;

	@Override
	public boolean onCreate() {
		mDbHelper = new NotesDBHelper(getContext());
		return false;
	}

	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		SQLiteDatabase db = mDbHelper.getWritableDatabase();
		int count = 0;
		switch (sUriMatcher.match(uri)) {
		case NOTES_ALL:
			count = db.delete(NotesMetaData.NotesTable.TABLE_NAME, where,
					whereArgs);
			break;

		case NOTES_ONE:
			String rowId = uri.getPathSegments().get(1);
			count = db.delete(
					NotesMetaData.NotesTable.TABLE_NAME,
					NotesMetaData.NotesTable.ID
							+ " = "
							+ rowId
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ")" : ""), whereArgs);
			break;

		default:
			throw new IllegalArgumentException("Unknown URI: " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public String getType(Uri uri) {

		switch (sUriMatcher.match(uri)) {
		case NOTES_ALL:
			return NotesMetaData.CONTENT_TYPE_NOTES_ALL;

		case NOTES_ONE:
			return NotesMetaData.CONTENT_TYPE_NOTES_ONE;

		default:
			throw new IllegalArgumentException("Unknown URI: " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {

		// you cannot insert a bunch of values at once so throw exception
		if (sUriMatcher.match(uri) != NOTES_ALL) {
			throw new IllegalArgumentException(" Unknown URI: " + uri);
		}

		// Insert once row
		SQLiteDatabase db = mDbHelper.getWritableDatabase();
		long rowId = db.insert(NotesMetaData.NotesTable.TABLE_NAME, null,
				values);
		if (rowId > 0) {
			Uri notesUri = ContentUris.withAppendedId(
					NotesMetaData.CONTENT_URI, rowId);
			getContext().getContentResolver().notifyChange(notesUri, null);
			return notesUri;
		}
		throw new IllegalArgumentException("<Illegal>Unknown URI: " + uri);
	}

	// Get values from Content Provider
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
		switch (sUriMatcher.match(uri)) {
		case NOTES_ALL:
			builder.setTables(NotesMetaData.NotesTable.TABLE_NAME);
			builder.setProjectionMap(sNotesColumnProjectionMap);
			break;

		case NOTES_ONE:
			builder.setTables(NotesMetaData.NotesTable.TABLE_NAME);
			builder.setProjectionMap(sNotesColumnProjectionMap);
			builder.appendWhere(NotesMetaData.NotesTable.ID + " = "
					+ uri.getLastPathSegment());
			break;

		default:
			throw new IllegalArgumentException("Unknown URI: " + uri);
		}

		SQLiteDatabase db = mDbHelper.getReadableDatabase();
		Cursor queryCursor = builder.query(db, projection, selection,
				selectionArgs, null, null, null);
		queryCursor.setNotificationUri(getContext().getContentResolver(), uri);

		return queryCursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where,
			String[] whereArgs) {

		SQLiteDatabase db = mDbHelper.getWritableDatabase();
		int count = 0;
		switch (sUriMatcher.match(uri)) {
		case NOTES_ALL:
			count = db.update(NotesMetaData.NotesTable.TABLE_NAME, values,
					where, whereArgs);
			break;

		case NOTES_ONE:
			String rowId = uri.getLastPathSegment();
			count = db
					.update(NotesMetaData.NotesTable.TABLE_NAME, values,
							NotesMetaData.NotesTable.ID	+ " = "	+ rowId	+ (!TextUtils.isEmpty(where) ? " AND ("	+ ")" : ""), whereArgs);

		default:
			throw new IllegalArgumentException("Unknown URI: " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

}

When you insert/update/delete, always remember to call “notifyChange()” to the URI that has been used.

When you query values, always remember to to call “setNotificationUri()” for Cursor.

That’s done for creating your custom content provider. In order to use, you need to register it to AndroidManifest.xml

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

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

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        
        
        <provider
            android:name="com.coderzheaven.custom_contentproviderdemo.NotesContentProvider"
            android:authorities="com.coderzheaven.custom_contentproviderdemo.Notes" >
        </provider>
        
    </application>

</manifest>

Now we look how we can use it in an activity

MainActivity.java

package com.coderzheaven.custom_contentproviderdemo;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.coderzheaven.custom_contentproviderdemo.NotesMetaData.NotesTable;

public class MainActivity extends Activity implements OnClickListener {

	private final static String TAG = "CustomContentProvider";
	EditText title, content, delete_id;
	Button add, update, delete, showNotes;

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

		title = (EditText) findViewById(R.id.title);
		content = (EditText) findViewById(R.id.content);
		delete_id = (EditText) findViewById(R.id.delete_id);

		// add Click Listners
		add = (Button) findViewById(R.id.button_add);
		add.setOnClickListener(this);
		update = (Button) findViewById(R.id.button_update);
		update.setOnClickListener(this);
		delete = (Button) findViewById(R.id.button_delete);
		delete.setOnClickListener(this);
		showNotes = (Button) findViewById(R.id.show_notes);
		showNotes.setOnClickListener(this);

		getNotes();

	}

	void addNote() {
		if (title.getText().toString().length() > 0
				&& content.getText().toString().length() > 0) {
			ContentValues values = new ContentValues();
			values.put(NotesTable.TITLE, title.getText().toString());
			values.put(NotesTable.CONTENT, content.getText().toString());
			getContentResolver().insert(NotesMetaData.CONTENT_URI, values);
			Log.i(TAG, "Inserted");
			makeToast("Note Added");
		} else {
			makeToast("Empty Field");
		}
	}

	void deleteNote(String str_id) {
		try {
			int id = Integer.parseInt(str_id);
			Log.i(TAG, "Deleting with id = " + id);
			getContentResolver().delete(NotesMetaData.CONTENT_URI,
					NotesMetaData.NotesTable.ID + " = " + id, null);
			Log.i(TAG, "Deleted");
			makeToast("Note Deleted");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	void updateNote(String str_id) {
		try {
			int id = Integer.parseInt(str_id);
			Log.i(TAG, "Updating with id = " + id);
			ContentValues values = new ContentValues();
			values.put(NotesTable.TITLE, title.getText().toString());
			values.put(NotesTable.CONTENT, content.getText().toString());
			getContentResolver().update(NotesMetaData.CONTENT_URI, values,
					NotesMetaData.NotesTable.ID + " = " + id, null);
			makeToast("Note Updated");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	void getNotes() {

		Cursor cur = getContentResolver().query(NotesMetaData.CONTENT_URI,
				null, null, null, null);

		if (cur.getCount() > 0) {
			Log.i(TAG, "Showing values.....");
			while (cur.moveToNext()) {
				String Id = cur.getString(cur.getColumnIndex(NotesTable.ID));
				String title = cur.getString(cur
						.getColumnIndex(NotesTable.TITLE));
				System.out.println("Id = " + Id + ", Note Title : " + title);
			}
			makeToast("Check the LogCat for Notes");
		} else {
			Log.i(TAG, "No Notes added");
			makeToast("No Notes added");
		}
	}

	@Override
	public void onClick(View arg0) {
		if (arg0 == add) {
			addNote();
		}
		if (arg0 == update) {
			// update note with Id
			updateNote(delete_id.getText().toString());
		}
		if (arg0 == delete) {
			// delete note with Id
			deleteNote(delete_id.getText().toString());
		}
		if (arg0 == showNotes) {
			// show all
			getNotes();
		}
	}

	private void makeToast(String text) {
		Toast.makeText(this, text, Toast.LENGTH_LONG).show();
	}

}

You can download the complete source code from this demo here.

Handling Multiple Instances of a Widget in Android and Identifying each instance with it’s own ID.

Hey everyone…….Hope all are well…..

This post is about Android Widgets.
This is going to be one of the bigger posts in Coderzheaven.

This posts helps you to handle multiple instances of a Widget.
Many of our problem is to identify different instances of the same widget.

But there is a solution to this problem.

Please check out my other posts in Coderzheaven to get an Idea of Android Widgets and it’s working.

Create new Widget

http://www.coderzheaven.com/2012/06/15/placing-controls-widget-android-listening-events-them/

How to get Notified when a widget is deleted?

Android Multiple Instance Widget

Android Multiple Instance Widget

Android Multiple Instance Widget

Android Multiple Instance Widget

Here is how we start.

First of all you need to keep these things about the Widget in Mind.

    1. Every instance of Same Widget is associated with a Unique ID.
    2. Widgets ID’s are sent through in the activities that has the “android.appwidget.action.APPWIDGET_CONFIGURE” intent-filter.
    3. RESULT_OK should sent back to the widget

Now we will start.

First we will look at the layouts.

This is the Widget Layout.
widget_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/widget_root"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:baselineAligned="false"
    android:orientation="vertical"
    android:background="@drawable/theme0" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Widget Text"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

Now the widgetprovider XML.

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="250dip"
    android:minHeight="72dip"
    android:updatePeriodMillis="100000"
    android:configure="com.coderzheaven.multiplewidgetinstance.SettingsPage" 
    android:initialLayout="@layout/widget_main"
/> 

Please note that you have to use the exact package name with the class named you used as Configure Intent-filter in the “android:configure” property.

Now the XML for the settings Page.

<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"
    android:padding="20dp"
    tools:context=".MainActivity" 
    android:background="@drawable/theme0">

    <TextView
        android:id="@+id/id_tv"
        android:paddingBottom="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textStyle="bold"
        android:textSize="18dp"
        android:text="@string/hello_world" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/id_tv"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
            android:textStyle="bold"
        android:text="Save" />

</RelativeLayout>

Please check the above screenshot how it looks like when clicking on the widget.
It is having an edittext in which we will enter the value for the widget.

Our all layout xml are now complete.
Now we will go to the java classes.

We will write the MyAppWidgetProvider class

MyAppWidgetProvider.java

package com.coderzheaven.multiplewidgetinstance;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;

public class MyAppWidgetProvider extends AppWidgetProvider {

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
	}

	/*
	 * This is called when an instance the App Widget is created for the first
	 * time.
	 */
	@Override
	public void onEnabled(Context context) {
		super.onEnabled(context);
	}

	/*
	 * This is called for every broadcast and before each of the above callback
	 * methods.
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
		super.onReceive(context, intent);
	}

	/*
	 * This is called When all instances of App Widget is deleted from the App
	 * Widget host.
	 */
	@Override
	public void onDisabled(Context context) {
		// Unschedule any timers and tasks
		super.onDisabled(context);
	}

	/*
	 * This is called every time an App Widget is deleted from the App Widget
	 * host.
	 */
	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		// Unschedule any timers and tasks
		super.onDeleted(context, appWidgetIds);
	}
}

Please make sure you read the comments in this java, so I am providing any description for that.

Now the SettingsPage that edit the widget.

package com.coderzheaven.multiplewidgetinstance;

import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RemoteViews;
import android.widget.TextView;

public class SettingsPage extends Activity {

	int thisWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	public static String ACTION_WIDGET_CONFIGURE = "WIDGET_CONFIGURED";
	SharedPreferences customSharedPreference;
	EditText ed = null;
	Button save = null;
	TextView widgetId = null;

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

		ed = (EditText) findViewById(R.id.editText1);
		save = (Button) findViewById(R.id.button1);
		widgetId = (TextView) findViewById(R.id.id_tv);

		save.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				updateWidget();
				if (ed.getText().toString().trim().length() > 0) {
					saveToPreferences("Widget" + thisWidgetId, ed.getText()
							.toString().trim());

					setResultDataToWidget(RESULT_OK);
				} else
					setResultDataToWidget(RESULT_CANCELED);
			}
		});

		getIdOfCurrentWidget(savedInstanceState);

	}

	/** Get the Id of Current Widget from the intent of the Widget **/
	void getIdOfCurrentWidget(Bundle savedInstanceState) {

		setResult(RESULT_CANCELED);

		Bundle extras = getIntent().getExtras();

		if (extras != null) {
			thisWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
					AppWidgetManager.INVALID_APPWIDGET_ID);
			if (getWidgetData("Widget" + thisWidgetId) != null) {
				save.setText("Update");
				ed.append(getWidgetData("Widget" + thisWidgetId));
			}

			widgetId.setText("Widget ID = " + thisWidgetId);
		}

		// If they gave us an intent without the widget id, just bail.
		if (thisWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
			finish();
		}

	}

	/**
	 * Update the Current Widget - This is very important to ensure the widget
	 * is enabled
	 **/
	void updateWidget() {
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
		RemoteViews remoteViews = new RemoteViews(getPackageName(),
				R.layout.widget_main);
		Intent clickIntent = getIntent();
		clickIntent.setAction(ACTION_WIDGET_CONFIGURE);
		remoteViews.setTextViewText(R.id.textView1, ed.getText().toString()
				.trim());
		clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, thisWidgetId);
		PendingIntent pendingIntent = PendingIntent.getActivity(this,
				thisWidgetId, clickIntent, 0);
		remoteViews.setOnClickPendingIntent(R.id.widget_root, pendingIntent);
		// update this widget
		appWidgetManager.updateAppWidget(thisWidgetId, remoteViews);
	}

	void setResultDataToWidget(int result) {
		Intent resultValue = new Intent();
		resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, thisWidgetId);
		setResult(result, resultValue);
		finish();
	}

	public void saveToPreferences(String file_name, String data) {
		SharedPreferences myPrefs = getSharedPreferences("Data",
				MODE_WORLD_WRITEABLE);
		SharedPreferences.Editor prefsEditor = myPrefs.edit();
		prefsEditor.putString(file_name, data);
		prefsEditor.commit();
	}

	public String getWidgetData(String file_name) {
		SharedPreferences myPrefs = getSharedPreferences("Data",
				MODE_WORLD_READABLE);
		return (myPrefs.getString(file_name, null));
	}

}

Now the AndroidManifest File.
Make sure you carefully read the Manifest files. Look at the intent filters in the activities and make sure that you have the correct package name in the provider xml file.

AndroidManifest.xml

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.coderzheaven.multiplewidgetinstance.SettingsPage"
            android:configChanges="keyboardHidden|orientation"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Dialog">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
            </intent-filter>
        </activity>

        <!-- Broadcast Receiver that will process AppWidget Updates -->
        <receiver
            android:name="com.coderzheaven.multiplewidgetinstance.MyAppWidgetProvider"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@layout/my_widget_provider" />
        </receiver>
    </application>

</manifest>

Hooray you multiple instance code is complete.
Here we are saving data for each widget in the preferences with the widgetId as key with which we are reloading the data and editing it.

You can download the complete source code from here.

How to create a fully customizable Toast which will use your own time duration and gravity and layout with ease without using the default toast in android?

Hello all
We all have seen toasts right…ok then you have already customized your toasts right.

Here I will show you a method to create toasts which will last the time you set and the gravity.

You can download the code by clicking on the download links.

Custom Toast

This is the class that creates the toast notification.

MyMsgBox.java

package com.example.messageboxtest;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MyMsgBox {

	private static final int ANIMATION_DURATION = 600;

	private int HIDE_DELAY = 5000;

	private View mContainer;

	private int gravity = Gravity.CENTER;

	private TextView mTextView;

	private Handler mHandler;

	private AlphaAnimation mFadeInAnimation;

	private AlphaAnimation mFadeOutAnimation;

	public MyMsgBox(Context context, int HIDE_DELAY, int gravity) {
		ViewGroup container = (ViewGroup) ((Activity) context)
				.findViewById(android.R.id.content);
		View v = ((Activity) context).getLayoutInflater().inflate(
				R.layout.newmb__messagebar, container);
		this.HIDE_DELAY = HIDE_DELAY;
		this.gravity = gravity;
		init(v);
	}

	private void init(View v) {
		mContainer = v.findViewById(R.id.mbContainer);
		mContainer.setVisibility(View.GONE);
		mTextView = (TextView) v.findViewById(R.id.mbMessage);
		mFadeInAnimation = new AlphaAnimation(0.0f, 1.0f);
		mFadeOutAnimation = new AlphaAnimation(1.0f, 0.0f);
		mFadeOutAnimation.setDuration(ANIMATION_DURATION);
		mFadeOutAnimation
				.setAnimationListener(new Animation.AnimationListener() {
					@Override
					public void onAnimationStart(Animation animation) {
					}

					@Override
					public void onAnimationEnd(Animation animation) {
						mContainer.setVisibility(View.GONE);
					}

					@Override
					public void onAnimationRepeat(Animation animation) {
					}
				});

		mHandler = new Handler();

	}

	public void show(String message) {
		mContainer.setVisibility(View.VISIBLE);

		((LinearLayout) mContainer).setGravity(gravity
				| Gravity.CENTER_VERTICAL);

		mTextView.setText(message);

		mFadeInAnimation.setDuration(ANIMATION_DURATION);

		mContainer.startAnimation(mFadeInAnimation);
		mHandler.postDelayed(mHideRunnable, HIDE_DELAY);
	}

	private final Runnable mHideRunnable = new Runnable() {
		@Override
		public void run() {
			mContainer.startAnimation(mFadeOutAnimation);
		}
	};

}

Now the layout for this toast.. Here I am making a toast with only one textview in it.

This is the layout.
newmb__messagebar.xml

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

    <LinearLayout
        style="@style/bgTheme"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="bottom"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/mbMessage"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Test"
            android:textColor="@drawable/white" />
    </LinearLayout>

</LinearLayout>

This will create some errors.
inside your drawable folder create an xml named “bg_gradiant.xml” and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item><shape>
            <solid android:color="@drawable/dark_grey" />

            <stroke android:width="0dp" android:color="#000000" />

            <corners android:radius="5dp" />
        </shape></item>

</selector>

And at last in your values/styles.xml add this style

 <style name="bgTheme">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_gravity">center_horizontal|center</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">@drawable/white</item>
        <item name="android:textStyle">bold</item>
        <item name="android:layout_margin">3dp</item>
        <item name="android:background">@drawable/bg_gradiant</item>
        <item name="android:textSize">14sp</item>
        <item name="android:typeface">normal</item>
        <item name="android:text">05</item>
        <item name="android:padding">10dp</item>
    </style>
[/xml

You can add these colors to your <strong>strings.xml</strong>
1
    <drawable name="white">#ffffff</drawable>
    <drawable name="black">#000000</drawable>
    <drawable name="blue">#2554C7</drawable>
    <drawable name="green">#347C2C</drawable>
    <drawable name="orange">#ff9900</drawable>
    <drawable name="pink">#FF00FF</drawable>
    <drawable name="violet">#a020f0</drawable>
    <drawable name="grey">#778899</drawable>
    <drawable name="red">#C11B17</drawable>
    <drawable name="yellow">#FFFF8C</drawable>
    <drawable name="PowderBlue">#b0e0e6</drawable>
    <drawable name="brown">#2F1700</drawable>
    <drawable name="Hotpink">#7D2252</drawable>
    <drawable name="dark_grey">#424242</drawable>

Now in your activity call the class like this.

// time in ms
MyMsgBox m = new MyMsgBox(arg0.getContext(), 5000,
		Gravity.BOTTOM);
m.show("Hello this is a custom toast");

Our custom toast is complete, now run the project and customize it according to your need.

You can download the complete android source code for this project from here.

How to create a simple PopUp Menu in Android?

Hello all…

This is a simple tutorial for creating a simple popup menu like the one you see in the action bar options button.
Actually this is fairly simple with actionBar. But if you don’t want the actionbar and only want the popup menu, then here is the solution.

PopUp in Android

You can read more about PopupMenu here
http://developer.android.com/reference/android/widget/PopupMenu.html

Note : The “PopupMenu” Class is only supported in versions from 3.0 (HoneyComb). So you must Set your project SDK to 3.0 or greater while testing this post.

Android 3.0(API Level 11) provide android.widget.PopupMenu class, to displays a Menu in a modal popup window anchored to a View. The popup will appear below the anchor view if there is room, or above it if there is not. If the IME is visible the popup will not overlap it until it is touched. Touching outside of the popup will dismiss it.

So here we start…

At first what you have to do is

1. Create a folder named “menu” in the “res” folder.

then create an XML named “popup.xml” in it and copy these contents to it.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/search"
        android:icon="@android:drawable/ic_menu_search"
        android:title="Search"/>
    <item
        android:id="@+id/add"
        android:icon="@android:drawable/ic_menu_add"
        android:title="Add"/>
    <item
        android:id="@+id/edit"
        android:icon="@android:drawable/ic_menu_edit"
        android:title="Edit">
        <menu>
            <item
                android:id="@+id/share"
                android:icon="@android:drawable/ic_menu_share"
                android:title="Share"/>
        </menu>
    </item>

</menu>

Now in your activity copy this code.
My Activity is named “PopupMenu1″…
So my code look like this…

package com.example.popuptest;

import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.Toast;

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

	public void onPopupButtonClick(View button) {
		PopupMenu popup = new PopupMenu(this, button);
		popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());

		popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				Toast.makeText(PopupMenu1.this,
						"Clicked popup menu item " + item.getTitle(),
						Toast.LENGTH_SHORT).show();
				return true;
			}
		});

		popup.show();
	}
}

How to crop an Image in Android?

This is a sample program that launches the camera and crop the captured image.

Check this link to another crop image example.

http://www.coderzheaven.com/2011/03/15/crop-an-image-in-android/

Crop an Image in Android

Crop an Image in Android

Crop an Image in Android

This is the layout xml.
activity_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:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="3dp"
        android:text="@string/intro"
        android:textStyle="bold" />

    <Button
        android:id="@+id/capture_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/capture" />

    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:contentDescription="@string/picture" />

</LinearLayout>

Now this is the Main Java File that implements the crop functionality.

Here we are using the “com.android.camera.action.CROP” Intent to crop the Image passing the captured Image URI to it.

package com.coderzheaven.cropimage;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class ShootAndCropActivity extends Activity implements OnClickListener {

	final int CAMERA_CAPTURE = 1;
	final int CROP_PIC = 2;
	private Uri picUri;

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

		Button captureBtn = (Button) findViewById(R.id.capture_btn);
		captureBtn.setOnClickListener(this);
	}

	public void onClick(View v) {
		if (v.getId() == R.id.capture_btn) {
			try {
				// use standard intent to capture an image
				Intent captureIntent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				// we will handle the returned data in onActivityResult
				startActivityForResult(captureIntent, CAMERA_CAPTURE);
			} catch (ActivityNotFoundException anfe) {
				Toast toast = Toast.makeText(this, "This device doesn't support the crop action!",
						Toast.LENGTH_SHORT);
				toast.show();
			}
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == CAMERA_CAPTURE) {
				// get the Uri for the captured image
				picUri = data.getData();
				performCrop();
			}
			// user is returning from cropping the image
			else if (requestCode == CROP_PIC) {
				// get the returned data
				Bundle extras = data.getExtras();
				// get the cropped bitmap
				Bitmap thePic = extras.getParcelable("data");
				ImageView picView = (ImageView) findViewById(R.id.picture);
				picView.setImageBitmap(thePic);
			}
		}
	}

	/**
	 * this function does the crop operation.
	 */
	private void performCrop() {
		// take care of exceptions
		try {
			// call the standard crop action intent (the user device may not
			// support it)
			Intent cropIntent = new Intent("com.android.camera.action.CROP");
			// indicate image type and Uri
			cropIntent.setDataAndType(picUri, "image/*");
			// set crop properties
			cropIntent.putExtra("crop", "true");
			// indicate aspect of desired crop
			cropIntent.putExtra("aspectX", 2);
			cropIntent.putExtra("aspectY", 1);
			// indicate output X and Y
			cropIntent.putExtra("outputX", 256);
			cropIntent.putExtra("outputY", 256);
			// retrieve data on return
			cropIntent.putExtra("return-data", true);
			// start the activity - we handle returning in onActivityResult
			startActivityForResult(cropIntent, CROP_PIC);
		}
		// respond to users whose devices do not support the crop action
		catch (ActivityNotFoundException anfe) {
			Toast toast = Toast
					.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
			toast.show();
		}
	}
}

Download the complete source code for the above example 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.

Dynamically Adding, Removing, Toggling and Removing all ActionBar Tabs in Android – Part 2?

Hi all..

In today’s post I will show you how to add actionbar tabs dynamically, remove one by one , hide and unhide them, removing all tabs at once etc.

This simple java code does that.

First create a project and in the MainActivity, paste this.

package com.coderzheaven.actionbartabs;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

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

    public void onAddTab(View v) {
        final ActionBar bar = getActionBar();
        final int tabCount = bar.getTabCount();
        final String text = "Tab " + tabCount;
        bar.addTab(bar.newTab()
                .setText(text)
                .setTabListener(new TabListener(new TabContentFragment(text))));
    }

    public void onRemoveTab(View v) {
        final ActionBar bar = getActionBar();
        if(bar.getTabCount() > 0)
        	bar.removeTabAt(bar.getTabCount() - 1);
    }

    public void onToggleTabs(View v) {
        final ActionBar bar = getActionBar();

        if (bar.getNavigationMode() == ActionBar.NAVIGATION_MODE_TABS) {
            bar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
            bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_TITLE);
        } else {
            bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
            bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
        }
    }

    public void onRemoveAllTabs(View v) {
        getActionBar().removeAllTabs();
    }

    /**
     * A TabListener receives event callbacks from the action bar as tabs
     * are deselected, selected, and reselected. 
     **/
    private class TabListener implements ActionBar.TabListener {
        private TabContentFragment mFragment;

        public TabListener(TabContentFragment fragment) {
            mFragment = fragment;
        }

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            ft.add(R.id.fragment_content, mFragment, mFragment.getText());
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            ft.remove(mFragment);
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            Toast.makeText(MainActivity.this, "Reselected!", Toast.LENGTH_SHORT).show();
        }
    }

    private class TabContentFragment extends Fragment {
        private String mText;

        public TabContentFragment(String text) {
            mText = text;
        }

        public String getText() {
            return mText;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View fragView = inflater.inflate(R.layout.action_bar_tab_content, container, false);

            TextView text = (TextView) fragView.findViewById(R.id.text);
            text.setText(mText);

            return fragView;
        }
    }
}

You may be getting many errors, we will be resolving all that in just a few minutes.

Now create an xml named “action_bar_tabs.xml” inside the res/layout folder and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">
    <FrameLayout android:id="@+id/fragment_content"
                 android:layout_width="match_parent"
                 android:layout_height="0dip"
                 android:layout_weight="1" />
    <LinearLayout android:layout_width="match_parent"
                  android:layout_height="0dip"
                  android:layout_weight="1"
                  android:orientation="vertical">
        <Button android:id="@+id/btn_add_tab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Add Tab"
                android:onClick="onAddTab" />
        <Button android:id="@+id/btn_remove_tab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Remove Tab"
                android:onClick="onRemoveTab" />
        <Button android:id="@+id/btn_toggle_tabs"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Toggle Tabs"
                android:onClick="onToggleTabs" />
        <Button android:id="@+id/btn_remove_all_tabs"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Remove All Tabs"
                android:onClick="onRemoveAllTabs" />
    </LinearLayout>
</LinearLayout>

Now create another xml for the tab content and named it “action_bar_tab_content.xml” and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/text"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" />

OK Done. Go on and run it.

ActionBar Tabs

ActionBar Tabs

ActionBar Tabs

ActionBar Tabs

Download Source code from here

Download.

Please leave your valuable comments now

How to create a Slide from Left animation while deleting a row from a ListView in Android?

Hello all……

I have written a lost of posts on Listviews. You can see that by just searching Listviews in my site. Today I will show you how to create a slide out animation while we delete a row from a ListView.

So this is the xml that contains the ListView. Let it be in the main.xml

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">
  
	<ListView android:layout_width="fill_parent" 
	  android:layout_height="fill_parent" 
	  android:id="@+id/mainListView">
	</ListView>
	
</LinearLayout>

Create another file inside the layout folder named “simplerow.xml”.

simplerow.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/rowTextView" 
 android:layout_width="fill_parent" 
 android:layout_height="wrap_content"
 android:padding="10dp"
 android:textSize="16sp" >
</TextView>

OK our xml part is over. Now the java part.

This is the main java file that implements this xml.

“SimpleListViewActivity.java”

package com.coderzheaven.pack;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class SimpleListViewActivity extends Activity {
  
  private ListView mainListView ;
  private ArrayAdapter<String> listAdapter ;
   ArrayList<String> all_planets = 
       new ArrayList<String>(){      
           private static final long serialVersionUID = -1773393753338094625L;
           {
               add("Mercury ");
               add("Venus "); 
               add("Earth"); 
               add("Mars"); 
               add("Jupiter"); 
               add("Saturn"); 
               add("Uranus"); 
               add("Neptune"); 
               add("Pluto"); 
           }
   };
   
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);    
  
    mainListView = (ListView) findViewById( R.id.mainListView );

    listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, all_planets);

    mainListView.setAdapter( listAdapter );  
    
    mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View rowView, int positon,long id) {
            Toast.makeText(rowView.getContext(), ""+positon, Toast.LENGTH_LONG).show();
            removeListItem(rowView,positon);
        }
    });
    
  }
  
  protected void removeListItem(View rowView, final int positon) {

      final Animation animation = AnimationUtils.loadAnimation(SimpleListViewActivity.this,android.R.anim.slide_out_right); 
      rowView.startAnimation(animation);
      Handler handle = new Handler();
      handle.postDelayed(new Runnable() {

		@Override
          public void run() {
        	  all_planets.remove(positon);
              listAdapter.notifyDataSetChanged();
              animation.cancel();
          }
      },1000);

  }

}

OK Done. Now run it and see the result.

Slide delete

Slide delete

Slide delete

Join the Forum discussion on this post

Download.

How to read and write files to SDCARD and application SandBox in Android – A complete example?

Here is a complete example of How to read and write files to SDCARD and application SandBox in Android.

First create a new project and inside the mainActivity paste this code.

package com.coderzheaven.filesexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

	EditText edittext;
	Button b1, b2, b3, b4;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        edittext = (EditText)findViewById(R.id.ed);
        edittext.setLines(10);
        b1 = (Button)findViewById(R.id.button1);
        b2 = (Button)findViewById(R.id.button2);
        b3 = (Button)findViewById(R.id.button3);
        b4 = (Button)findViewById(R.id.button4);
        
        b1.setOnClickListener(this);
        b2.setOnClickListener(this);
        b3.setOnClickListener(this);
        b4.setOnClickListener(this);        
        
    }
	@Override
	public void onClick(View v) {
		int id = v.getId();
		MyFile file = new MyFile(v.getContext());
		
		switch(id){
			case R.id.button1:
				if(!edittext.getText().toString().trim().equals("")){
					file.writeToSD(edittext.getText().toString());
				}else{
					Toast.makeText(v.getContext(), "Please enter some contents for the file", Toast.LENGTH_LONG).show();
				}
				break;
				
			case R.id.button2:
				edittext.setText(file.readFromSD());
				break;
			
			case R.id.button3:
				if(!edittext.getText().toString().trim().equals("")){
					file.writeToSandBox(edittext.getText().toString());
				}else{
					Toast.makeText(v.getContext(), "Please enter some contents for the file", Toast.LENGTH_LONG).show();
				}
				break;
				
			case R.id.button4:
				edittext.setText(file.readFromSandBox());
				break;
		}
		
		
		
	}

}

Now create another class named MyFile.java and copy this code into it.

package com.coderzheaven.filesexample;

import java.io. BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class MyFile {

	String TAG = "MyFile";
	Context context;
	public MyFile(Context context){
		this.context = context;
	}
	
	public Boolean writeToSD(String text){
		Boolean write_successful = false;
		 File root=null;  
	        try {  
	            // check for SDcard   
	            root = Environment.getExternalStorageDirectory();  
	            Log.i(TAG,"path.." +root.getAbsolutePath());  
	  
	            //check sdcard permission  
	            if (root.canWrite()){  
	                File fileDir = new File(root.getAbsolutePath());  
	                fileDir.mkdirs();  
	  
	                File file= new File(fileDir, "samplefile.txt");  
	                FileWriter filewriter = new FileWriter(file);  
	                BufferedWriter out = new BufferedWriter(filewriter);  
	                out.write(text);  
	                out.close();  
	                write_successful = true;
	            }  
	        } catch (IOException e) {  
	            Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());  
	            write_successful = false;
	        }  
		return write_successful;
	}
	
	public String readFromSD(){
		File sdcard = Environment.getExternalStorageDirectory();
		File file = new File(sdcard,"samplefile.txt");
		StringBuilder text = new StringBuilder();
		try {
		    BufferedReader br = new BufferedReader(new FileReader(file));
		    String line;
		    while ((line = br.readLine()) != null) {
		        text.append(line);
		        text.append('\n');
		    }
		}
		catch (IOException e) {
		}
		return text.toString();
	}

	@SuppressLint("WorldReadableFiles")
	@SuppressWarnings("static-access")
	public Boolean writeToSandBox(String text){
		Boolean write_successful = false;
		try{
			FileOutputStream fOut = context.openFileOutput("samplefile.txt",
					context.MODE_WORLD_READABLE);
			OutputStreamWriter osw = new OutputStreamWriter(fOut); 
			osw.write(text);
			osw.flush();
			osw.close();
		}catch(Exception e){
			write_successful = false;
		}
		return write_successful;
	}
	public String readFromSandBox(){
		String str ="";
		String new_str = "";
		try{
			FileInputStream fIn = context.openFileInput("samplefile.txt");
            InputStreamReader isr = new InputStreamReader(fIn);
            BufferedReader br=new BufferedReader(isr);
           
			while((str=br.readLine())!=null)
            {
				new_str +=str;
				System.out.println(new_str);
            }            
		}catch(Exception e)
		{			
		}
		return new_str;
	}
}

Now the layout for the xml file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/ed"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
		android:lines="5" android:gravity="top|left" android:inputType="textMultiLine"
		android:scrollHorizontally="false" 
		android:minWidth="10.0dip"
		android:maxWidth="5.0dip"
        android:layout_weight="1"/>


    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Write File to SDCARD" />
    
    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Read File from SDCARD" />
    
    <Button
        android:id="@+id/button3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Write File to Application SandBox" />
    
    <Button
        android:id="@+id/button4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Read File from Application SandBox" />

</LinearLayout>

Note you should give this permission in the AndroidManifest file.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

OK Done. Now run the project.

To view the files

1. To see the SDCARD
Open File explorer -> expand sdcard (or mnt/sdcard).
2. To see the Application SANDBOX
Open File explorer -> expand data/data/your_package_name/files.

Files Example

Download
.

Please leave your valuable comments on this post.

Join the Forum discussion on this post

How to stream an audio in Android?

This is a simple example to how to stream an audio in android.

Here is the java code for that.

package com.coderzheaven.pack;

import android.app.Activity;
import android.app.ProgressDialog;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class StreamAudioDemo extends Activity implements OnClickListener,
OnPreparedListener, OnErrorListener, OnCompletionListener {

    MediaPlayer mp;
    ProgressDialog pd;
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button bt = (Button)findViewById(R.id.play);
    bt.setOnClickListener(this);
}

   @Override
   public void onPrepared(MediaPlayer mp) {
       Log.i("StreamAudioDemo", "prepare finished");
       pd.setMessage("Playing.....");
       mp.start();
  }

  @Override
  public void onClick(View v) {
       try
        {
    	    pd = new ProgressDialog(this);
    	    pd.setMessage("Buffering.....");
    	    pd.show();
            mp = new MediaPlayer();
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mp.setOnPreparedListener(this);
            mp.setOnErrorListener(this);
            mp.setDataSource("http://www.robtowns.com/music/blind_willie.mp3");
            mp.prepareAsync();
            mp.setOnCompletionListener(this);
        }
        catch(Exception e)
        {
            Log.e("StreamAudioDemo", e.getMessage());
        }
  	}

  	@Override
  	public boolean onError(MediaPlayer mp, int what, int extra) {
      pd.dismiss();
      return false;
  	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		pd.dismiss();
		Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_LONG).show();		
	}
}

This is the xml that contains the button.

<?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"
    >
<Button  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Stream Audio and Play"
    android:id="@+id/play"
    />
</LinearLayout>

When you run this program you will see a button and on clicking on that button you will see a dialog with message “Buffering…..”. Once the buffering is complete the audio will be start playing.

Stream_1

Stream_2

Stream_3

Please leave your valuable comments on this post.

A Simple FlashLight Application.

Here is a simple Application on how to use flashlight in android.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class FlashLightActivity extends Activity {

	//flag to detect flash is on or off
	private boolean isLighOn = false;

	private Camera camera;

	private Button button;

	@Override
	protected void onStop() {
		super.onStop();

		if (camera != null) {
			camera.release();
		}
	}

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

		button = (Button) findViewById(R.id.buttonFlashlight);

		Context context = this;
		PackageManager pm = context.getPackageManager();

		// if device support camera?
		if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
			Log.e("err", "Device has no camera!");
			return;
		}
		try{
			camera = Camera.open();
			final Parameters p = camera.getParameters();
	
			button.setOnClickListener(new OnClickListener() {
	
				@Override
				public void onClick(View arg0) {
	
					if (isLighOn) {
	
						Log.i("info", "torch is turn off!");
	
						p.setFlashMode(Parameters.FLASH_MODE_OFF);
						camera.setParameters(p);
						camera.stopPreview();
						isLighOn = false;
	
					} else {
	
						Log.i("info", "torch is turn on!");
	
						p.setFlashMode(Parameters.FLASH_MODE_TORCH);
	
						camera.setParameters(p);
						camera.startPreview();
						isLighOn = true;
	
					}
	
				}
			});
		}catch(Exception e){
			Toast.makeText(this, "Your device doesnot have FlashLight capability", Toast.LENGTH_LONG).show();
		}

	}
}

Now the layout file main.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="fill_parent"
    android:layout_height="fill_parent" >

    <Button
        android:id="@+id/buttonFlashlight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       	android:layout_centerVertical="true"
       	android:layout_centerHorizontal="true"
        android:text="Torch" />

</RelativeLayout>

AndroiManifest.xml file contents.

Make sure to add the permissions.

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

    <uses-sdk android:minSdkVersion="5" />

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />

    <application
        android:debuggable="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".FlashLightActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Download the android java source code from here.

please leave your valuable comments on this post.

How to add a new contact programmatically in android?

We all know how to add a new contact to our android devices without programming right.
OK that’s a normal man’s use.
But what from a programmer’s view.

This is the sample java code that helps you to add contact programatically.

package com.coderzheaven.pack;

import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentValues;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Contacts.People;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.widget.Toast;

public class AddContactDemo extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        addContact("Coderz","1234567890");
        addContact("James","5656215521");
        addContact("John","4545454545");
        addContact("Mary","9632587410");
        addContact("Peter","4561237890");
    }
   private void addContact(String name, String phone) {
        ContentValues values = new ContentValues();
        values.put(People.NUMBER, phone);
        values.put(People.TYPE, Phone.TYPE_CUSTOM);
        values.put(People.LABEL, name);
        values.put(People.NAME, name);
        Uri dataUri = getContentResolver().insert(People.CONTENT_URI, values);
        Uri updateUri = Uri.withAppendedPath(dataUri, People.Phones.CONTENT_DIRECTORY);
        values.clear();
        values.put(People.Phones.TYPE, People.TYPE_MOBILE);
        values.put(People.NUMBER, phone);
        updateUri = getContentResolver().insert(updateUri, values);
      }
}

After running this programs please switch to contacts application on your device to see the result.

Add Contacts

Please leave your comments and also share it if you like it.

How to get Notified when a widget is deleted?

I have already covered a tutorial on how to start with widgets and how to create a simple widget here..

http://www.coderzheaven.com/2012/06/07/create-widget-android/

Today I will show you how to get notified when a widget is deleted.

if you have already gone through my previous post, then there is only a small change in the “MyWidget.java” file.

we have to add the onReceive() method to the class like this.

package com.coderzheaven.pack;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyWidget extends AppWidgetProvider {
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
		
	}
	@Override
	public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
				final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
																AppWidgetManager.INVALID_APPWIDGET_ID);
				if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
					this.onDeleted(context, new int[] { appWidgetId });
				}
				Toast.makeText(context, "Widget deleted", Toast.LENGTH_LONG).show();
			} else {
				super.onReceive(context, intent);
			}
			
	}
}

onReceive is always called before onUpdate is called. This code snipped checks the called action
and decides wheather to just run the receive method or the delete method.

I have already shown how to add a widget to the home screen, now for deleting simply press and hold the widget and drag to the delete icon on the bottom of the screen.

When you do this the onReceive() method will be called and a toast will appear saying “Widget Deleted”.

Widgets Android

You can download the complete android source code of the above post from here.

Please leave your valuable comments on this post.

How to add checkboxes and radio buttons to ListView in android? OR How to set single choice items in a ListView in android?

To create a list of multiple-choice items (checkboxes) or single-choice items (radio buttons) inside the dialog, use the setMultiChoiceItems() and setSingleChoiceItems() methods, respectively. If you create one of these selectable lists in the onCreateDialog() callback method, Android manages the state of the list for you. As long as the Activity is active, the dialog remembers the items that were previously selected, but when the user exits the Activity, the selection is lost.

final CharSequence[] items = {"Red", "Green", "Blue"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
    }
});
AlertDialog alert = builder.create();
alert.show();

The second parameter in the setSingleChoiceItems() method is an integer value for the checkedItem, which indicates the zero-based list position of the default selected item. Use “-1″ to indicate that no item should be selected by default.

Single Choice List

How to download a file from a remote site in android? – Another simple example – Method -3

Hello all …….

I have shown many examples on how to download and upload files in android through this site.

These are other methods for downloadign a file in android.

1. How to Download an image in ANDROID programatically?
2. How to download a file to your android device from a remote server with a custom progressbar showing progress?

I have shown four methods to upload an image to a server.
Check these posts to refer this.

1. Uploading audio, video or image files from Android to server
2. How to Upload Multiple files in one request along with other string parameters in android?
3. ANDROID – Upload an image to a server.
4. How to upload an image from Android device to server? – Method 4

This is yet another example on how to do download a file.

So this is the java code that downloads the file.

package com.coderzheaven.pack;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DownloadFileDemo extends Activity {
	
	String dwnload_file_path = "http://coderzheaven.com/sample_folder/sample_file.png";
	String dest_file_path = "/sdcard/dwnloaded_file.png";
	Button b1;
	ProgressDialog dialog = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        b1 = (Button)findViewById(R.id.Button01);
        b1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				dialog = ProgressDialog.show(DownloadFileDemo.this, "", "Downloading file...", true);
				 new Thread(new Runnable() {
			            public void run() {
			            	 downloadFile(dwnload_file_path, dest_file_path);
			            }
			          }).start();				
			}
		});
    }
    
    public void downloadFile(String url, String dest_file_path) {
    	  try {
    		  File dest_file = new File(dest_file_path);
    	      URL u = new URL(url);
    	      URLConnection conn = u.openConnection();
    	      int contentLength = conn.getContentLength();

    	      DataInputStream stream = new DataInputStream(u.openStream());

	          byte[] buffer = new byte[contentLength];
	          stream.readFully(buffer);
	          stream.close();

	          DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
	          fos.write(buffer);
	          fos.flush();
	          fos.close();
	          hideProgressIndicator();
	          
    	  } catch(FileNotFoundException e) {
    		  hideProgressIndicator();
    	      return; 
    	  } catch (IOException e) {
    		  hideProgressIndicator();
    	      return; 
    	  }
    }
    
    void hideProgressIndicator(){
    	runOnUiThread(new Runnable() {
		    public void run() {
		    	dialog.dismiss();
		    }
		});  
    }
}

This is the xml file that contains the button.

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="File Download Demo from Coderzheaven \n\nFile to download : http://coderzheaven.com/sample_folder/sample_file.png \n\nSaved Path : sdcard/\n"
    />
<Button 
	android:text="Download File" 
	android:id="@+id/Button01" 
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content">
</Button>
</LinearLayout>

Note : Please add these two permissions in the AndroidManifest.xml

  <uses-permission android:name="android.permission.INTERNET"/>    
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

download file android

download file android

Please leave your comments and also share this post if you like it.

How to check different Network status in Android?

This code snippet checks which of your networks are available in android.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.widget.Toast;

public class CheckConnectionsDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        checkAvailableConnection();
    }
    
    void checkAvailableConnection()
    {
	    ConnectivityManager connMgr = (ConnectivityManager)
	    this.getSystemService(Context.CONNECTIVITY_SERVICE);	
	
	    final android.net.NetworkInfo wifi =
	    connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);	
	
	    final android.net.NetworkInfo mobile =
	    connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
	
	    if( wifi.isAvailable() ){
	    	Toast.makeText(this, "Wifi Available" , Toast.LENGTH_LONG).show();
	    }
	    else if( mobile.isAvailable() ){
	    	Toast.makeText(this, "3G Available" , Toast.LENGTH_LONG).show();
	    }
	    else{	
	    	Toast.makeText(this, "No Network Available" , Toast.LENGTH_LONG).show();
	    }
    }
}

How to download a file to your android device from a remote server with a custom progressbar showing progress?

Actually this is really simple.

I have already posted an example for how to download a file in this post.

How to Download an image in ANDROID programatically?

This is another one little different with a progressbar included.

Previously I have shown three other methods to upload files to a server.
Check these posts to refer this.

1. Uploading audio, video or image files from Android to server
2. How to Upload Multiple files in one request along with other string parameters in android?
3. ANDROID – Upload an image to a server.

OK We will start now.
This is the file we are going to download.

http://coderzheaven.com/sample_folder/sample_file.png

First we will create a simple layout with a button that will download a file on it’s onClick event.

This is the contents of 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:id="@+id/tv1"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Downloading File with ProgressBar Demo From Coderzheaven"
    />
<Button 
	android:id="@+id/b1"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Download File"
    android:onClick="downloadFile"
    />
</LinearLayout>

download a file to your android device from a remote server with a custom progressbar showing progress

Now we will write the java code to download the file.
Copy this code to your main java file. My file is named “DownloadFileDemo1.java”.

package com.coderzheaven.pack;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class DownloadFileDemo1 extends Activity {
	
    ProgressBar pb;
    Dialog dialog;
    int downloadedSize = 0;
    int totalSize = 0;
    TextView cur_val;
    String dwnload_file_path = "http://coderzheaven.com/sample_folder/sample_file.png";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        Button b = (Button) findViewById(R.id.b1);
        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				 showProgress(dwnload_file_path);
			        
			        new Thread(new Runnable() {
			            public void run() {
			            	 downloadFile();
			            }
			          }).start();
			}
		});
    }
  	    
    void downloadFile(){
    	
    	try {
    		URL url = new URL(dwnload_file_path);
    		HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    		urlConnection.setRequestMethod("GET");
    		urlConnection.setDoOutput(true);

    		//connect
    		urlConnection.connect();

    		//set the path where we want to save the file    		
    		File SDCardRoot = Environment.getExternalStorageDirectory(); 
    		//create a new file, to save the downloaded file 
    		File file = new File(SDCardRoot,"downloaded_file.png");
 
    		FileOutputStream fileOutput = new FileOutputStream(file);

    		//Stream used for reading the data from the internet
    		InputStream inputStream = urlConnection.getInputStream();

    		//this is the total size of the file which we are downloading
    		totalSize = urlConnection.getContentLength();

    		runOnUiThread(new Runnable() {
			    public void run() {
			    	pb.setMax(totalSize);
			    }			    
			});
    		
    		//create a buffer...
    		byte[] buffer = new byte[1024];
    		int bufferLength = 0;

    		while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
    			fileOutput.write(buffer, 0, bufferLength);
    			downloadedSize += bufferLength;
    			// update the progressbar //
    			runOnUiThread(new Runnable() {
    			    public void run() {
    			    	pb.setProgress(downloadedSize);
    			    	float per = ((float)downloadedSize/totalSize) * 100;
    			    	cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
    			    }
    			});
    		}
    		//close the output stream when complete //
    		fileOutput.close();
    		runOnUiThread(new Runnable() {
			    public void run() {
			    	// pb.dismiss(); // if you want close it..
			    }
			});    		
    	
    	} catch (final MalformedURLException e) {
    		showError("Error : MalformedURLException " + e);  		
    		e.printStackTrace();
    	} catch (final IOException e) {
    		showError("Error : IOException " + e);  		
    		e.printStackTrace();
    	}
    	catch (final Exception e) {
    		showError("Error : Please check your internet connection " + e);
    	}    	
    }
    
    void showError(final String err){
    	runOnUiThread(new Runnable() {
		    public void run() {
		    	Toast.makeText(DownloadFileDemo1.this, err, Toast.LENGTH_LONG).show();
		    }
		});
    }
    
    void showProgress(String file_path){
    	dialog = new Dialog(DownloadFileDemo1.this);
    	dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    	dialog.setContentView(R.layout.myprogressdialog);
    	dialog.setTitle("Download Progress");

    	TextView text = (TextView) dialog.findViewById(R.id.tv1);
    	text.setText("Downloading file from ... " + file_path);
    	cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
    	cur_val.setText("Starting download...");
    	dialog.show();
    	
    	pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
    	pb.setProgress(0);
    	pb.setProgressDrawable(getResources().getDrawable(R.drawable.green_progress));  
    }
}

OK now we have to make a layout for the progressdialog since it is a custom one.

create a new xml file inside res/layout folder and name it myprogressdialog.xml and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/layout_root"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10dp"
              >
    
    <TextView 
    	android:id="@+id/tv1"
      	android:layout_width="wrap_content"
      	android:layout_height="wrap_content"
      	android:textColor="#FFF"
      	android:text="hello"
      	android:textStyle="bold"  
    />
       
    <TextView 
    	android:id="@+id/cur_pg_tv"
      	android:layout_width="wrap_content"
      	android:layout_height="wrap_content"
      	android:textColor="#0F0"
      	android:text="hello"
      	android:layout_marginTop="5dp"
      	android:textStyle="bold|italic"    />       
    <ProgressBar   
		android:id="@+id/progress_bar"  
		android:layout_width="fill_parent"  
		android:layout_height="wrap_content"  
		android:progress="0"  
		android:layout_marginTop="5dp"
		android:layout_marginBottom="10dp"
		style="?android:attr/progressBarStyleHorizontal"  
		android:maxHeight="10dip"  
		android:minHeight="10dip"  
	/>  
	
</LinearLayout>

Now create a new file inside res/drawable folder and name it “green_progress.xml” and copy this code into it.
This xml is used for giving a green color to the progressbar.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@android:id/background">
    <shape>
        <corners android:radius="5dip" />
        <gradient
                android:startColor="#ff9d9e9d"
                android:centerColor="#ff5a5d5a"
                android:centerY="0.75"
                android:endColor="#ff747674"
                android:angle="270"
        />
    </shape>
</item>
<item
    android:id="@android:id/progress">
    <clip>
        <shape>
            <corners
                android:radius="5dip" />
            <gradient
                	android:startColor="@color/greenStart"
                    android:centerColor="@color/greenMid"
                    android:centerY="0.75"
                    android:endColor="@color/greenEnd"
                    android:angle="270"
            />
        </shape>
    </clip>
</item>
</layer-list>

OK now we have customized the progressbar.

This line sets the progressbar to green color.

pb.setProgressDrawable(getResources().getDrawable(R.drawable.green_progress));

The showProgress() method inside the java code will invoke the custom progressbar.

Now the main thing..
Dont forget to add the permissions to the manifest file.

These two are the permissions we need .


This is the AndroidManifest file for this example.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.coderzheaven.pack"
      android:versionCode="1"
      android:versionName="1.0">
      
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".DownloadFileDemo1"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

download a file to your android device from a remote server with a custom progressbar showing progress

download a file to your android device from a remote server with a custom progressbar showing progress

download a file to your android device from a remote server with a custom progressbar showing progress

The file will be downloaded to the sdcard root. Please go to the DDMS perpective and open the File Explorer and expand the SDCARD to see the downloaded file.

Check the screen shot..

download a file to your android device from a remote server with a custom progressbar showing progress

Download.

How to upload an image from Android device to server? – Method 4

Hello all….

This post is also about uploading an image to server from your android device.
Previously I have shown three other methods to upload an image to a server.
Check these posts to refer this.

1. Uploading audio, video or image files from Android to server
2. How to Upload Multiple files in one request along with other string parameters in android?
3. ANDROID – Upload an image to a server.

These are for downloading files from the server.

1. How to Download an image in ANDROID programatically?
2. How to download a file to your android device from a remote server with a custom progressbar showing progress?

Now we will see another method.

Before that I will show my sdcard contents. I have some images in my sdcard of which I am uploading one.
check this post to how to put files inside your emulator or device from eclipse.
How to add files like images inside your emulator in ANDROID?

First create a fresh project and name it “UploadImageDemo”.

Now this the layout file I am using for the main activity. (main.xml).
This contains a button which onclick will upload the file.

<?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"
    >
	<Button  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="Upload File"
	    android:id="@+id/but"
    />
    
	<TextView  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="@string/hello"
	    android:id="@+id/tv"
	    android:textColor="#00FF00"
	    android:textStyle="bold"
    />
 </LinearLayout>

Now the java code.
UploadImageDemo.java

package com.coderzheaven.pack;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class UploadImageDemo extends Activity {
   
	TextView tv;
	Button b;
	int serverResponseCode = 0;
	ProgressDialog dialog = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        b = (Button)findViewById(R.id.but);
        tv = (TextView)findViewById(R.id.tv);
        tv.setText("Uploading file path :- '/sdcard/android_1.png'");
        
        b.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				dialog = ProgressDialog.show(UploadImageDemo.this, "", "Uploading file...", true);
				 new Thread(new Runnable() {
					    public void run() {
					    	 runOnUiThread(new Runnable() {
				    			    public void run() {
				    			    	tv.setText("uploading started.....");
				    			    }
				    			});					     
					   	 int response= uploadFile("/sdcard/android_1.png");
				         System.out.println("RES : " + response);					      
					    }
					  }).start();		 
				}
		});
    }
    
    public int uploadFile(String sourceFileUri) {
    	  String upLoadServerUri = "http://10.0.2.2/upload_test/upload_media_test.php";
    	  String fileName = sourceFileUri;

    	  HttpURLConnection conn = null;
    	  DataOutputStream dos = null;  
    	  String lineEnd = "\r\n";
    	  String twoHyphens = "--";
    	  String boundary = "*****";
    	  int bytesRead, bytesAvailable, bufferSize;
    	  byte[] buffer;
    	  int maxBufferSize = 1 * 1024 * 1024; 
    	  File sourceFile = new File(sourceFileUri); 
    	  if (!sourceFile.isFile()) {
    	   Log.e("uploadFile", "Source File Does not exist");
    	   return 0;
    	  }
	    	  try { // open a URL connection to the Servlet
	    	   FileInputStream fileInputStream = new FileInputStream(sourceFile);
	    	   URL url = new URL(upLoadServerUri);
	    	   conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
	    	   conn.setDoInput(true); // Allow Inputs
	    	   conn.setDoOutput(true); // Allow Outputs
	    	   conn.setUseCaches(false); // Don't use a Cached Copy
	    	   conn.setRequestMethod("POST");
	    	   conn.setRequestProperty("Connection", "Keep-Alive");
	    	   conn.setRequestProperty("ENCTYPE", "multipart/form-data");
	    	   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
	    	   conn.setRequestProperty("uploaded_file", fileName); 
	    	   dos = new DataOutputStream(conn.getOutputStream());
	
	    	   dos.writeBytes(twoHyphens + boundary + lineEnd); 
	    	   dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
	    	   dos.writeBytes(lineEnd);
	
	    	   bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size
	
	    	   bufferSize = Math.min(bytesAvailable, maxBufferSize);
	    	   buffer = new byte[bufferSize];
	
	    	   // read file and write it into form...
	    	   bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
	    	    
	    	   while (bytesRead > 0) {
	    	     dos.write(buffer, 0, bufferSize);
	    	     bytesAvailable = fileInputStream.available();
	    	     bufferSize = Math.min(bytesAvailable, maxBufferSize);
	    	     bytesRead = fileInputStream.read(buffer, 0, bufferSize);	    	    
	    	    }
	
	    	   // send multipart form data necesssary after file data...
	    	   dos.writeBytes(lineEnd);
	    	   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
	
	    	   // Responses from the server (code and message)
	    	   serverResponseCode = conn.getResponseCode();
	    	   String serverResponseMessage = conn.getResponseMessage();
	    	   
	    	   Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
	    	   if(serverResponseCode == 200){
	    		   runOnUiThread(new Runnable() {
	    			    public void run() {
	    			    	tv.setText("File Upload Completed.");
	    			    	Toast.makeText(UploadImageDemo.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
	    			    }
	    			});	    		   
	    	   }	
	    	  
	    	   //close the streams //
	    	   fileInputStream.close();
	    	   dos.flush();
	    	   dos.close();
	    	   
	      } catch (MalformedURLException ex) {  
	    	  dialog.dismiss();  
	    	  ex.printStackTrace();
	    	  Toast.makeText(UploadImageDemo.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
	    	  Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
    	  } catch (Exception e) {
    		  dialog.dismiss();  
    		  e.printStackTrace();
    		  Toast.makeText(UploadImageDemo.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
    		  Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);  
    	  }
    	  dialog.dismiss();    	  
    	  return serverResponseCode;  
    	 } 
}

This is the manifest file.
Make sure to add the internet permission in the AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.coderzheaven.pack"
      android:versionCode="1"
      android:versionName="1.0">
      
    <uses-permission android:name="android.permission.INTERNET"/>    
    
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".UploadImageDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

OK Our Android part is over.

Now we will go to the server part.
I am using xampp in Windows. So my code goes to the htdocs folder inside my xampp folder.
ie. I am working on localhost, however you can replace the url with your own server name.
Inside the htdocs folder create a folder named “upload_test” and inside that create a file named “upload_media_test.php” and copy this code into it.

So the path is like this.

C:/xampp/htdocs/upload_test/upload_media_test.php.

<?php
$target_path1 = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) {
    echo "The first file ".  basename( $_FILES['uploaded_file']['name']).
    " has been uploaded.";
} else{
    echo "There was an error uploading the file, please try again!";
    echo "filename: " .  basename( $_FILES['uploaded_file']['name']);
    echo "target_path: " .$target_path1;
}
?>


I am uploading the file into a folder named “uploads” which is in the same directory as the above php code.
So please create a “uploads” folder before running this code.

Also before running this code make sure that
1. Your server is running.
2. Your serverpath is correct.
3. The folder has correct write permissions.
4. You have the file to upload the file in the sdcard.
check this post to how to put files inside your emulator or device from eclipse.
How to add files like images inside your emulator in ANDROID?

OK now run the application and check the upload directory.
If the server response the ‘200’, your file has been uploaded.


Please leave your valuable comments on this post.

How to read and write a text file that is stored in your application sandbox in ANDROID?

Hi all…..

In this post I will show you how to read a text file in ANDOID.
Let your file is in the your application sandbox of your ANDOID project, i.e the file’s location is /data/data/your_package_name folder.
To view this folder -> open File Explorer and expand each folder.
For this example to work first push te file into this folder, because I am not creating it now.
The file is named “myfile.txt”

This example reads the file line by line using readLine() function till the end of the file. Here your need two classes named “InputStreamReader” and “BufferedReader”. For writing into the file you need “OutputStreamReader” class. The result is displayed in a Toast. Make sure you notice it.

The following is the code for reading the text file………

String     res  =    null;
try {

	   InputStream       in = openFileInput("myfile.txt");

	   if (in != null) {
	    // prepare the file for reading
	     InputStreamReader input = new InputStreamReader(in);
	     BufferedReader buffreader = new BufferedReader(input);

	      res = "";
	      while (( line = buffreader.readLine()) != null) {
	      	res += line;
	      }
	      in.close();
	      Toast.makeText(getApplicationContext(),"File Contents ==> " + res,Toast.LENGTH_SHORT).show();
          }else{
	    }

} catch(Exception e){
       Toast.makeText(getApplicationContext(),     e.toString() +   e.getMessage(),Toast.LENGTH_SHORT).show();
}

Want More then

Follow this link

How to read and write files to SDCARD and application SandBox in Android – A complete example?

Please leave your comments on this post.

Fling Gesture in Android

On implementing the onGestureListener you can get the events like

Fling
LongPress
Scroll
ShowPress
SingleTap

Its really simple, otherwise we have to calculate the distance between the touchdown and touchup event to check a fling event is happened or not.


import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater.Filter;
import android.view.View.OnClickListener;
import android.widget.Toast;

public  class FlingActivity extends Activity implements OnGestureListener
{
	private GestureDetector gestureScanner;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		gestureScanner = new GestureDetector(this);
		setContentView(R.layout.main);
	}

	@Override
	public boolean onTouchEvent(MotionEvent me)
	{
		return gestureScanner.onTouchEvent(me);
	}

	public boolean onDown(MotionEvent e)
	{
		Toast.makeText(FlingActivity.this, "Motion Event", Toast.LENGTH_LONG).show();
		return false;
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
	{
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

        Toast.makeText(FlingActivity.this, "fling Event ", Toast.LENGTH_LONG).show();
        return true;
	}

	public void onLongPress(MotionEvent e)
	{
		Toast.makeText(FlingActivity.this, "Long-Press event", Toast.LENGTH_LONG).show();
	}

	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
	{
		Toast.makeText(FlingActivity.this, "Scroll event", Toast.LENGTH_LONG).show();
		return false;
	}

	public void onShowPress(MotionEvent e)
	{
		Toast.makeText(FlingActivity.this, "Show-Press event", Toast.LENGTH_LONG).show();
	}

	public boolean onSingleTapUp(MotionEvent e)
	{
		Toast.makeText(FlingActivity.this, "Single-Tap event ", Toast.LENGTH_LONG).show();
		return true;
	}
}

Date and TimePicker in ANDROID.

The following code simply allows you to select a date and time using the datepicker and timepicker in ANDROID.

package AndroidDatePicker.pack;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;

public class AndroidDatePicker extends Activity {

 private int myYear, myMonth, myDay, myHour, myMinute;
 static final int ID_DATEPICKER = 0;
 static final int ID_TIMEPICKER = 1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button datePickerButton = (Button)findViewById(R.id.datepickerbutton);
        Button timePickerButton = (Button)findViewById(R.id.timepickerbutton);
        datePickerButton.setOnClickListener(datePickerButtonOnClickListener);
        timePickerButton.setOnClickListener(timePickerButtonOnClickListener);
    }

    private Button.OnClickListener datePickerButtonOnClickListener
     = new Button.OnClickListener(){

   @Override
   public void onClick(View v) {

          final Calendar c = Calendar.getInstance();
          myYear = c.get(Calendar.YEAR);
          myMonth = c.get(Calendar.MONTH);
          myDay = c.get(Calendar.DAY_OF_MONTH);
          showDialog(ID_DATEPICKER);
   }
    };

    private Button.OnClickListener timePickerButtonOnClickListener
  = new Button.OnClickListener(){

   @Override
   public void onClick(View v) {

          final Calendar c = Calendar.getInstance();
          myHour = c.get(Calendar.HOUR_OF_DAY);
          myMinute = c.get(Calendar.MINUTE);
          showDialog(ID_TIMEPICKER);
   }
    };

	 @Override
	 protected Dialog onCreateDialog(int id) {

	        switch(id){
	         case ID_DATEPICKER:
	          Toast.makeText(AndroidDatePicker.this,
	            "- onCreateDialog(ID_DATEPICKER) -",
	            Toast.LENGTH_LONG).show();
	          return new DatePickerDialog(this,
	            myDateSetListener,
	            myYear, myMonth, myDay);
	         case ID_TIMEPICKER:
	          Toast.makeText(AndroidDatePicker.this,
	            "- onCreateDialog(ID_TIMEPICKER) -",
	            Toast.LENGTH_LONG).show();
	          return new TimePickerDialog(this,
	            myTimeSetListener,
	            myHour, myMinute, false);
	         default:
	          return null;

	  }
	 }

	 private DatePickerDialog.OnDateSetListener myDateSetListener
	        = new DatePickerDialog.OnDateSetListener(){

	         @Override
	         public void onDateSet(DatePicker view, int year,
	           int monthOfYear, int dayOfMonth) {
	          String date = "Year: " + String.valueOf(year) + "n"
	           + "Month: " + String.valueOf(monthOfYear+1) + "n"
	           + "Day: " + String.valueOf(dayOfMonth);
	          Toast.makeText(AndroidDatePicker.this, date,
	            Toast.LENGTH_LONG).show();
	         }
	 };

	 private TimePickerDialog.OnTimeSetListener myTimeSetListener
	        = new TimePickerDialog.OnTimeSetListener(){
	         @Override
	         public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

	          String time = "Hour: " + String.valueOf(hourOfDay) + "n"
	           + "Minute: " + String.valueOf(minute);
	          Toast.makeText(AndroidDatePicker.this, time,
	            Toast.LENGTH_LONG).show();
	         }
	 };
}

Copying an image to another in ANDROID.

Here is a simple example to copy an image to another image file in ANDROID.
In this example a button click will open the gallery and after that it will be copied to another image file.
You have to check the File-explorer to find the file.

This is the java code for doing it.

package pack.coderzheaven;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class CopyingImageFromGalleryDemo extends Activity {

	String mSelectedImagePath;
	private static final int SELECT_IMAGE = 1;
	Button b;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b = (Button)findViewById(R.id.Button01);
        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				imageFromGallery();
			}
		});
    }

    /*** this function opens the gallery and gets the image ***/
    public void imageFromGallery() {
    	Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_IMAGE);
    }

    /* After opening gallery control comes here */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	  super.onActivityResult(requestCode, resultCode, data);
    	  if (resultCode == RESULT_OK) {
    	    switch(requestCode) {
	    	    case SELECT_IMAGE:
	    	        mSelectedImagePath = getPath(data.getData());
	    	        System.out.println("mSelectedImagePath : " + mSelectedImagePath);
	    	        try {
	    	    		File sd = Environment.getExternalStorageDirectory();
	    	    		if (sd.canWrite()) {
	    	    			System.out.println("(sd.canWrite()) = " + (sd.canWrite()));
	    	    		    String destinationImagePath= "/file.jpg";	// this is the destination image path.
	    	    		    File source = new File(mSelectedImagePath );
	    	    		    File destination= new File(sd, destinationImagePath);
	    	    		    if (source.exists()) {
	    	    		        FileChannel src = new FileInputStream(source).getChannel();
	    	    		        FileChannel dst = new FileOutputStream(destination).getChannel();
	    	    		        dst.transferFrom(src, 0, src.size());		// copy the first file to second.....
	    	    		        src.close();
	    	    		        dst.close();
	    	    		        Toast.makeText(getApplicationContext(), "Check the copy of the image in the same path as the gallery image. File is name file.jpg", Toast.LENGTH_LONG).show();
	    	    		    }
	    	    		}else{
	    	    			Toast.makeText(getApplicationContext(), "SDCARD Not writable.", Toast.LENGTH_LONG).show();
	    	    		}
	    	    	}catch (Exception e) {
	    	    		System.out.println("Error :" + e.getMessage());
	    	    	}
	    	        break;
    	  }
    	}
    }

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		startManagingCursor(cursor);
		int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}
}

here is the main.xml file

<?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:text="Gallery"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
</LinearLayout>

Then the strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello"><b>Copying an Image to another Demo From CoderzHeaven</b></string>
    <string name="app_name">Copy an Image to another</string>
</resources>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".CopyingImageFromGalleryDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
Copy Image Demo

Copy Image Demo

Copy Image Demo

Copy Image Demo

Change the name of the file as you like.
Enjoy…………..

Please leave your comments and click on the +1 button above.

Switch Images in ANDROID.

Hi all ……..

Ofter we have trouble with loading continous images in ANDROID from our application directory.
The reason is that all resources have a unique resource ID which we need to get to load these resources.
The following example shows how to get these unique identifier from the “path” of the resource.
For example Here I have seven images with names sample_0.png, sample_1.png to sample_7.png.
By using
imgID = getResources().getIdentifier(“sample_”+num, “drawable”, “com.switchImages”);
I convert the path to it’s identifier.
Note that all these images need to be in “drawable” folder.
Even if your folder name is “drawable-hdpi” also then give only “drawable” and third parameter the package name.Just copy and paste the following code to your java file.
Make sure that you have all the images in the resource.

package com.switchImages;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class Switch extends Activity {
    ImageView img;
    Button preview;
    int num = 0;
    public int imgID = 0;

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

        img = (ImageView)findViewById(R.id.imageView);
        preview = (Button)findViewById(R.id.Prev);

        try
             {
                 imgID = getResources().getIdentifier("sample_"+num, "drawable", "com.switchImages");
                         img.setImageResource(imgID);
             }catch(Exception e){
                        Toast.makeText(Switch.this,e.getMessage() , Toast.LENGTH_SHORT).show();
             }

             preview.setOnClickListener(new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                                 imgID = getID();
                                                switchImage(imgID);
                                    }
                        });
    }

    public void switchImage(int ID){
             try
                         {
                                     ID = getResources().getIdentifier("sample_"+num, "drawable", "com.switchImages");
                                     img.setImageResource(ID);
                         }catch(Exception e){
                                    Toast.makeText(Switch.this,e.getMessage() , Toast.LENGTH_SHORT).show();
                         }
    }

    public int getID(){
             int imgID = 0;
             num++;
             if(num > 7) num = 0;
             try
             {
                        imgID = getResources().getIdentifier("sample_"+num, "drawable", "com.switchImages");
             }catch(Exception e){
                        Toast.makeText(Switch.this,e.getMessage(), Toast.LENGTH_SHORT).show();
             }
             return imgID;
    }
}

Please leave your valuable comments if this post was useful…..

Using WebView to call a function in android java code or How to use a WebViewClient in android?

Hello everyone

Today I will explain how will you call a function that is defined inside the java android code from a webview.
For this we need to add a webviewclient in android for the WebView we are adding in the xml.

Then we have to register the webviewclient with the WebView we are creating using this method.

 myWebView.setWebViewClient(new MyWebViewClient());

Now we will start….

Create a new project and name it WebViewDemo.

Now in the main.xml copy this code.
This file contains the webview only.

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

Now create a file named test.html inside the assets folder and copy this code into it. This is the html file that we are loading into the webview.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN"
    "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">
<html>
<body>
<a href="http://www.coderzheaven.com">CoderzHeaven</a>
<input type="button" value="Click Me" onClick="showAndroidToast('Hello CoderzHeaven!')" />
<script type="text/javascript">
    function showAndroidToast(toast) {
    	Android.showToast(toast);
    }
</script>
</body>
</html>

Now in the java code refer the webview and load the html file

WebView myWebView;
 myWebView = (WebView) findViewById(R.id.webview);
 myWebView.loadUrl("file:///android_asset/test.html");

Now enable the javascript by calling this function

 WebSettings webSettings = myWebView.getSettings();
 webSettings.setJavaScriptEnabled(true);

Now we have to add the javascript interface for listening to the javascript functions that we define in the webview html file.

  myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

// outside oncreate
 public class JavaScriptInterface {
        Context mContext;

        /** Instantiate the interface and set the context */
        JavaScriptInterface(Context c) {
            mContext = c;
        }

        /** Show a toast from the web page */
        public void showToast(String toast) {
            Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
            startActivity(new Intent(WebViewDemo.this, WebViewDemo.class));
        }
    }

Now create a webview client for listening to the browser activities and doing specific function.

 myWebView.setWebViewClient(new MyWebViewClient());

 private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals("www.coderzheaven.com")) {
               	Toast.makeText(getApplicationContext(), "www.coderzheaven.com", Toast.LENGTH_SHORT).show();
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
    }

Now we listen to the backbutton.

 @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the BACK key and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

Now the project is over . Now run and see the result.
Here is the full java code for this example

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class WebViewDemo extends Activity {

	WebView myWebView;
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        myWebView = (WebView) findViewById(R.id.webview);
        myWebView.loadUrl("file:///android_asset/test.html");
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

       // myWebView.setWebViewClient(new WebViewClient());
        myWebView.setWebViewClient(new MyWebViewClient());
    }

    public class JavaScriptInterface {
        Context mContext;

        /** Instantiate the interface and set the context */
        JavaScriptInterface(Context c) {
            mContext = c;
        }

        /** Show a toast from the web page */
        public void showToast(String toast) {
            Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
            startActivity(new Intent(WebViewDemo.this, WebViewDemo.class));
        }
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals("www.google.com")) {
                // This is my web site, so do not override; let my WebView load the page
            	Toast.makeText(getApplicationContext(), "www.google.com", Toast.LENGTH_SHORT).show();
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the BACK key and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        // If it wasn't the BACK key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }
}
Calling an android function from javascript

Calling an android function from javascript

please leave your valuable comments if this post was useful.

How to show a sliding window from below in Android?

Hello everyone,

I have already showed you how to use a SlidingViewer to create a slidingWindow. Today I will show another way to create such a window with the help of animation.

Please check one of my previous posts to do this in another way.

How to show a sliding window from below in Android?

Check this new One using Navigation Drawer

First Create a file named “SlidingPanel.java” and copy this code into it.

package com.pack.coderzheaven;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.widget.LinearLayout;

public class SlidingPanel extends LinearLayout
{
	private Paint	innerPaint, borderPaint ;

	public SlidingPanel(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public SlidingPanel(Context context) {
		super(context);
		init();
	}

	private void init() {
		innerPaint = new Paint();
		innerPaint.setARGB(100, 25, 25, 75); //gray
		innerPaint.setAntiAlias(true);

		borderPaint = new Paint();
		borderPaint.setARGB(255, 255, 255, 255);
		borderPaint.setAntiAlias(true);
		borderPaint.setStyle(Style.STROKE);
		borderPaint.setStrokeWidth(5);
	}

	public void setInnerPaint(Paint innerPaint) {
		this.innerPaint = innerPaint;
	}

	public void setBorderPaint(Paint borderPaint) {
		this.borderPaint = borderPaint;
	}

    @Override
    protected void dispatchDraw(Canvas canvas) {

    	RectF drawRect = new RectF();
    	drawRect.set(0,0, getMeasuredWidth(), getMeasuredHeight());

    	canvas.drawRoundRect(drawRect, 5, 5, innerPaint);
		canvas.drawRoundRect(drawRect, 5, 5, borderPaint);

		super.dispatchDraw(canvas);
    }
}

This is the layout for the Panel window that comes up. Actually this java file creates gradiant only. No visual components are created with this code.

Now the main.xml, the place where “SlidingPanel ” is used.
Copy this code to your main.xml file

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

    <ImageButton
    		android:id="@+id/show_popup_button"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_gravity="left"
			android:background="@drawable/open"
	        />

	<com.pack.coderzheaven.SlidingPanel
			android:id="@+id/popup_window"
    	    android:layout_width="fill_parent"
        	android:layout_height="wrap_content"
        	android:orientation="vertical"
        	android:gravity="left"
        	android:padding="1px"
        	android:background="@drawable/white">

		<LinearLayout	xmlns:android="http://schemas.android.com/apk/res/android"
					    android:orientation="horizontal"
					    android:layout_width="fill_parent"
					    android:layout_height="fill_parent"
					    android:background="@drawable/gradient_bar">

			<TextView
					android:id="@+id/site_name"
			        android:layout_width="wrap_content"
			        android:layout_height="wrap_content"
	        		android:textStyle="bold"
	        		android:textSize="16px"
	        		android:text="CoderzHeaven"
	        		android:layout_gravity="center"
	        		android:layout_alignParentLeft="true"
	        		android:textColor="@drawable/black"
	        		android:layout_weight="1"
	        		android:layout_marginLeft="5px"/>

			<ImageButton android:id="@+id/hide_popup_button"
			        android:layout_width="wrap_content"
			        android:layout_height="wrap_content"
	    			android:layout_alignParentRight="true"
			        android:layout_centerInParent="true"
	    			android:layout_margin="2px"
	    			android:layout_gravity="center"
			        android:background="@drawable/close"/>

		</LinearLayout>

	    <TextView	android:id="@+id/site_description"
			        android:layout_width="wrap_content"
			        android:layout_height="wrap_content"
				android:textColor="@drawable/black"
				android:textStyle="italic"
	        		android:layout_margin="5px"/>

	</com.pack.coderzheaven.SlidingPanel>

</LinearLayout>

Make sure you have all the resources(images) for the xml.

Now create a folder named “anim” inside “res” folder and create an xml named “popup_hide.xml” and another one named “popup_show.xml”
popup_hide.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
	<translate android:fromYDelta="0" android:toYDelta="100%p" android:duration="750"/>
</set>

popup_show.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
	<translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="750"/>
</set>

These two files create the animation for the window.

Now create file named gradient_bar.xml in the “res/drawable” folder and copy this code into it.
This is applied as background for the title in the sliding window.
You can edit the animation files to change the duration of the window coming.

Now the main java file
The file is named “PopUpAnimationDemo.java

package com.pack.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.TextView;

public class PopUpAnimationDemo extends Activity {

	private Animation animShow, animHide;

	@Override
	public void onCreate(Bundle icicle) {

        super.onCreate(icicle);
        setContentView(R.layout.main);
        initPopup();
    }

    private void initPopup() {

    	final SlidingPanel popup = (SlidingPanel) findViewById(R.id.popup_window);

    	// Hide the popup initially.....
    	popup.setVisibility(View.GONE);

    	animShow = AnimationUtils.loadAnimation( this, R.anim.popup_show);
    	animHide = AnimationUtils.loadAnimation( this, R.anim.popup_hide);

    	final ImageButton   showButton = (ImageButton) findViewById(R.id.show_popup_button);
    	final ImageButton   hideButton = (ImageButton) findViewById(R.id.hide_popup_button);
    	showButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				popup.setVisibility(View.VISIBLE);
				popup.startAnimation( animShow );
				showButton.setEnabled(false);
				hideButton.setEnabled(true);
        }});

        hideButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				popup.startAnimation( animHide );
				showButton.setEnabled(true);
				hideButton.setEnabled(false);
				popup.setVisibility(View.GONE);
        }});

    	final TextView locationName = (TextView) findViewById(R.id.site_name);
        final TextView locationDescription = (TextView) findViewById(R.id.site_description);

        locationName.setText("CoderzHeaven");
        locationDescription.setText("Heaven of all working codes"
        							+ " A place where you can ask, share & even shout for code! Let’s share a wide range of technology here." +
        	  						" From this site you will get a lot of working examples in your favorite programming languages!." +
        	  						" Always remember we are only one comment away from you… Let’s shorten the distance between your doubts and your answers…");

	}
}

Here is the Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">Sliding Window Demo</string>
</resources>

Now create a file named colors.xml in the res/values folder and copy this into it

<?xml version="1.0" encoding="utf-8"?>
<resources>
        <string name="select_Category">Select Category</string>
	<drawable name="white">#ffffff</drawable>
	<drawable name="black">#000000</drawable>
	<drawable name="green">#347C2C</drawable>
	<drawable name="pink">#FF00FF</drawable>
	<drawable name="violet">#a020f0</drawable>
	<drawable name="grey">#778899</drawable>
	<drawable name="red">#C11B17</drawable>
	<drawable name="yellow">#FFFF8C</drawable>
	<drawable name="PowderBlue">#b0e0e6</drawable>
	<drawable name="brown">#2F1700</drawable>
	<drawable name="Hotpink">#7D2252</drawable>
	<drawable name="darkgrey">#606060</drawable>
</resources>

Click on the ImagButton to open the sliding Window

Sliding Window

Sliding Window

Sliding Window

Sliding Window

Download the whole project from here

Please don’t forget to add your valuable comments on this post, because comments are our encouragements for future posts.