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.

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 make a http call repeatedly from a service in android?

We may have applications in which we may have to make repeated calls to a webservice. At that time services may be useful.

This is such an example in which we will be creating a Service in android to create a repeated call to a webservice in a time delay of some seconds or milliseconds.

OK We will start.

First We will create a new android project named “AcessWebFromService” and in the main java file copy this code.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class AcessWebFromServiceDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        startService(new Intent(AcessWebFromServiceDemo.this, MyService.class));
    }
}

You may be getting some errors after this. Now we will clear all the errors.

Now create another class and name it “MyService.java“. This is our Service file that extends Android Service.

Paste this code into this file .

package com.coderzheaven.pack;

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

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service{
	
	private static String TAG = MyService.class.getSimpleName();
	private MyThread mythread;
	public boolean isRunning = false;
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "onCreate");		
		mythread  = new MyThread();
	}

	@Override
	public synchronized void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy");
		if(!isRunning){
			mythread.interrupt();
			mythread.stop();
		}		
	}

	@Override
	public synchronized void onStart(Intent intent, int startId) {
		super.onStart(intent, startId); 
		Log.d(TAG, "onStart");
		if(!isRunning){
			mythread.start();
			isRunning = true;
		}
	}
	
	public void readWebPage(){
          HttpClient client = new DefaultHttpClient();
          HttpGet request = new HttpGet("http://google.com");
          // Get the response
          ResponseHandler<String> responseHandler = new BasicResponseHandler();
          String response_str = null;
		  try {
			 response_str = client.execute(request, responseHandler);
			 if(!response_str.equalsIgnoreCase("")){
				 Log.d(TAG, "Got Response");
			 }
		  } catch (Exception e) {
			 e.printStackTrace();
		  }
	}
	
	class MyThread extends Thread{
		static final long DELAY = 3000;
		@Override
		public void run(){			
			while(isRunning){
				Log.d(TAG,"Running");
				try {					
					readWebPage();
					Thread.sleep(DELAY);
				} catch (InterruptedException e) {
					isRunning = false;
					e.printStackTrace();
				}
			}
		}
		
	}

}

We have called this service to start running in the main java file using this code.

startService(new Intent(AcessWebFromServiceDemo.this, MyService.class));

Now the important thing is for this service to run we have to declare it in the AndroidManifest file.

This is how the AndroidManifest file looks.

<?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">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AcessWebFromServiceDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <service android:name=".MyService"></service>

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

OK Now you are done. When you run this application you can see the Log coming every three seconds in the LogCat. PLease make sure that you have internet connection in the Emulator or Device.

This is how the Log looks in the Logcat.

Service

Please leave your valuable comments on this post and also share it by hitting a plus(+1) button.

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 create CustomProgressBar in android – Part 3?

Hello all…

In my previous posts I have shown two methods to create custom progressbar in android.

Check out these tutorials to find out how?

1. How to build a custom progressBar in android- Part 2?
2. Custom progressbar in android with text – part 3

Today in this post I will show you a third method.

Here is the main.xml that contains the progressBar.

<?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" 
    android:gravity="center">
 
 
        <ProgressBar
            android:id="@+id/progressBar1"
             android:indeterminateDrawable="@drawable/progressbackground1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_margin="20dp" />
 
        <ProgressBar
            android:id="@+id/progressBar2"
             android:indeterminateDrawable="@drawable/progressbackground2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_margin="20dp"  />
         
         <ProgressBar
            android:id="@+id/progressBar3"
             android:indeterminateDrawable="@drawable/progressbackground3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_margin="20dp"  />
            
         <ProgressBar
            android:id="@+id/progressBar4"
             android:indeterminateDrawable="@drawable/progressbackground4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_margin="20dp"  />
 
</LinearLayout>

Now we will create the “android:indeterminateDrawable” xml that is mentioned in the above xml.

Create 4 xml files inside the res/drawable directory whose names and contents are given below.

Here is the first one. “progressbackground1.xml”

<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/progressbar1"
android:pivotX="50%"
android:pivotY="50%" />

progressbackground2.xml

<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/progressbar2"
android:pivotX="50%"
android:pivotY="50%" />

progressbackground3.xml

<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/progressbar3"
android:pivotX="50%"
android:pivotY="50%" />

progressbackground4.xml

<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/progressbar4"
android:pivotX="50%"
android:pivotY="50%" />

I have four drawable images inside my res/drawable folder.

progressbar

progressbar

progressbar

progressbar

Running it will produce the below result.

Progressbar android

Please leave your valuable comments on this post.

Download the complete java source code from here.

Custom progressbar in android with text – part 3

Hello all……

I have posted two posts on how to customize a progressbar in android.

1. Custom Indeterminate progressBar for android?
2. How to build a custom progressBar in android- Part 2?

Here is another one with update text on top of the progressbar.

Here is how we start.

After creating a fresh project create a new java file and name it “TextProgressBar.java”.

Now copy this code to the above file.
This file extends the progressbar to add additional functionality.

package com.coderzheaven.pack;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.ProgressBar;

public class TextProgressBar extends ProgressBar {
	private String text;
	private Paint textPaint;

	public TextProgressBar(Context context) {
		super(context);
		text = "0/100";
		textPaint = new Paint();
		textPaint.setColor(Color.BLACK);
	}

	public TextProgressBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		text = "0/100";
		textPaint = new Paint();
		textPaint.setColor(Color.BLACK);
	}

	public TextProgressBar(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		text = "0/100";
		textPaint = new Paint();
		textPaint.setColor(Color.BLACK);
	}

	@Override
	protected synchronized void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		Rect bounds = new Rect();
		textPaint.getTextBounds(text, 0, text.length(), bounds);
		int x = getWidth() / 2 - bounds.centerX();
		int y = getHeight() / 2 - bounds.centerY();
		canvas.drawText(text, x, y, textPaint);
	}

	public synchronized void setText(String text) {
		this.text = text;
		drawableStateChanged();
	}

	public void setTextColor(int color) {
		textPaint.setColor(color);
		drawableStateChanged();
	}
}

OK the progressbar class is now complete.

