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 call a function using a String in Android and also pass parameters along with it.

Hi all …

Today’s post is all about calling functions using Simple Strings.

Here we will do two things.

1. Call a function without parameters.
2. Call a function with parameters.

String to functions

String to functions

This is the class which contains the functions that we are going to call using “simple Strings”.


package com.coderzheaven.Stringtofunction;

public class Test {

	public String functionWithParams(String p1, String p2) {
		return p1 + ", " + p2;
	}

	public String noParamsFunction() {
		return "Return from noParamsFunction";
	}

}

Now this is the main activity that calls these functions.

package com.coderzheaven.Stringtofunction;

import java.lang.reflect.Method;

import android.app.Activity;
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;

public class MainActivity extends Activity {

	String TAG = getClass().getSimpleName();
	TextView tv;
	
	@SuppressWarnings("rawtypes")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		final Object paramsObj[] = { "Hello", "CoderzHeaven" };
		final Class[] class_params = { String.class, String.class };
		final String class_name = getPackageName() + ".Test";

		Button b1 = (Button) findViewById(R.id.button1);
		b1.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				/** This is the function without parameters in Test.java **/
				callFunctionWithoutParameter(class_name, "noParamsFunction");
			}
		});

		Button b2 = (Button) findViewById(R.id.button2);
		b2.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				/** This is the function with two parameters in Test.java **/
				callFunctionWithParams(class_name, "functionWithParams",
						class_params, paramsObj);
			}
		});
		
		tv = (TextView)findViewById(R.id.tv);

	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	void callFunctionWithoutParameter(String class_name, String function_name) {
		try {
			Class c = Class.forName(class_name);
			Method m = c.getMethod(function_name);
			Object iClass = c.newInstance();
			String p = (String) m.invoke(iClass);
			Log.i(TAG, p);
			tv.setText("Result (Without Prameters) : " + p);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	void callFunctionWithParams(String aClass, String aMethod, Class[] params,
			Object[] args) {
		try {
			Class c = Class.forName(aClass);
			Method m = c.getDeclaredMethod(aMethod, params);
			Object i = c.newInstance();
			String p = (String) m.invoke(i, args);
			Log.i(TAG, p);
			tv.setText("Result (With Prameters) : " + p);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Now this is the layout that the mainactivity uses.

<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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Call function without parameters" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Call function with parameters" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/padding_medium"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />

</LinearLayout>

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.

Simplest Lazy Loading ListView Example in Android with data populated from a MySQL database using php.

Hello all…

You may have seen many implementations of Lazy Loading ListView.
Today I will show you my method to create Lazy Loading ListViews.

I dont know whether it can be any more simple than this.

In this I am using AsyncTask to download each image.

So we will start.

Here we have 6 classes.

1. MainPage – This is our main activity that loads the ListView.
2. GetDataFromDB – This class get the image urls and it’s description as a string from the DB server and return that string.
Then we will split that string to seperate the urls and description and then set it to listview.
3. MyCustomArrayAdapter – Custom adapter for the ListView.
4. Model _ this class creates the object to be set for the ListView for each row.
5. PbAndImage – This class has an imageView and ProgressBar to send to the Asynctask.
6. DownloadImageTask – This class Asynchronously downloads the image.

At last the PHP Script which simple echoes the string containing the URLS and description of the image.

Here is the PHP Script.

getImageUrlsAndDescription.php

<?php
// get these values from your DB.
echo 	"http://coderzheaven.com/sample_folder/android_1.png,ANDROID0 ## 
		http://coderzheaven.com/sample_folder/coderzheaven.png,ANDROID1 ## 
		http://coderzheaven.com/sample_folder/coderzheaven.png,ANDROID2 ## 
		http://coderzheaven.com/sample_folder/coderzheaven.png,ANDROID3 ## 
		http://coderzheaven.com/sample_folder/android_1.png,ANDROID4 ## 
		http://coderzheaven.com/sample_folder/coderzheaven.png,ANDROID5 ## 
		http://coderzheaven.com/sample_folder/coderzheaven.png,ANDROID6 ## 
		http://coderzheaven.com/sample_folder/android_1.png,ANDROID7 ## 
		http://coderzheaven.com/sample_folder/coderzheaven.png,ANDROID8 ## 

http://coderzheaven.com/sample_folder/coderzheaven.png,ANDROID9";

?>

So we will start.

MainPage.java


package com.coderzheaven.lazyloadinglistwithphpconnection;

import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public     class     MainPage    extends ListActivity {

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

		setContentView(R.   layout.    contacts_list);

		final List<Model> list = new ArrayList<Model>();
		
		/** This block is for getting the image url to download from the server **/
		final GetDataFromDB getvalues = new GetDataFromDB();
		
		final ProgressDialog dialog = ProgressDialog.show(MainPage.this,
				"", "Gettting values from DB", true);
		new    Thread   (new Runnable() {
			public void run() {
				String response = getvalues.getImageURLAndDesciptionFromDB();
				System.out.println("Response : " + response);
				
				dismissDialog(dialog);
				if (!response.equalsIgnoreCase("")) {
					if (!response.equalsIgnoreCase("error")) {
						dismissDialog(dialog);
						
						// Got the response, now split it to get the image Urls and description
						String all[] = response.split("##"); 
						for(int k = 0; k < all.length; k++){
							String urls_and_desc[] = all[k].split(","); //  urls_and_desc[0] contains image url and [1] -> description.
							list.add(get(urls_and_desc[1],urls_and_desc[0]));
						}
					}
					
				} else {
					dismissDialog(dialog);
				}
			}
		}).start();
		/*************************** GOT data from Server ********************************************/

		ArrayAdapter<Model> adapter = new MyCustomArrayAdapter(this, list);
		setListAdapter(adapter);
	}

	public void dismissDialog(final ProgressDialog dialog){
		runOnUiThread(new Runnable() {
			public void run() {
				dialog.dismiss();
			}
		});
	}
	private Model get(String s, String url) {
		return new Model(s, url);
	}

}

GetDataFromDB.java

package com.coderzheaven.lazyloadinglistwithphpconnection;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class GetDataFromDB {

	public String getImageURLAndDesciptionFromDB() {
		try {

			HttpPost httppost;
			HttpClient httpclient;
			httpclient = new DefaultHttpClient();
			httppost = new HttpPost(
					"http://10.0.2.2/test/getImageUrlsAndDescription.php"); // change this to your URL.....
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			final String response = httpclient.execute(httppost,
					responseHandler);
			
			return response;

		} catch (Exception e) {
			System.out.println("ERROR : " + e.getMessage());
			return "error";
		}
	}
}

Model.java

package com.coderzheaven.lazyloadinglistwithphpconnection;

public class Model {
	 
    private String name;
    private String url;
    
    public Model(String name, String url) {
        this.name = name;
        this.url = url;
    }

	public String getName() {
		return name;
	}

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

	public String getURL() {
		return url;
	}

	public void setURL(String url) {
		this.url = url;
	}
}

MyCustomArrayAdapter.java

package com.coderzheaven.lazyloadinglistwithphpconnection;

import java.util.List;
import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MyCustomArrayAdapter extends ArrayAdapter<Model> {

	private final Activity context;
	private final List<Model> list;

	public MyCustomArrayAdapter(Activity context, List<Model> list) {
		super(context, R.layout.list_layout, list);
		this.context = context;
		this.list = list;
	}

	static class ViewHolder {
		protected TextView text;
		protected ImageView image;
		protected ProgressBar pb;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = null;
		if (convertView == null) {
			LayoutInflater inflator = context.getLayoutInflater();
			view = inflator.inflate(R.layout.list_layout, null);
			final ViewHolder viewHolder = new ViewHolder();
			viewHolder.text = (TextView) view.findViewById(R.id.label);
			viewHolder.text.setTextColor(Color.BLACK);
			viewHolder.image = (ImageView) view.findViewById(R.id.image);
			viewHolder.image.setVisibility(View.GONE);
			viewHolder.pb = (ProgressBar) view.findViewById(R.id.progressBar1);
			view.setTag(viewHolder);
		} else {
			view = convertView;
		}
		ViewHolder holder = (ViewHolder) view.getTag();
		holder.text.setText(list.get(position).getName());
		holder.image.setTag(list.get(position).getURL());
		holder.image.setId(position);
		PbAndImage pb_and_image = new PbAndImage();
		pb_and_image.setImg(holder.image);
		pb_and_image.setPb(holder.pb);
    	new DownloadImageTask().execute(pb_and_image);
		return view;
	}
}

PbAndImage.java

package com.coderzheaven.lazyloadinglistwithphpconnection;

import android.widget.ImageView;
import android.widget.ProgressBar;

public class PbAndImage {
	
	private ImageView img;
	private ProgressBar pb;

	public ImageView getImg() {
		return img;
	}

	public void setImg(ImageView img) {
		this.img = img;
	}

	public ProgressBar getPb() {
		return pb;
	}

	public void setPb(ProgressBar pb) {
		this.pb = pb;
	}

}

DownloadImageTask.java

package com.coderzheaven.lazyloadinglistwithphpconnection;

import java.io.InputStream;
import java.net.URL;
import com.coderzheaven.lazyloadinglistwithphpconnection.PbAndImage;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class DownloadImageTask extends AsyncTask<PbAndImage, Void, Bitmap> {

	ImageView imageView = null;
	ProgressBar pb = null;

	protected Bitmap doInBackground(PbAndImage... pb_and_images) {
		this.imageView = (ImageView)pb_and_images[0].getImg();
		this.pb = (ProgressBar)pb_and_images[0].getPb();
		return getBitmapDownloaded((String) imageView.getTag());
	}

	protected void onPostExecute(Bitmap result) {
		System.out.println("Downloaded " + imageView.getId());
		imageView.setVisibility(View.VISIBLE); 
		pb.setVisibility(View.GONE);  // hide the progressbar after downloading the image.
		imageView.setImageBitmap(result); //set the bitmap to the imageview.
	}

	/** This function downloads the image and returns the Bitmap **/
	private Bitmap getBitmapDownloaded(String url) {
		System.out.println("String URL " + url);
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream((InputStream) new URL(url)
					.getContent());
			bitmap = getResizedBitmap(bitmap, 50, 50);
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;
	}
	
	/** decodes image and scales it to reduce memory consumption **/
	public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // CREATE A MATRIX FOR THE MANIPULATION
        Matrix matrix = new Matrix();
        // RESIZE THE BIT MAP
        matrix.postScale(scaleWidth, scaleHeight);
        // RECREATE THE NEW BITMAP
        Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
        return resizedBitmap;
    }
}

And the Most important thing – DONT FORGET TO ADD THE INTERNET PERMISSION ON YOUR MANIFEST FILE.

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

These are the layout files.

contacts_list.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_margin="10dp" >
    
  <ListView
            android:id="@id/android:list"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:dividerHeight="1dp"
            android:cacheColorHint="#0000"
            android:clipToPadding="true"
            android:layout_margin="5dp"
            android:soundEffectsEnabled="true"
            android:scrollbars="none"
            android:layout_weight="1">
    </ListView>

</LinearLayout>

list_layout.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="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">
    
    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
     <ImageView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:layout_margin="10dp"
        android:id="@+id/image"
        android:contentDescription="@drawable/ic_launcher">        
    </ImageView>
    
    <TextView 
        android:text="@+id/label" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:id="@+id/label"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="5dp"
        android:textStyle="bold"
        android:textSize="20sp">        
    </TextView>
   
</LinearLayout>

Lazy Loading Image

Lazy Loading Image

Lazy Loading Image

Lazy Loading Image

Lazy Loading Image

Please leave your comments on this post.

Join the Forum discussion 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 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.

JSON IN ANDROID.

Complex JSON String parsing in ANDROID

http://www.coderzheaven.com/2011/06/10/complex-json-string-parsing-in-android/

Parsing JSON Object in ANDROID.

http://www.coderzheaven.com/2011/06/09/parsing-json-objects-in-android/

Get characters in a string – C Sharp/C#

Hi,

Sometimes you may need to get all the characters in a string using C Sharp/C#. The following code gives you an example of how to get or display all the characters of a given string.

using System;

class MainClass
{

  public static void Main()
  {
    string sampleString= "I Love Coding";


    for (int num = 0; num < sampleString.Length; num++)
    {
      Console.WriteLine("sampleString[" + num + "] = " + sampleString[num]);
    }

  }

}

Output:
sampleString[0] = I
sampleString[1] =
sampleString[2] = L
sampleString[3] = o
sampleString[4] = v
sampleString[5] = e
sampleString[6] =
sampleString[7] = C
sampleString[8] = o
sampleString[9] = d
sampleString[10] = i
sampleString[11] = n
sampleString[12] = g
:)

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…..

How to use Calendar in Android?

Hello all…….

In today’s post I will show you how to use Calendar in android. Actually it is really easy to use calendar in android.
For that android provides a calendar widget.
We use calendar class to show the Calendar widget.

Here is the java source code for this example.

package com.coderzheaven.pack;

import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;

public class CalendarTestDemo extends Activity {

	String arrayMonth[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"};
	Button date_button;
	static final int DATE_DIALOG_ID = 0;
	private int mYear;
	private int mMonth;
	private int mDay;
	EditText date_;

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

        date_ = (EditText)findViewById(R.id.EditText01);
        date_.setTextColor(Color.RED);
        date_button = (Button)findViewById(R.id.Button01);

        date_button.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event)
			{
				showDialog(DATE_DIALOG_ID);
				return false;
			}
		});

        // get the current date
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        // display the current date (this method is below)
        updateDisplay();

    }

    private void updateDisplay() {
    	date_.setText(
                new StringBuilder()
                        // Month is 0 based so add 1
                        .append(arrayMonth[mMonth]).append(" ")
                        .append(mDay).append(" ")
                        .append(mYear).append(" "));
    }

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

            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateDisplay();
            }
        };
        @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this,
                            mDateSetListener,
                            mYear, mMonth, mDay);
            }
            return null;
        }

}

This is the main.xml for the layout for the above java code.

<?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"
    android:layout_margin="10dp">
    >
	<TextView
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="Calendar Demo from Coderzheaven"
	    android:layout_margin="10dp"
	    />
	<EditText
		android:text=""
		android:id="@+id/EditText01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_margin="10dp">
	</EditText>
	<Button
		android:text="Show Calendar"
		android:id="@+id/Button01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_marginLeft="10dp">
	</Button>
</LinearLayout>

Please leave your valuable comments on this post.

A Simple Layout with two listViews.

Here is a simple example to show two listviews horizintally in android.

here is the java code that sets up the list.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class AlphabetListDemo extends Activity {
	//String of alphabets //
	String[] alphabts = {"A","B","C","D","E","F","G","H","I","J","K","L"};
	ListView L1, L2;
	myAdapter myadp;
	myAdapter2 myadp2;
	String prod_arr[] = {};

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

        L1 = (ListView)findViewById(R.id.list1);
        L2 = (ListView)findViewById(R.id.list2);

        myadp = new myAdapter(this,alphabts);
        L2.setAdapter(myadp);

        // initial populating //
        setProducts(0);

        L2.setOnItemClickListener(new OnItemClickListener(){
    		@Override
    		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
    				long arg3) {
    			setProducts(arg2);
    		}
    	});

    }

    public void setProducts(int number){
    	prod_arr = new String[25];
    	// adding some dummy data //
    	for(int i = 0; i < 25 ; i++){
			prod_arr[i] = "Product : " + alphabts[number] + i;
		}
		//setting the adapter in listview //
		 myadp2 = new myAdapter2(AlphabetListDemo.this,prod_arr);
	     L1.setAdapter(myadp2);
    }

    class myAdapter extends ArrayAdapter<String>
    {
  	   TextView label;
  	   ImageView image;
  	   View row;
  	   public myAdapter(Context context,String[] arr)
  	   {
  		    super(context, android.R.layout.simple_list_item_1, arr);
  	   }

  	   public View getView(final int position, View convertView, ViewGroup parent)
  		{
  	 		   try{
  	 				LayoutInflater inflater=getLayoutInflater();
  	 				row = inflater.inflate(R.layout.lv_rows, parent, false);
  					label = (TextView)row.findViewById(R.id.item_title);
  					label.setText(alphabts[position]);
  					label.setTextColor(Color.YELLOW);
  	 		   }catch(Exception e){

  			   }
  		    return row;
  		}
    }
    // adapter for second list.....
    class myAdapter2 extends ArrayAdapter<String>
    {
  	   TextView label;
  	   ImageView image;
  	   View row;
  	   public myAdapter2(Context context,String[] arr)
  	   {
  		    super(context, android.R.layout.simple_list_item_1, arr);
  	   }

  	   public View getView(final int position, View convertView, ViewGroup parent)
  		{
  	 		   try{
  	 				LayoutInflater inflater=getLayoutInflater();
  	 				row = inflater.inflate(R.layout.lv_rows, parent, false);
  					label = (TextView)row.findViewById(R.id.item_title);
  					label.setText(prod_arr[position]);
  					label.setTextColor(Color.WHITE);
  	 		   }catch(Exception e){

  			   }
  		    return row;
  		}
    }
}

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="wrap_content"
    android:layout_height="fill_parent">

    <LinearLayout
	    android:layout_width="fill_parent"
	    android:layout_height="fill_parent"
	    android:layout_marginLeft="5dp"
	    android:layout_marginRight="5dp"
	    android:layout_marginTop="5dp"
	    android:orientation="horizontal">

	    <!--  this list contains products -->
		 <ListView
		 	android:id="@+id/list1"
			android:cacheColorHint="#00000000"
			android:scrollbars="none"
			android:fadingEdge="vertical"
			android:soundEffectsEnabled="true"
			android:dividerHeight="1px"
			android:padding="0dip"
			android:smoothScrollbar="true"
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content"
		    android:drawSelectorOnTop="false"
		    android:layout_marginTop="5dip"
		    android:layout_marginLeft="5dip"
		    android:layout_marginRight="5dip"
		    android:layout_marginBottom="5dip"
		    android:layout_weight="1"
		   />

		  <ListView
		 	android:id="@+id/list2"
		 	android:layout_weight="4"
			android:cacheColorHint="#00000000"
			android:scrollbars="none"
			android:fadingEdge="vertical"
			android:soundEffectsEnabled="true"
			android:dividerHeight="1px"
			android:padding="0dip"
			android:smoothScrollbar="true"
		    android:layout_width="wrap_content"
		    android:layout_height="wrap_content"
		    android:drawSelectorOnTop="false"
		    android:layout_marginTop="5dip"
		    android:layout_marginLeft="5dip"
		    android:layout_marginRight="5dip"
		    android:layout_marginBottom="5dip" />

  	</LinearLayout>
    </LinearLayout>