Now the xml in which the progressbar contains.

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="Custom ProgressBar Demo from CoderzHeaven"
	    android:textStyle="bold"
	    android:layout_margin="10dp"
    />
    
	<com.coderzheaven.pack.TextProgressBar   
		android:id="@+id/pb"  
		android:layout_width="fill_parent"  
		android:layout_height="wrap_content"  
		android:max="100"  
		android:progress="0"  
		style="?android:attr/progressBarStyleHorizontal"  
		android:maxHeight="20dip"  
		android:minHeight="20dip"  
	/>  
	
</LinearLayout>

Take a look at this line in the xml

This adds the custom progressbar in the xml.

OK Done now we have to just implement in the custom progressbar.

Now the main java file that is calling the progressbar.

package com.coderzheaven.pack;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class CustomProgressBarDemo extends Activity {
	
	int myProgress = 0;
	TextProgressBar pb;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        pb = new TextProgressBar(this);
        pb = (TextProgressBar) findViewById(R.id.pb);  
        new Thread(myThread).start();
    }
    
    private Runnable myThread = new Runnable(){
	  @Override
	  public void run() {	  
		   while (myProgress<100){
			    try{
			    	System.out.println("SSS");
			    	pb.setProgress(myProgress);
			    	pb.setText(myProgress+"/100");
			    	myHandle.sendMessage(myHandle.obtainMessage());
			    	Thread.sleep(500);
			    }
			    catch(Throwable t){
			    }
		   }
	  }

	  Handler myHandle = new Handler(){
		   @Override
		   public void handleMessage(Message msg) {
		    myProgress++;
			pb.setProgress(myProgress);
			pb.setText(myProgress+"/100");
		   }
	  };
	};
}

OK Go on and run the project you will get these results.

custom ProgressBar with text

custom ProgressBar with text

custom ProgressBar with text

How to build a custom progressBar in android- Part 2?

Hello all…….

Today I am going to show you how to create a custom progressbar in android.
Previously in another posts I have already shown how to build a custom indeterminate progressbar in android.
And in this post I will show you how to customize the horizontal progressbar.

OK Now we will start.

First create a fresh project and name in “CustomProgressBarDemo_01″ and name the Activity “CustomProgressBarDemo”.

Now copy this code to the the “CustomProgressBarDemo.java” file.

package com.coderzheaven.pack;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;

public class CustomProgressBarDemo extends Activity {
	
	int myProgress = 0;
	ProgressBar pb;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        pb = (ProgressBar)findViewById(R.id.player_exp_bar);
        pb.setProgressDrawable(getResources().getDrawable(R.drawable.green_progress));  
        new Thread(myThread).start();
    }
    
    private Runnable myThread = new Runnable(){
	  @Override
	  public void run() {	  
		   while (myProgress<100){
			    try{
			    	pb.setProgress(myProgress);
			     myHandle.sendMessage(myHandle.obtainMessage());
			     Thread.sleep(500);
			    }
			    catch(Throwable t){
			    }
		   }
	  }

	  Handler myHandle = new Handler(){
		   @Override
		   public void handleMessage(Message msg) {
		    myProgress++;
		    pb.setProgress(myProgress);
		   }
	  };
	};
}

After pasting it you may get some errors but don’t worry in the coming lines we will remove all that.

Now the layout file “main.xml” which contains the progressbar.

<?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="Custom ProgressBar Demo from CoderzHeaven"
    android:textStyle="bold"
    android:layout_margin="10dp"
    />
    

	<ProgressBar  
		android:id="@+id/player_exp_bar"  
		android:layout_width="fill_parent"  
		android:layout_height="wrap_content"  
		android:max="100"  
		android:progress="0"  
		style="?android:attr/progressBarStyleHorizontal"  
		android:maxHeight="5dip"  
		android:minHeight="5dip"  
	/>  
	
</LinearLayout>

There may be more errors. Leave it and continue.

Now go to your drawable folder inside the “res” folder and create an xml named “green_progress.xml”.
Copy this code into it.

<?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/secondaryProgress">
    <clip>
        <shape>
            <corners android:radius="5dip" />
            <gradient
                    android:startColor="#80ffd300"
                    android:centerColor="#80ffb600"
                    android:centerY="0.75"
                    android:endColor="#a0ffcb00"
                    android:angle="270"
            />
        </shape>
    </clip>
</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 open the strings.xml inside the values folder and copy these code into it.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, CustomProgressBarDemo!</string>
    <string name="app_name">CustomProgressBarDemo</string>
    
    <color name="greenStart">#ff33dd44</color>
	<color name="greenMid">#ff0A8815</color>
	<color name="greenEnd">#ff1da130</color>

</resources>

Ok now I think your errors are cleaned.

It’s time to run the project.

You will see this screen.

I have simulated this progressbar to run to end.

custom_progress_1

custom_progress_2

Please share your comments and likes on this post.

Download the complete source code from here.

How to create Simple Login form using php in android? – Connect php with android.

Hello all..
I have shown two other examples for creating a connection between android and php. But still users are finding difficulty in grasping it.

These are other posts.
1.Android phpMysql connection.
2.Android phpmySQL connection redone.

Here is one more post on this which is even more detailed.

OK we will start now.

First create a fresh project named “AndroidPHP”.

Now My main java file is named “AndroidPHPConnectionDemo.java”.

First we will create a layout for the login form. This xml will do this. copy this code to 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"
    android:layout_gravity="center|center_vertical"
    >
<TextView 
	android:id="@+id/tv0"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Login Form Demo From Coderzheaven"
    android:textSize="20sp"
    android:gravity="center"
    android:textStyle="bold"
    />
<TextView 
	android:id="@+id/tv1"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Username"
    />
<EditText 
	android:text="" 
	android:id="@+id/username" 
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content"
	android:singleLine="true">
</EditText>
<TextView 
	android:id="@+id/tv2"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Password"
    />
<EditText 
	android:text="" 
	android:id="@+id/password" 
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content"
	android:singleLine="true">