Here is the layout for each row in the list .

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="7dp"
    >
        <TextView
            android:id="@+id/item_title"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:padding="2dp"
            android:text="Main Item"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textSize="14dp"
            android:textStyle="normal" />
 </RelativeLayout>

Here is the complete source code for this example.

CustomAlert without any custom Layout in android.

We can create a dialog with custom alert dialog with our xml in android.
But for making simple alerts we can make custom alerts through code itself.

Here is a simple function for this. Here I am having a Listview and an edittext with two buttons in the alertBox.

  public void addDialog(){

          String test[] = {"hello1","hello2"};

    	  AlertDialog.Builder builder = new AlertDialog.Builder(this);
          builder.setCancelable(true);
          builder.setTitle("My Title");
          builder.setInverseBackgroundForced(true);
          builder.setIcon(R.drawable.android_2);
          builder.setItems(test, new OnClickListener() {
  			@Override
  			public void onClick(DialogInterface dialog, int which) {
  				System.out.println("onClick " + which);
  			}
  		  });
          builder.setAdapter(myadp, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				System.out.println("DialogInterface : " + which);
			}
		  });

          EditText ed = new EditText(this);
          builder.setView(ed);
          builder.setPositiveButton("Yes",
                  new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog,
                              int which) {
                          dialog.dismiss();
                      }
                  });
          builder.setNegativeButton("No",
                  new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog,
                              int which) {
                          dialog.dismiss();
                      }
                  });
          AlertDialog alert = builder.create();
          alert.show();
    }

Please leave your valuable comments on this post.

Custom Alert

Changing the style or theme of default alertDialog in Android.

Hello everyone,
Here is a simple example showing how to change the theme of default AlertDialog in android.

Check this post before for understanding how to use styles.
http://www.coderzheaven.com/2012/04/17/inherit-styles-extend-styles-android/

To start first create a fresh project named AlertTest.
In the AlertTestDemo.java file copy this code

package com.coderzheaven.pack;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;

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

        AlertDialog dialog = new CustomDialog(this);
        dialog.setButton("OK", new OnClickListener()
        {
            public void onClick(DialogInterface arg0, int arg1)
            {
            }
        });
        dialog.setTitle("Coderzheaven");
        dialog.setMessage("Heaven of all working codes!! n Keep Visiting..n" +
        		"Thankyou.");
        dialog.show();
    }
}


Now create a file named “styles.xml” inside the res/values folder and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="CenterTextView" parent="@android:style/Widget.TextView">
        <item name="android:gravity">center|center_vertical</item>
    </style>

    <style name="CenterJustifyDialogTitle" parent="@android:style/DialogWindowTitle" >
         <item name="android:gravity">center|center_vertical</item>
         <item name="android:textColor">#000000</item>
    </style>

	<style name="CenterJustifyTheme1" parent="@android:style/Theme.Translucent">
        <item name="android:textViewStyle">@style/CenterTextView</item>
        <item name="android:windowTitleStyle">@style/CenterJustifyDialogTitle</item>
    </style>

    <style name="CenterJustifyTheme2" parent="@android:style/Theme.Black">
        <item name="android:textViewStyle">@style/CenterTextView</item>
        <item name="android:windowTitleStyle">@style/CenterJustifyDialogTitle</item>
    </style>

    <style name="CenterJustifyTheme3" parent="@android:style/Theme.Light">
        <item name="android:textViewStyle">@style/CenterTextView</item>
        <item name="android:windowTitleStyle">@style/CenterJustifyDialogTitle</item>
    </style>