</EditText>
<Button 
	android:text="Login" 
	android:id="@+id/Button01" 
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content">
</Button>
<TextView 
	android:id="@+id/tv"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text=""
    />
</LinearLayout>

Now create another xml named userpage.xml by right clicking the layout folder -> Android XML File.
Copy this code into that. This is the layout to show in the activity when the user successfully logins.

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

Now in the main java file im my case AndroidPHPConnectionDemo.java, copy this code.

package pack.coderzheaven;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidPHPConnectionDemo extends Activity {
	Button b;
	EditText et,pass;
	TextView tv;
	HttpPost httppost;
	StringBuffer buffer;
	HttpResponse response;
	HttpClient httpclient;
	List<NameValuePair> nameValuePairs;
	ProgressDialog dialog = null;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        b = (Button)findViewById(R.id.Button01);  
        et = (EditText)findViewById(R.id.username);
        pass= (EditText)findViewById(R.id.password);
        tv = (TextView)findViewById(R.id.tv);
        
        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog = ProgressDialog.show(AndroidPHPConnectionDemo.this, "", 
                        "Validating user...", true);
				 new Thread(new Runnable() {
					    public void run() {
					    	login();					      
					    }
					  }).start();				
			}
		});
    }
	
	void login(){
		try{			
			 
			httpclient=new DefaultHttpClient();
			httppost= new HttpPost("http://10.0.2.2/my_folder_inside_htdocs/check.php"); // make sure the url is correct.
			//add your data
			nameValuePairs = new ArrayList<NameValuePair>(2);
			// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
			nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
			nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim())); 
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			//Execute HTTP Post Request
			response=httpclient.execute(httppost);
			// edited by James from coderzheaven.. from here....
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			final String response = httpclient.execute(httppost, responseHandler);
			System.out.println("Response : " + response); 
			runOnUiThread(new Runnable() {
			    public void run() {
			    	tv.setText("Response from PHP : " + response);
					dialog.dismiss();
			    }
			});
			
			if(response.equalsIgnoreCase("User Found")){
				runOnUiThread(new Runnable() {
				    public void run() {
				    	Toast.makeText(AndroidPHPConnectionDemo.this,"Login Success", Toast.LENGTH_SHORT).show();
				    }
				});
				
				startActivity(new Intent(AndroidPHPConnectionDemo.this, UserPage.class));
			}else{
				showAlert();				
			}
			
		}catch(Exception e){
			dialog.dismiss();
			System.out.println("Exception : " + e.getMessage());
		}
	}
	public void showAlert(){
		AndroidPHPConnectionDemo.this.runOnUiThread(new Runnable() {
		    public void run() {
		    	AlertDialog.Builder builder = new AlertDialog.Builder(AndroidPHPConnectionDemo.this);
		    	builder.setTitle("Login Error.");
		    	builder.setMessage("User not Found.")  
		    	       .setCancelable(false)
		    	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		    	           public void onClick(DialogInterface dialog, int id) {
		    	           }
		    	       });		    	       
		    	AlertDialog alert = builder.create();
		    	alert.show();		    	
		    }
		});
	}
}

Now create another java class “UserPage.java”
This is simply a navigation page when the user log in.

package pack.coderzheaven;

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

public class UserPage extends Activity {

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

OK Android side is done.

Now the server side (php side).

These things you need top remember.
1. Make sure the url you are providing to the android java code is correct.
2. Make sure your server is running.
3. Make sure your php page has no errors.
4. Also if connecting to a remote URL, you should have internet connection in your emulator or device.
5. Make sure you have a database named mydatabase(in this case) and a table named “tbl_user” and some users inserted in it.

This is the creation query of the table tbl_user in the MYSQL database.

CREATE TABLE  `mydatabase`.`tbl_user` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 20 ) NOT NULL ,
`password` VARCHAR( 20 ) NOT NULL
) ENGINE = MYISAM

Check the screenshot.

I an using xampp server.
So inside xampp/htdocs folder, i have a folder named “my_folder_inside_htdocs”. Inside this folder I have a php file “check.php” which has the code for checking the user in the database.

Copy this code to check.php

<?php
$hostname_localhost ="localhost";
$database_localhost ="mydatabase";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);

mysql_select_db($database_localhost, $localhost);

$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select * from tbl_user where username = '".$username."' AND password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
 if($rows == 0) { 
 echo "No Such User Found"; 
 }
 else  {
	echo "User Found"; 
}
?>

Done.Now run your project and sign in with a valid user. that’s all.

NOTE: All NETWORK OPERATIONS SHOULD BE DONE INSIDE A THREAD.

Happy Coding.

Feel free to ask if you have any doubts.

Please leave your valuable comments on this post and also you can share this post.

Download the complete source code of this example from here.

How to change the hint text color in android?

Hello all..

This simple example will show you how to change the hint text color in android

Here is the java code to simply do this.

youredittext.setHint(Html.fromHtml("<font color='#FF0000'>Hello</font> "));

here is a sample project to view the difference.

This is the contents of the main java file.

package com.coderzheaven.pack;

import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.EditText;

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

          EditText ed = (EditText)findViewById(R.id.editText1);
          ed.setHint("Hello ");

          EditText ed2 = (EditText)findViewById(R.id.editText2);
          ed2.setHint(Html.fromHtml("<font color='#FF0000'>Hello</font> "));
     }
}

The main.xml file

<?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:text="@string/hello" />

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

          <requestFocus />
     </EditText>

     <EditText
          android:id="@+id/editText2"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:ems="10" >
     </EditText>
</LinearLayout>


Here I am setting a read color to the second edittext hint.
See the screenshot.

Please leave your comments if you found this useful.

How to take screenshot of your phone in android through code?

Hey all…

This is a very simple thing to do in android.
Just copy this code to see this.

here is the main java file

package pack.coderzheaven;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class ScreenShotDemo extends Activity {
	LinearLayout L1;
	ImageView image;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        L1 = (LinearLayout) findViewById(R.id.LinearLayout01);
        Button but = (Button) findViewById(R.id.Button01);
        but.setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
		        View v1 = L1.getRootView();
		        v1.setDrawingCacheEnabled(true);
		        Bitmap bm = v1.getDrawingCache();
		        BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
		        image = (ImageView) findViewById(R.id.ImageView01);
		        image.setBackgroundDrawable(bitmapDrawable);
		    }
	   });
  }
}