</resources>

Now create another java file named “CustomDialog.java” and copy this code into it.
We will apply the theme through this java file.
The theme is located and named in the above xml file.


package com.coderzheaven.pack;
import android.app.AlertDialog;
import android.content.Context;
import com.coderzheaven.pack.R;


public class CustomDialog extends AlertDialog {
		public CustomDialog(Context ctx)
		{
			super(ctx, R.style.CenterJustifyTheme1);
		}
}

How to encrypt a string in Android Using Base64?

package com.coderzheaven.encryptstring;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Base64;

@SuppressLint({ "WorldReadableFiles", "WorldWriteableFiles" })
public class MainActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		saveText("CoderzHeaven");
		System.out.println(getText());
	}

	public void saveText(String text) {
		SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",
				MODE_WORLD_READABLE);
		SharedPreferences.Editor editor = myPrefs.edit();
		text = Base64.encodeToString(text.getBytes(), Base64.DEFAULT);
		editor.putString("some_text", text);
		editor.commit();
	}

	public String getText() {
		SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",
				MODE_WORLD_WRITEABLE);
		String text = myPrefs.getString("some_text", null);
		text = new String(Base64.decode(text, Base64.DEFAULT));
		return text;
	}
}

Please check the LogCat for output.

Join the Forum discussion on this post

Single Selection ListView in android

Hello all…..

In today’s post I will show you how to create a single selection list in android.

Here is the 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:id="@android:id/list"
			android:cacheColorHint="#00000000"
			android:scrollbars="none"
			android:fadingEdge="vertical"
			android:soundEffectsEnabled="true"
			android:dividerHeight="1px"
			android:padding="5dip"
			android:smoothScrollbar="true"
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content"
		    android:drawSelectorOnTop="false"
		    android:layout_marginLeft="10dip"
		    android:layout_marginRight="10dip"
		    android:layout_marginBottom="10dip"
		    android:layout_weight="1"/>

</LinearLayout>

Now this line in the java file creates the single choice.

setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_single_choice,
android.R.id.text1, names));

Now this is the full java code

package com.coderzheaven.pack;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

        String[] names = new String[] { "Android", "Windows7", "Symbian", "iPhone",
        		"Android", "Windows7", "Symbian", "iPhone",
        		"Android", "Windows7", "Symbian", "iPhone" };
		setListAdapter(new ArrayAdapter<String>(this,
					   android.R.layout.simple_list_item_single_choice,
					   android.R.id.text1, names));
		ListView listView = getListView();
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    }
}

Single Choice ListView

Single Selection ListView in android

Customizing a spinner in android.

Hello everyone………

You all knew that a spinner or combobox is an inbuilt widget in android. And Like any other widgets spinners are also customizable.
Here is a simple example to customize a spinner. First we will look at the java code.
The getView method is called for each row in the spinner. So with the help of an Layout Inflater you can inflate any layout for each row.
At extreme you can have each layout for each row.

Check these older posts about spinner.

1. How to get a selected Item from a spinner in ANDROID?

2. How to set an item selected in Spinner in ANDROID?

3. How to create a custom ListView in android?

Check out these of ListViews

1. Simplest Lazy Loading ListView Example in Android with data populated from a MySQL database using php.

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

Custom Spinner Demo

Custom Spinner Demo

Custom Spinner Demo

Custom Spinner Demo

Now we will look at the source code

Resources needed.
These are images I am using in this example. Put these images inside the res/drawable folder.

apple.png
bkg.png
coderzheaven.png
google.png
icon.png
microsoft.png
samsung.png
yahoo.png

package         pack.coderzheaven;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

public class CustomSpinnerDemo extends Activity {
	String[] strings = {"CoderzHeaven","Google",
			"Microsoft", "Apple", "Yahoo","Samsung"};

	String[] subs = {"Heaven of all working codes ","Google sub",
			"Microsoft sub", "Apple sub", "Yahoo sub","Samsung sub"};


	int arr_images[] = { R.drawable.coderzheaven,
						 R.drawable.google, R.drawable.microsoft,
						 R.drawable.apple, R.drawable.yahoo, R.drawable.samsung};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
        mySpinner.setAdapter(new MyAdapter(CustomSpinnerDemo.this, R.layout.row, strings));
    }

    public class MyAdapter extends ArrayAdapter<String>{

    	public MyAdapter(Context context, int textViewResourceId,	String[] objects) {
    		super(context, textViewResourceId, objects);
    	}

    	@Override
    	public View getDropDownView(int position, View convertView,ViewGroup parent) {
    		return getCustomView(position, convertView, parent);
    	}

    	@Override
    	public View getView(int position, View convertView, ViewGroup parent) {
    		return getCustomView(position, convertView, parent);
    	}

    	public View getCustomView(int position, View convertView, ViewGroup parent) {

	    	LayoutInflater inflater=getLayoutInflater();
	    	View row=inflater.inflate(R.layout.row, parent, false);
	    	TextView label=(TextView)row.findViewById(R.id.company);
	    	label.setText(strings[position]);

	    	TextView sub=(TextView)row.findViewById(R.id.sub);
	    	sub.setText(subs[position]);

	    	ImageView icon=(ImageView)row.findViewById(R.id.image);
	    	icon.setImageResource(arr_images[position]);

	    	return row;
    		}
    	}
   }

Now the main.xml which defines the main layout.

<?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"
      android:background="@drawable/bkg"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Spinner
    android:id="@+id/spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:drawSelectorOnTop="true"
    android:prompt="@string/prompt"
    />
</LinearLayout>

Now the layout for each row in the spinner.
row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:padding="3dip"
>
	<ImageView
		 android:id="@+id/image"
		 android:layout_width="wrap_content"
		 android:layout_height="wrap_content"
		 android:src="@drawable/icon"/>
	<TextView
		 android:layout_toRightOf="@+id/image"
		 android:padding="3dip"
		 android:layout_marginTop="2dip"
		 android:textColor="@drawable/red"
		 android:textStyle="bold"
		 android:id="@+id/company"
		 android:text="CoderzHeaven"
		 android:layout_marginLeft="5dip"
		 android:layout_width="wrap_content"
		 android:layout_height="wrap_content"/>
	 <TextView
		 android:layout_toRightOf="@+id/image"
		 android:padding="2dip"
		 android:textColor="@drawable/darkgrey"
		 android:layout_marginLeft="5dip"
		 android:id="@+id/sub"
		 android:layout_below="@+id/company"
		 android:text="Heaven of all working codes"
		 android:layout_width="wrap_content"
		 android:layout_height="wrap_content"/>
</RelativeLayout>

Now the strings.xml.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">CustomSpinner Demo from CoderzHeaven!</string>
    <string name="prompt">  Select your Favourite  </string>
    <string name="app_name">CustomSpinner Demo</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>
	<string name="select_Category">Select Category</string>
	<drawable name="darkgrey">#606060</drawable>
</resources>

Please click the +1 button on top to share it with your friends and leave your valuable comments also.

Sort elements in a String Array – C Sharp / C#

Hi,

In order to sort the elements in a string array in C Sharp/C#, we use the sort() method. Given below is a simple example using sort() method to sort the elements in a string array.

using System;

class MainClass
{

  public static void Main()
  {

    string[] urStringArray = {"xylo", "apple", "zeebra", "coderz", "heaven123", "heaven777"};
    Array.Sort(urStringArray );
    Console.WriteLine("Sorted string Array:");
    for (int i = 0; i < urStringArray.Length; i++)
    {
      Console.WriteLine("urStringArray[" + i + "] = " + urStringArray[i]);
    }
  }

}

It will print out,
Sorted string Array:
urStringArray[0] = apple
urStringArray[1] = coderz
urStringArray[2] = heaven123
urStringArray[3] = heaven777
urStringArray[4] = xylo
urStringArray[5] = zeebra
:)