And this is the layout file 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"
    android:id="@+id/LinearLayout01"
    >
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Take Screenshot"
    android:id="@+id/Button01"
    />

  <ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Take Screenshot"
    android:id="@+id/ImageView01"
    />
</LinearLayout>
Screenshot in android

ScreenShot in android

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

Uploading audio, video or image files from Android to server

Hello everyone,

Check out the popular posts from Coderzheaven.com

Uploading and Downloading of files – Popular and Useful posts from CoderzHeaven

In one of the previous posts I have shown one method to upload an image in android.
Here is another method to upload a media file like images,audio or video in android.
Here is the main java file that does the upload.
Here I am trying to open audio from the gallery. However you can change it to image or video according to your need.
The code for upload will not change since we change only the code for opening the gallery. We use only the path of the selected file whether it is image or video or audio to upload.

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?

package pack.coderzheaven;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
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.util.Log;

public class UploadAudioDemo extends Activity {

	private static final int SELECT_AUDIO = 2;
	String selectedPath = "";

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

        openGalleryAudio();
    }

    public void openGalleryAudio(){

   	Intent intent = new Intent();
        intent.setType("audio/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select Audio "), SELECT_AUDIO);
   }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {

	    if (resultCode == RESULT_OK) {

	        if (requestCode == SELECT_AUDIO)
	        {
	        	System.out.println("SELECT_AUDIO");
	            Uri selectedImageUri = data.getData();
	            selectedPath = getPath(selectedImageUri);
	         	System.out.println("SELECT_AUDIO Path : " + selectedPath);
	         	doFileUpload();
	        }

	    }
	}

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

    private void doFileUpload(){
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String lineEnd = "rn";
        String twoHyphens = "--";
        String boundary =  "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;
        String responseFromServer = "";
        String urlString = "http://your_website.com/upload_audio_test/upload_audio.php";
        try
        {
         //------------------ CLIENT REQUEST
        FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
         // open a URL connection to the Servlet
         URL url = new URL(urlString);
         // Open a HTTP connection to the URL
         conn = (HttpURLConnection) url.openConnection();
         // Allow Inputs
         conn.setDoInput(true);
         // Allow Outputs
         conn.setDoOutput(true);
         // Don't use a cached copy.
         conn.setUseCaches(false);
         // Use a post method.
         conn.setRequestMethod("POST");
         conn.setRequestProperty("Connection", "Keep-Alive");
         conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
         dos = new DataOutputStream( conn.getOutputStream() );
         dos.writeBytes(twoHyphens + boundary + lineEnd);
         dos.writeBytes("Content-Disposition: form-data; name="uploadedfile";filename="" + selectedPath + """ + lineEnd);
         dos.writeBytes(lineEnd);
         // create a buffer of maximum size
         bytesAvailable = fileInputStream.available();
         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);
         // close streams
         Log.e("Debug","File is written");
         fileInputStream.close();
         dos.flush();
         dos.close();
        }
        catch (MalformedURLException ex)
        {
             Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
        catch (IOException ioe)
        {
             Log.e("Debug", "error: " + ioe.getMessage(), ioe);
        }
        //------------------ read the SERVER RESPONSE
        try {
              inStream = new DataInputStream ( conn.getInputStream() );
              String str;

              while (( str = inStream.readLine()) != null)
              {
                   Log.e("Debug","Server Response "+str);
              }
              inStream.close();

        }
        catch (IOException ioex){
             Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        }
      }
}

Now the server side , the code is written in Php.

<?php
// Where the file is going to be placed
$target_path = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
    echo "filename: " .  basename( $_FILES['uploadedfile']['name']);
    echo "target_path: " .$target_path;
}
?>

Things to keep in mind
1. Make sure your server is running.
2. Your server file path should be right.
3. Check your folder write permission in the server.

Please leave your valuable comments.
Enjoy.

Show Alert in cocos2D Android.

Here is a simple example showing alert in android cocos2D.
For this I am using an example from my previous android cocos2D tutorial..
So please read that tutorial before reading this because the I am using the classes and files from it.

I am only changing the Gamelayer.java file to show an Alert Dialog when the sprite move is finished.
Check the showAlert() function which will show the Alert.

Here is the modified GameLayer.java

package com.coderzheaven.pack;

import org.cocos2d.actions.instant.CCCallFuncN;
import org.cocos2d.actions.interval.CCMoveTo;
import org.cocos2d.actions.interval.CCSequence;
import org.cocos2d.layers.CCColorLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCLabel;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGSize;
import org.cocos2d.types.ccColor3B;
import org.cocos2d.types.ccColor4B;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.view.MotionEvent;

public class GameLayer extends CCColorLayer
{
	protected CCLabel _label = null;
	CGSize winSize = CCDirector.sharedDirector().displaySize();
	int myscore = 0;

	public static CCScene scene()
	{
		CCScene scene = CCScene.node();
		CCColorLayer layer = new GameLayer(ccColor4B.ccc4(255, 255, 255, 255));
		scene.addChild(layer);
		return scene;
	}

	protected GameLayer(ccColor4B color)
	{
		super(color);
		this.setIsTouchEnabled(true);

		DBOperations();
	}

	public void DBOperations(){
		addAndroid();
		createAndInitializeTables();
		insertData(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		updateTable(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		showLabel(myscore);
	}

	public void createAndInitializeTables(){
        try{
        	MyTable mytable = new MyTable();
        	String[] tableCreateArray = {mytable.getDatabaseCreateQuery()};
    		dbOperation operation = new dbOperation(CCDirector.sharedDirector().getActivity(),tableCreateArray);
			operation.open();
			operation.close();
        }catch(Exception e){
           System.out.println("Error creating table " + e.getMessage());
        }
        System.out.println("Table successfully created!!");
	}
	public int getDataFromTable(){
		dbOperation operationObj = new dbOperation(CCDirector.sharedDirector().getActivity());
        operationObj.open();
		MyTable mytable = new MyTable();
		int score = 0;
		String  condition2 = mytable.getID() +" = 1 ";
        String[] dbFields4 = {mytable.getScore()};
        Cursor cursor =  operationObj.getTableRow(mytable.getTableName(),dbFields4,condition2,mytable.getID() + " ASC ",1 +"");
        if(cursor.getCount()>0)
        {
        	 cursor.moveToFirst();
        	 do{
        		 score = cursor.getInt(0);
        	 }while(cursor.moveToNext());
        }
        cursor.close();
		cursor.deactivate();
		operationObj.close();

		return score;
	}
	public void insertData(int score){
		MyTable mytable = new MyTable();
		dbOperation operationObj = new dbOperation(CCDirector.sharedDirector().getActivity());
        operationObj.open();
		ContentValues initialValues = new ContentValues();
    	initialValues.put(mytable.getScore(),score+"");
        operationObj.insertTableData(mytable.getTableName(),initialValues);
        int maxID = operationObj.lastInsertedID(mytable.getTableName());
        System.out.println("LAST INSERTED ID : " + maxID);
        operationObj.close();
	}
	public void updateTable(int scr){
		MyTable mytable = new MyTable();
		dbOperation operationObj = new dbOperation(CCDirector.sharedDirector().getActivity());
        operationObj.open();
        String condition = mytable.getID() + " = 1";
		ContentValues initialValues = new ContentValues();
    	initialValues.put(mytable.getScore(),scr+"");
        operationObj.updateTable(mytable.getTableName(),initialValues,condition);
        operationObj.close();
	}
	public void showLabel(int scr){

		if(_label != null){
			this.removeChild(_label,true);
		}
		_label = CCLabel.makeLabel("Score : " + scr, "Verdana", 20);
		_label.setColor(ccColor3B.ccBLACK);
		_label.setPosition(55f, winSize.height - 15);
		addChild(_label);
	}
	public void addAndroid(){
		CGSize winSize = CCDirector.sharedDirector().displaySize();
		CCSprite player = CCSprite.sprite("android.png");
		player.setPosition(CGPoint.ccp(player.getContentSize().width / 2.0f, winSize.height / 2.0f));
		addChild(player);

		CCMoveTo actionMove = CCMoveTo.action(3, CGPoint.ccp(winSize.getWidth(), winSize.getHeight()/2.0f));
		CCCallFuncN actionMoveDone = CCCallFuncN.action(this, "spriteMoveFinished");
		CCSequence actions = CCSequence.actions(actionMove, actionMoveDone);

		player.runAction(actions);
	}

	public void spriteMoveFinished(Object sender)
	{
		CCSprite sprite = (CCSprite)sender;
		this.removeChild(sprite, true);
		myscore++;
		updateTable(myscore);
		showLabel(myscore);
		showAlert();
		//addAndroid();
	}
	public void showAlert(){
		CCDirector.sharedDirector().getActivity().runOnUiThread(new Runnable() {
		    public void run() {
		    	AlertDialog.Builder builder = new AlertDialog.Builder(CCDirector.sharedDirector().getActivity());
		    	builder.setMessage("Are you sure you want to exit?")
		    	       .setCancelable(false)
		    	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		    	           public void onClick(DialogInterface dialog, int id) {
		    	        	   CCDirector.sharedDirector().getActivity().finish();
		    	           }
		    	       })
		    	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		    	           public void onClick(DialogInterface dialog, int id) {
		    	                dialog.cancel();
		    	           }
		    	       });
		    	AlertDialog alert = builder.create();
		    	alert.show();
		    }
		});
	}

	@Override
	public boolean ccTouchesBegan(MotionEvent event)
	{
		return true;
	}
}

Please copy all other files from this project before proceeding.
A sample project is available for download for this tutorial.

Alert in android cocos2D

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);
		}
}

Saving TextFile to SDCARD in android?

Hello android lovers,

In today’s tutorial I will show you how to

1. Create a text file and save a textfile in your SDCARD in your preferred path.

2. Read the contents from the same file and show it in a TextView.

For writing a file we use the FileWriter class and for reading the textfile we use the FileReader class.
Now Let’s check out how we do this .

First create a fresh project and name it “saveFileDemo”.
In the “saveFileDemo.java” file copy this contents.

package com.coderzheaven.pack;

import java.io.FileReader;
import java.io.FileWriter;

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

public class saveFileDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        createFile();
        String file_contents = readFile();
    	System.out.println("FILE CONTENTS :  "  + file_contents);

    	TextView tv = (TextView)findViewById(R.id.tv);
    	tv.setText("Read File contents from SDCARD : n" + file_contents);
    }
    public void createFile(){
    	FileWriter fWriter;
        try{
             fWriter = new FileWriter("/sdcard/myfile.txt");
             fWriter.write("My file contents");
             fWriter.flush();
             fWriter.close();
         }catch(Exception e){
                  e.printStackTrace();
         }
    }
    public String readFile(){
        char buf[] = new char[512];
        FileReader rdr;
        String contents = "";
		try {
			rdr = new FileReader("/sdcard/myfile.txt");
			int s = rdr.read(buf);
			for(int k = 0; k < s; k++){
				contents+=buf[k];
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return contents;
    }
}

This is the main.xml file contents.

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

Here is the Strings.xml file contents

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, saveFileDemo!</string>
    <string name="app_name">saveFileDemo from Coderzheaven</string>
</resources>

Now the AndroidManifest.xml file contents.

<?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">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".saveFileDemo"
                  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>


You can actually see the file by going to the FileExplorer and expanding the mnt folder(or simply SDCARD in older versions) and the SDCARD folder.
See the screenshot.

Check this link to see the contents of this file manually.

Please leave your valuable comments 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

Image transition animation in Android

Hello all…

I have shown a lot of examples of animations in android.
Today I will show you how to show an image transition animation between two images. For that you have to create an xml named “expand_collapse.xml” inside the res/drawable folder.

The contents of “expand_collapse.xml” are

<transition xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:drawable="@drawable/android_1" />
      <item android:drawable="@drawable/android_2" />
</transition>

Now in the main.xml place an imageView to show the transition

<?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"
    >
<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/toggle_image"
    />
</LinearLayout>

Now in the main java file I will show you how to apply this transition.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.widget.ImageView;

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

        Resources res = getApplicationContext().getResources();
        TransitionDrawable transition = (TransitionDrawable) res.getDrawable(R.drawable.expand_collapse);
        ImageView image = (ImageView) findViewById(R.id.toggle_image);
        image.setImageDrawable(transition);

        transition.startTransition(5000);
   }
}