How to use SeekBar in ANDROID?

Here is a simple example to show how to use seek Bar in android.

Create a new project and place this code in it.

package com.coderzheaven;

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

public class SeekBarDemo extends Activity  implements SeekBar.OnSeekBarChangeListener {
    SeekBar mSeekBar;
    TextView mProgressText;
    TextView mTrackingText;

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

        setContentView(R.layout.main);

        mSeekBar = (SeekBar)findViewById(R.id.seek);
        mSeekBar.setOnSeekBarChangeListener(this);
        mProgressText = (TextView)findViewById(R.id.progress);
        mTrackingText = (TextView)findViewById(R.id.tracking);
    }

    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
        mProgressText.setText(progress + " " +
                getString(R.string.seekbar_from_touch) + "=" + fromTouch);
    }

    public void onStartTrackingTouch(SeekBar seekBar) {
        mTrackingText.setText(getString(R.string.seekbar_tracking_on));
    }

    public void onStopTrackingTouch(SeekBar seekBar) {
        mTrackingText.setText(getString(R.string.seekbar_tracking_off));
    }
}

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">

    <SeekBar android:id="@+id/seek"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="50"
        android:secondaryProgress="75" />

    <TextView android:id="@+id/progress"
       	android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView android:id="@+id/tracking"
       	android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

The strings.xml file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">SeekBarDemo</string>
    <string name="seekbar_tracking_on">Tracking on</string>
    <string name="seekbar_tracking_off">Tracking off</string>
    <string name="seekbar_from_touch">from touch</string>
</resources>
SeekBar Demo in ANDROID

SeekBar Demo in ANDROID

Here is another example to show How to get the current progress on your SeekBar in android?

Please leave your valuable cmments

Complex JSON String parsing in ANDROID

Hello all…..

In the previous post I have shown you how to parse a Simple JSON String in ANDROID.
In today’s tutorial I will show you how to parse a complex JSON String.
Take a look at the example

Here the JSON String used is

"{"menu": "
    "{"id": "
	 ""file", "value": "File", "popup": "
		 "{ "menuitem": [ {"value": "New",   "onclick": "CreateNewDoc()"}, "
			 "{"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}}}";

Now let’s dothe operation………..

package pack.coderzheaven;

import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;

public class JSON_Demo extends Activity {
	private JSONObject jObject;
	private String jString = "{"menu": " +
							 "{"id": " +
							 ""file", "value": "File", "popup": " +
							 "{ "menuitem": [ {"value": "New",   "onclick": "CreateNewDoc()"}, " +
							 "{"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}}}";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		try {
			parse();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void parse() throws Exception {

		jObject = new JSONObject(jString);

		JSONObject menuObject = jObject.getJSONObject("menu");
		String attributeId = menuObject.getString("id");
		System.out.println(attributeId);

		String attributeValue = menuObject.getString("value");
		System.out.println(attributeValue);

		JSONObject popupObject = menuObject.getJSONObject("popup");
		JSONArray menuitemArray = popupObject.getJSONArray("menuitem");

		for (int i = 0; i < 3; i++) {
			System.out.println(menuitemArray.getJSONObject(i)
					.getString("value").toString());
			System.out.println(menuitemArray.getJSONObject(i).getString(
					"onclick").toString());
		}
	}
}

Please check the Logcat for the output.

Please leave your valuable comments on this post.

Parsing JSON Object in ANDROID.

JSON are alternative to XML and easy to understand than XML.
As other languages Java also supports JSON parsing.
Here is a simple example of JSON parsing in ANDROID.

This is the JSON String that I am going to parse.

{"A":
           { "A1":"A1_value" ,"A2":"A2_value","sub":
              { "sub1":[ {"sub1_attr":"sub1_attr_value" }]}
           }
}";

And this JSON is same as this xml.

	  <A A1="A1_value" A2="A2_value">
	 	<sub>
	 		<sub1 sub1_attr="sub1_attr_value" />
	 	</sub>
	   <A>

Here is the code for this parsing.

package pack.coderzheaven;

import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;

public class JSON_Demo extends Activity {
	private JSONObject jObject;
	private String test = "{"A":  {  "A1":"A1_value" ,"A2":"A2_value", "sub": { "sub1":[ {"sub1_attr":"sub1_attr_value" }] } }    }";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		try {
			parse();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void parse() throws Exception {

		jObject = new JSONObject(test);
		JSONObject menuObject = jObject.getJSONObject("A");
		String attributeId1 = menuObject.getString("A1");
		System.out.println("A1 value == " +attributeId1);
		String attributeId2 = menuObject.getString("A2");
		System.out.println("A2 value == " +attributeId2);

		JSONObject popupObject = menuObject.getJSONObject("sub");
		JSONArray menuitemArray = popupObject.getJSONArray("sub1");

		System.out.println("sub1_attr = " + menuitemArray.getJSONObject(0).getString("sub1_attr").toString());
	}
}

Please check the Logcat for the output.

Posts to come.

More complex JSON String parsing in ANDROID.

Please leave your valuable comments.

Program for Palindrome checking in C Sharp/C#

Hi,

Sometimes you need to check for whether the given string is Palindrome or not. Given below is a sample code to check whether the given string is Palindrome or not using C Sharp/C#.

class Palindrome
{
  static void Main()
  {
      string checkStr, sampleStr;
      char[] temp;

      System.Console.Write("Enter your String: ");

      sampleStr = System.Console.ReadLine();

      checkStr = sampleStr.Replace(" ", "");

      checkStr = checkStr.ToLower();

      temp = checkStr.ToCharArray();

      System.Array.Reverse(temp);

      if(checkStr== new string(temp))
      {
          System.Console.WriteLine(""{0}" is a palindrome.",sampleStr);
      }

      else
      {
          System.Console.WriteLine(""{0}" is NOT a palindrome.",sampleStr);
      }

  }
}

:)

TextView with link in ANDROID…….

Hi all…….

All of you may be familiar with TextViews in ANDROID.
But how many of you know that we have have html as text in a textView. This post is a simple example to show this.

Create a fresh project and copy this code to the main java file.

package com.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;

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

        TextView tv = (TextView) findViewById(R.id.tv);
        tv.setText( Html.fromHtml("<b>This is a textView with a link </b>  " +
                    " <br /> <a href="http://www.coderzheaven.com">Coderzheaven</a> " +
                    "created in the Java source code using HTML."));
         tv.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

The 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/tv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
</LinearLayout>

The AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".TextViewLinkDemo"
                  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>
Link in TextView Demo

Link in TextView Demo

Get a file from PhotoGallery and copy it to your directory in your project resources in Titanium(iPhone or ANDROID).

This example opens the photogallery and then when you select a file from it , it will be copied to your resources directory.
First manually create a directory in your resources, here the directory is named “mydirectory”.
Call this functiion inside a button click or something

var directory = "mydirectory"
 Titanium.Media.openPhotoGallery({
	success:function(event)
	{
		var cropRect = event.cropRect;
		var image = event.media;
		var mime_type = image.mimeType;  	// Getting the file type.....
		var arr = Array();
		arr = mime_type.split('/');
		var image_type = arr[1];
		if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO)
		{
			var image_name = "My_img""."+arr[1];
			Ti.API.info(image_name);
			var filename = Titanium.Filesystem.resourcesDirectory +  directory + image_name;
			var bgImage = Titanium.Filesystem.getFile(filename);
			bgImage.write(image);                  	//write the image binary to new image file.
	},
	cancel:function()
	{	Ti.API.info(' Cancelled ');		},
	error:function(error)
	{  	Ti.API.info(' An error occurred!! ');	 	},
	allowEditing:true,
	mediaTypes:[Ti.Media.MEDIA_TYPE_PHOTO]
});

Now after running this code check the directory you have created.

If you want to delete the image use this

var file = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory+"/"+directory +"/"+My_img.png);
file.deleteFile();

Note: Change it to appropriate file extension.

If you want to list all the files inside the directory use this code…

var my_dir = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory+"/"+directory+"/");
		var files = my_dir.getDirectoryListing().toString();
		Ti.API.info('directoryListing = ' + files);
		var files_array = Array();
		files_array = gal_files.split(',');
		var num_of_files = files_array.length;

If you want to delete a directory Use this

	var my_dir= Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory+"/"+directory+"/");
		 	if(my_dir.exists()){
				var files = gal_dir.getDirectoryListing().toString();
				var files_array = Array();
				files_array = gal_files1.split(',');
				var num_of_files = gal_files_array1.length;

				for(var j = 0; j < num_of_files ; j++){
					var file1 = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory+"/"+directory+"/"+files_array[j]);
					file1.deleteFile();
				}
				my_dir.deleteDirectory();
		 	}

Please leave your valuable comments.

Email validation in ANDROID.

This is a simple example showing email validation in ANDROID.
This example uses regex for email validation.
Create a button and an edittext in your main.xml file and try this code.

package com.coderzheaven;

import java.util.regex.Pattern;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class EmailValidationDemo extends Activity   {

	EditText TF;
	public Button checkButton;

	public final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
	          "[a-zA-Z0-9+._%-+]{1,256}" +
	          "@" +
	          "[a-zA-Z0-9][a-zA-Z0-9-]{0,64}" +
	          "(" +
	          "." +
	          "[a-zA-Z0-9][a-zA-Z0-9-]{0,25}" +
	          ")+"
	      );
     @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);

	   TF=(EditText) findViewById(R.id.TF);
	   checkButton=(Button) findViewById(R.id.checkButton);

	    checkButton.setOnClickListener(new OnClickListener() {
		public void onClick(View v) {
			   String email=TF.getText().toString();
			   if(checkEmail(email))
				  Toast.makeText(EmailValidationDemo.this,"Valid Email Addresss", Toast.LENGTH_SHORT).show();
			   else
			 	  Toast.makeText(EmailValidationDemo.this,"Invalid Email Addresss", Toast.LENGTH_SHORT).show();
		}
	    });
    }
    private boolean checkEmail(String email) {
        return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
    }
}

Check this link to find how you can send email from android programatically.
Please leave your valuable comments……