How to create a custom layout for your camera in Android?

Hello everyone,

Today’s example shows how to create a custom layout for your camera preview, that is if you want a custom layout while your camera is opening.
This example helps you to achieve this.

First create a fresh project and name it CameraCustomLayout and copy this code to CameraCustomLayout.java file.

package com.coderzheaven.pack;

import java.io.IOException;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;

public class CustomCameraActivity extends Activity implements SurfaceHolder.Callback {

	Camera camera;
	SurfaceView surfaceView;
	SurfaceHolder surfaceHolder;
	boolean previewing = false;
	LayoutInflater controlInflater = null;

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

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        getWindow().setFormat(PixelFormat.UNKNOWN);
        surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        controlInflater = LayoutInflater.from(getBaseContext());
        View viewControl = controlInflater.inflate(R.layout.custom, null);
        LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT,
        								   					LayoutParams.FILL_PARENT);
        this.addContentView(viewControl, layoutParamsControl);
    }

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		if(previewing){
			camera.stopPreview();
			previewing = false;
		}

		if (camera != null){
			try {
				camera.setPreviewDisplay(surfaceHolder);
				camera.startPreview();
				previewing = true;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		camera = Camera.open();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		camera.stopPreview();
		camera.release();
		camera = null;
		previewing = false;
	}
}

After that create an xml file named custom.xml inside the res/layout folder and copy this code into it.
This is the layout which comes when you open the camera in your device.

<?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:gravity="left">

	<Button
		android:text="Click Me"
		android:id="@+id/Button01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</Button>
	<Button
		android:text="Click Me too"
		android:id="@+id/Button02"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</Button>
</LinearLayout>

Now in the main.xml file copy this code.
This file contains the SurfaceView which holds the cameraPreview.

<?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"
    >
<SurfaceView
	android:id="@+id/camerapreview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
</LinearLayout>

Now you are done.
Note : Please run it on a real device, because camera will not work on the emulator.

You can download the source code from here.
PLease dont forget to comment on this post if you like it.

Parsing an XML from Online in Android

In the previous example I showed how to parse an xml that is stored in a file in res/xml folder.
In this post I will show you how to parse an xml that is stored in a server in an xml file.

Here I am using an xml that is stored in here

Here is the java code for that.

First create a fresh project and name it ParseXMLDemo

Then in the ParseXMLDemo.java file copy this code

package com.coderzheaven.pack;

import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

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

        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        String xml = ParseXMLMethods.getXML();
        Document doc = ParseXMLMethods.XMLfromString(xml);

        int numResults = ParseXMLMethods.numResults(doc);

        if((numResults <= 0)){
        	Toast.makeText(ParseXMLDemo.this, "There is no data in the xml file", Toast.LENGTH_LONG).show();
        	finish();
        }

		NodeList children = doc.getElementsByTagName("os");

		for (int i = 0; i < children.getLength(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			Element e = (Element)children.item(i);
			map.put("id", ParseXMLMethods.getValue(e, "id"));
        	map.put("name", ParseXMLMethods.getValue(e, "name"));
        	map.put("site", ParseXMLMethods.getValue(e, "site"));
        	mylist.add(map);
		}

        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.list_layout,
                        new String[] { "name", "site" },
                        new int[] { R.id.title, R.id.subtitle});

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		@SuppressWarnings("unchecked")
				HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
        		Toast.makeText(ParseXMLDemo.this,o.get("name"), Toast.LENGTH_LONG).show();
			}
		});
    }
}

Now create another java file inside the src folder and name it ParseXMLMethods.java and copy this contents into it.

package com.coderzheaven.pack;

import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class ParseXMLMethods {

	public final static Document XMLfromString(String xml){

		Document doc = null;

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
	        is.setCharacterStream(new StringReader(xml));
	        doc = db.parse(is);

		} catch (ParserConfigurationException e) {
			System.out.println("XML parse error: " + e.getMessage());
			return null;
		} catch (SAXException e) {
			System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
		} catch (IOException e) {
			System.out.println("I/O exeption: " + e.getMessage());
			return null;
		}
        return doc;
	}

	 public final static String getElementValue( Node elem ) {
	     Node kid;
	     if( elem != null){
	         if (elem.hasChildNodes()){
	             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
	                 if( kid.getNodeType() == Node.TEXT_NODE  ){
	                     return kid.getNodeValue();
	                 }
	             }
	         }
	     }
	     return "";
	 }

	 public static String getXML(){
			String line = null;

			try {

				DefaultHttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost("http://coderzheaven.com/xml/test.xml");

				HttpResponse httpResponse = httpClient.execute(httpPost);
				HttpEntity httpEntity = httpResponse.getEntity();
				line = EntityUtils.toString(httpEntity);

			} catch (Exception e) {
				line = "Internet Connection Error >> " + e.getMessage();
			}
			return line;
	}

	public static int numResults(Document doc){
		Node results = doc.getDocumentElement();
		int res = -1;
		try{
			res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
		}catch(Exception e ){
			res = -1;
		}
		return res;
	}

	public static String getValue(Element item, String str) {
		NodeList n = item.getElementsByTagName(str);
		return ParseXMLMethods.getElementValue(n.item(0));
	}
}

Now the main layout file main.xml

<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="@id/android:list"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:layout_weight="1"
	    android:background="#FF0000"
	 	android:drawSelectorOnTop="false" />
</LinearLayout>

Create another file named list_layout.xml inside the 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:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="7dp"
    >
<TextView
	android:id="@+id/title"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:padding="2dp"
    android:textSize="20dp"
    android:textStyle="bold"
    />
    <TextView
	android:id="@+id/subtitle"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:textSize="14dp"
    android:textColor="#000000" />
</LinearLayout>

This is the Strings.xml file

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, ParseXMLDemo!</string>
    <string name="app_name">ParseXMLDemo Coderzheaven.com</string>
</resources>

Now you are done go on and run the application.

Parse XML in Android

Parse XML in Android

Get the full source code from here and don’t forget to comment on this post.

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.

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.

How to change the default transition between activities?

In android the default transition between activities is to slide from left to right.
But with custom animations we can change that.

First create a folder inside the res/drawable folder called “anim”.
Then create a file named “fade.xml” and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:fromAlpha="0.0" android:toAlpha="1.0"
       android:duration="@android:integer/config_longAnimTime" />

create another file named “hold.xml” in the same place
hold.xml.

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:fromXDelta="0" android:toXDelta="0"
       android:duration="@android:integer/config_longAnimTime" />

activity_animation.xml

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

    <TextView
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip"
        android:text="Sample Animation"/>

    <Button android:id="@+id/fade_animation"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="fade In">
        <requestFocus />
    </Button>
</LinearLayout>

Now the main java file.

package pack.coderzheaven;

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

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

        Button button = (Button)findViewById(R.id.fade_animation);
        button.setOnClickListener(mFadeListener);
    }

    private OnClickListener mFadeListener = new OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(ActivityAnimation.this, SecondClass.class));
            overridePendingTransition(R.anim.fade, R.anim.hold);
        }
    };
}

package pack.coderzheaven;

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

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

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="Second Class"
    />
</LinearLayout>

How to create a custom ListView in android?

Hello all…..

In today’s tutorial I will show you how to create a custom listview in android.
For that we need 3java files.
One holding the ListView itself another a Model object that holds the data for the listview and the third one for the Adapter which extends the ArrayAdapter class for holding the model.

First the Model.java file

package pack.coderzheaven;

public class Model {

	private String name;
	private String place;
	private boolean selected;

	public Model(String name, String place) {
		this.name = name;
		this.place = place;
		selected = false;
	}

	public String getName() {
		return name;
	}

	public String getPlace() {
		return place;
	}

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

	public void setPlace(String place) {
		this.place = place;
	}

	public boolean isSelected() {
		return selected;
	}

	public void setSelected(boolean selected) {
		this.selected = selected;
	}

}

Now the second file MyCustomArrayAdapter.java that extends the Arrayadapter class.

package pack.coderzheaven;

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.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

public class MyCustomArrayAdapter extends ArrayAdapter<Model> {

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

	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, sub;
		protected CheckBox checkbox;
	}

	@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.sub = (TextView) view.findViewById(R.id.sub);
			viewHolder.sub.setTextColor(Color.GRAY);
			viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
			viewHolder.checkbox
					.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
						@Override
						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							Model element = (Model) viewHolder.checkbox.getTag();
							element.setSelected(buttonView.isChecked());
							System.out.println("Checked : " + element.getName());
						}
					});
			view.setTag(viewHolder);
			viewHolder.checkbox.setTag(list.get(position));
		} else {
			view = convertView;
			((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
		}
		ViewHolder holder = (ViewHolder) view.getTag();
		holder.text.setText(list.get(position).getName());
		holder.sub.setText(list.get(position).getPlace());
		holder.checkbox.setChecked(list.get(position).isSelected());
		return view;
	}
}

Now the main Java file which is named ModelListViewActivity.java

package pack.coderzheaven;

import java.util.ArrayList;
import java.util.List;

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

public class ModelListViewActivity extends ListActivity {

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);

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

	private List<Model> getModel() {
		List<Model> list = new ArrayList<Model>();
		list.add(get("Android","Google"));
		list.add(get("Windows 7","Microsoft"));
		list.add(get("iPhone","Apple"));
		list.add(get("Ubuntu","Linux"));
		list.add(get("Bada","Samsung"));
		list.add(get("Android","Google"));
		list.add(get("Symbian","Nokia"));
		list.add(get("Windows 7","Microsoft"));
		list.get(1).setSelected(true);	// select one item by default
		return list;
	}

	private Model get(String s,String place) {
		return new Model(s,place);
	}
}

Now the layout for each row in the ListView. – list_layout.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">
	<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="20px"></TextView>
	<TextView android:text="@+id/sub"
		android:layout_below="@+id/label"
			android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:id="@+id/sub"
		android:layout_marginLeft="15dp"
		android:textSize="15px"></TextView>
	<CheckBox android:id="@+id/check" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:layout_marginLeft="4px"
		android:layout_marginRight="10px" android:layout_alignParentRight="true"
		></CheckBox>
</RelativeLayout>

Now the main.xml file that holds the ListView.

<?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="@id/android:list"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:background="@drawable/customshape"
			android:dividerHeight="1px"
			android:cacheColorHint="#0000"
			android:clipToPadding="true"
			android:layout_margin="5dp"
			android:soundEffectsEnabled="true"
			android:scrollbars="none">
	</ListView>
</LinearLayout>

customshape.xml (in the drawable folder)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
             <gradient
                android:endColor ="#000000"
                android:startColor="#FFFF0000"
                android:angle="270" />
            <stroke
                android:width="0dp"
                android:color="#C2C2C2" />
            <corners
                android:radius="5dp" />
        </shape>
    </item>   
</selector>

Now the AndroidManifest.xml file.

<?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">
    <uses-sdk android:minSdkVersion="6" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ModelListViewActivity"
                  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>
Custom ListView

Custom ListView

How to create a splash screen in android?

Hello everyone today i will show you how to create a splash screen in android.
This is one of the simplest ways to create a splash screen however there are another ways to create the splash screen.
Lets look at the code.

We need two layouts one for the splash screen and another for the first screen that comes after splash screen.

The splash screen layout will look like this.
splashscreen.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">
    <ImageView android:src="@drawable/android"
    android:layout_width="fill_parent"
     android:id="@+id/imageView1"
     android:layout_height="fill_parent"></ImageView>
</LinearLayout>

Now 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="Splash screen Demo from CoderzHeaven"
    />
</LinearLayout>

Now the main java file.

package pack.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;

public class SplashScreenDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashscreen);
        creatingSplashScreen();
    }

	private void createFirstScreen()
	{
	    	   setContentView(R.layout.main);
	}

	private void creatingSplashScreen()
	{
		 new CountDownTimer(5000, 1000) {
                   public void onTick(long millisUntilFinished)
		     {
		     }

		     public void onFinish() {
		    	 createFirstScreen();
		     }
		  }.start();
	}
}

Make sure you have an image named “android.png” or “android.jpg” in your res/drawable folder.

How to Upload Multiple files in one request along with other string parameters in android?

Hello everyone,

I have shown two methods to upload files in android.
In today’s tutorial I will show another simple method to upload files. With this method you can upload multiple files in one request + you can send your own string parameters with them.

Here is another method on working with uploading of images.
How to upload an image from Android device to server? – Method 4

These are the things to do after creating the project.
1. You have to include two libraries in the your project build path(Download these libraries from here apache-mime4j-0.6.jar and httpmime-4.0.1.jar).
2. Add these libraries to the project build path.
3. Here you can see the the other things you need to remember while connecting to a server.

Refer the image

Note : I am working here on the local system as server. So I have used the server domain name as 10.0.2.2. Please change this according to your need.

OK Now open your main java file and copy this code into it.

package pack.coderzheaven;

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
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 FileUploadTest extends Activity {

	private static final int SELECT_FILE1 = 1;
	private static final int SELECT_FILE2 = 2;
	String selectedPath1 = "NONE";
	String selectedPath2 = "NONE";
	TextView tv, res;
	ProgressDialog progressDialog;
	Button b1,b2,b3;
	HttpEntity resEntity;

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

        tv = (TextView)findViewById(R.id.tv);
        res = (TextView)findViewById(R.id.res);
        tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
        b1 = (Button)findViewById(R.id.Button01);
        b2 = (Button)findViewById(R.id.Button02);
        b3 = (Button)findViewById(R.id.upload);
        b1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				openGallery(SELECT_FILE1);
			}
		});
        b2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				openGallery(SELECT_FILE2);
			}
		});
        b3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
					progressDialog = ProgressDialog.show(FileUploadTest.this, "", "Uploading files to server.....", false);
		       		 Thread thread=new Thread(new Runnable(){
		           	        public void run(){
		           	       		doFileUpload();
		           	            runOnUiThread(new Runnable(){
		           	                public void run() {
		           	                    if(progressDialog.isShowing())
		           	                    	progressDialog.dismiss();
		           	                }
		           	            });
		           	        }
		   	        });
		   	        thread.start();
				}else{
	  	                	Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
				}
	        }
		});

    }

    public void openGallery(int req_code){

   	 	Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
   }

   public void onActivityResult(int requestCode, int resultCode, Intent data) {

	    if (resultCode == RESULT_OK) {
	    	Uri selectedImageUri = data.getData();
	        if (requestCode == SELECT_FILE1)
	        {
	            selectedPath1 = getPath(selectedImageUri);
	         	System.out.println("selectedPath1 : " + selectedPath1);
	        }
	        if (requestCode == SELECT_FILE2)
	        {
	            selectedPath2 = getPath(selectedImageUri);
	         	System.out.println("selectedPath2 : " + selectedPath2);
	        }
	        tv.setText("Selected File paths : " + selectedPath1 + "," + selectedPath2);
	    }
	}

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

    private void doFileUpload(){

    	File file1 = new File(selectedPath1);
    	File file2 = new File(selectedPath2);
        String urlString = "http://10.0.2.2/upload_test/upload_media_test.php";
        try
        {
        	 HttpClient client = new DefaultHttpClient();
             HttpPost post = new HttpPost(urlString);
	         FileBody bin1 = new FileBody(file1);
	         FileBody bin2 = new FileBody(file2);
	         MultipartEntity reqEntity = new MultipartEntity();
	         reqEntity.addPart("uploadedfile1", bin1);
	         reqEntity.addPart("uploadedfile2", bin2);
	         reqEntity.addPart("user", new StringBody("User"));
	         post.setEntity(reqEntity);
	         HttpResponse response = client.execute(post);
	         resEntity = response.getEntity();
	         final String response_str = EntityUtils.toString(resEntity);
	         if (resEntity != null) {
	             Log.i("RESPONSE",response_str);
	        	 runOnUiThread(new Runnable(){
	 	                public void run() {
	 	                	 try {
	 	                		res.setTextColor(Color.GREEN);
	 							res.setText("n Response from server : n " + response_str);
	 							Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
	 						} catch (Exception e) {
	 							e.printStackTrace();
	 						}
	 	                   }
	 	            });
	         }
        }
        catch (Exception ex){
             Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
      }
}

Now the layout for this file 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="Multiple File Upload from CoderzHeaven"
    />
<Button
    android:id="@+id/Button01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get First File">
</Button>
<Button
    android:id="@+id/Button02"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get Second File">
</Button>
<Button
    android:id="@+id/upload"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start Upload">
</Button>
<TextView
	android:id="@+id/tv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Selected File path : "
    />

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

Now the AndroidManifest file(Remember to add the permission for accessing internet)

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

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

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".FileUploadTest"
                  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>

Now the server side(Here it is written in PHP)
upload_media_test.php file contents

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

$target_path2 = $target_path2 . basename( $_FILES['uploadedfile2']['name']);
if(move_uploaded_file($_FILES['uploadedfile2']['tmp_name'], $target_path2)) {
    echo "n The second file ".  basename( $_FILES['uploadedfile2']['name']).
    " has been uploaded.";
} else{
    echo "There was an error uploading the file, please try again!";
    echo "filename: " .  basename( $_FILES['uploadedfile2']['name']);
    echo "target_path2: " .$target_path2;
}

$user = $_REQUEST['user'];
echo "n String Parameter send from client side : " . $user;
?>


Please leave your comments. If you like this post, please hit a “+1″ for this post and share it across your networks.