Tag Archives: Dialog

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

Hello all……

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

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

main.xml

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

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

simplerow.xml

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

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

This is the main java file that implements this xml.

“SimpleListViewActivity.java”

package com.coderzheaven.pack;

import java.util.ArrayList;

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

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

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

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

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

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

  }

}

OK Done. Now run it and see the result.

Slide delete

Slide delete

Slide delete

Join the Forum discussion on this post

Download.

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

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

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

package com.coderzheaven.filesexample;

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

public class MainActivity extends Activity implements OnClickListener {

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

}

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

package com.coderzheaven.filesexample;

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

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

public class MyFile {

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

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

Now the layout for the xml file.

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

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


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

</LinearLayout>

Note you should give this permission in the AndroidManifest file.

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

OK Done. Now run the project.

To view the files

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

Files Example

Download
.

Please leave your valuable comments on this post.

Join the Forum discussion on this post

How to show two different DatepickerDialogs on same activity with only one listener function in android?

In android for each time picker Dialog we can associate with a dialog. So with this dialog and a global variable we can have any number of Dialog listeners. Here is the sample java code.

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:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnChangeDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Date" />
    
     <Button
        android:id="@+id/btnChangeDate2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Date2" />

    <TextView
        android:id="@+id/lblDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Current Date (M-D-YYYY): "
        android:textAppearance="?android:attr/textAppearanceLarge" />
  
    <TextView
        android:id="@+id/tvDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />
    
     <TextView
        android:id="@+id/tvDate2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

MyAndroidAppActivity .java


import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MyAndroidAppActivity extends Activity {

	private TextView tvDisplayDate, tvDisplayDate2;
	private DatePicker dpResult;
	private Button btnChangeDate, btnChangeDate2;

	private int year;
	private int month;
	private int day;

	static final int DATE_DIALOG_ID = 1;
	static final int DATE_DIALOG_ID2 = 2;
	int cur = 0;

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

		setCurrentDateOnView();
		addListenerOnButton();

	}

	// display current date
	public void setCurrentDateOnView() {

		tvDisplayDate = (TextView) findViewById(R.id.tvDate);
		tvDisplayDate2 = (TextView) findViewById(R.id.tvDate2);

		final Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);

		// set current date into textview
		tvDisplayDate.setText(new StringBuilder()
				// Month is 0 based, just add 1
				.append(month + 1).append("-").append(day).append("-")
				.append(year).append(" "));

		tvDisplayDate2.setText(tvDisplayDate.getText().toString());
	}

	public void addListenerOnButton() {

		btnChangeDate = (Button) findViewById(R.id.btnChangeDate);

		btnChangeDate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				showDialog(DATE_DIALOG_ID);

			}

		});
		btnChangeDate2 = (Button) findViewById(R.id.btnChangeDate2);

		btnChangeDate2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				showDialog(DATE_DIALOG_ID2);

			}

		});

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		
		case DATE_DIALOG_ID:
			System.out.println("onCreateDialog  : " + id);
			cur = DATE_DIALOG_ID;
			// set date picker as current date
			return new DatePickerDialog(this, datePickerListener, year, month,
					day);
		case DATE_DIALOG_ID2:
			cur = DATE_DIALOG_ID2;
			System.out.println("onCreateDialog2  : " + id);
			// set date picker as current date
			return new DatePickerDialog(this, datePickerListener, year, month,
					day);
		
		}
		return null;
	}

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

		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			
			year = selectedYear;
			month = selectedMonth;
			day = selectedDay;

			if(cur == DATE_DIALOG_ID){
				// set selected date into textview
				tvDisplayDate.setText("Date1 : " + new StringBuilder().append(month + 1)
						.append("-").append(day).append("-").append(year)
						.append(" "));
			}
			else{
				tvDisplayDate2.setText("Date2 : " + new StringBuilder().append(month + 1)
						.append("-").append(day).append("-").append(year)
						.append(" "));
			}

		}
	};

}

Time Picker Dialog

Time Picker Dialog

Please leave your valuable comments on this post.

How to stream an audio in Android?

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

Here is the java code for that.

package com.coderzheaven.pack;

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

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

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

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

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

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

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

This is the xml that contains the button.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Stream Audio and Play"
    android:id="@+id/play"
    />
</LinearLayout>

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

Stream_1

Stream_2

Stream_3

Please leave your valuable comments on this post.

How to override hardware Home button in android? OR How to listen to home button click in android?

Hello everyone…

In this post I will show you how to listen to hardware button in an android smartphone.

This post especially shows how to listen to the home button in android. But my advice is never override the home button in your app.
Home button is to move the currently running process to background. But you can override the Backbutton and other buttons, android allows that on the keyDown Method. But if you try to match the “Home” button in the keyDown method it will not work. For that we have to follow another way which is shown in this post.

This simple java code handles the button pressed.

package test.test;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.WindowManager;

public class Test2Activity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_HOME)) {
        	System.out.println("KEYCODE_HOME");
        	showDialog("'HOME'");
            return true;
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        	System.out.println("KEYCODE_BACK");
        	showDialog("'BACK'");
            return true;
        }
        if ((keyCode == KeyEvent.KEYCODE_MENU)) {
        	System.out.println("KEYCODE_MENU");
        	showDialog("'MENU'");
            return true;
        }
        return false;
    }
    
    void showDialog(String the_key){
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setMessage("You have pressed the " + the_key + " button. Would you like to exit the app?")
    		  .setCancelable(true)
    	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	   dialog.cancel();
    	        	   finish();
    	           }
    	       })
    	       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	                dialog.cancel();
    	           }
    	       });
    	AlertDialog alert = builder.create();
    	alert.setTitle("CoderzHeaven.");
    	alert.show();
    }
    
    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);           
    }
    
    public void onUserLeaveHint() { // this only executes when Home is selected.
    	// do stuff
    	super.onUserLeaveHint();
    	System.out.println("HOMEEEEEEEEE");
    }
}

When “onUserLeaveHint()” function is defined you can actually listen to the home button press and do some saving of data or something.

 public void onUserLeaveHint() { // this only executes when Home is selected.
    	// do stuff
    	super.onUserLeaveHint();
    	System.out.println("HOMEEEEEEEEE");
    }

Home button override

Home button override

Home button override

Please leave your comments on this post and share it on the social Networks.

How to sign an android APK, a simplest way

Hello all..

This post is also about how to sign an android apk to publish it to the android market.
I have already shown another method to sign the apk, which is through the command line.

How to sign an android APK ? – a simplest way

Here is another simple method without using the command line options to create a keystore file and then sign your apk to upload to the android or any other markets such as amazon markets.

1. OK we will start by creating a sample project named “Test”.

Look at the screenshot 1.

2. Now double click on the AndroidManifest.xml file.
Set the appropriate version number and version code for your project.

3. Now below this there is a link called “use the export wizard”. Click on that.

then another window will open, there select your desired project.

4. click Next, then you will be asked for a keystore, if you have a keystore file then browse and locate the file.
OR
Create a new one.
If you have a keystore file the after locating the file you have to give the password.

Click on Finish and your APK file will be created in the destination directory.

If you are creating a new one then…

Go through these steps by filling in the details that appear in the dialog.

Clicking on Finish will create your signed APK.

5. Now Give a location for you signed apk file.- Click finish -> Your signed APK is ready for upload to the market.

Please leave your valuable comments on this post. PLease share it if you like this post, so that it will be helpful to others also.

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

Actually this is really simple.

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

How to Download an image in ANDROID programatically?

This is another one little different with a progressbar included.

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

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

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

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

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

This is the contents of main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
	android:id="@+id/tv1"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Downloading File with ProgressBar Demo From Coderzheaven"
    />
<Button 
	android:id="@+id/b1"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Download File"
    android:onClick="downloadFile"
    />
</LinearLayout>

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

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

package com.coderzheaven.pack;

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

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

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

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

    		//connect
    		urlConnection.connect();

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

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

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

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

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

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

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

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

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

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

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

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

OK now we have customized the progressbar.

This line sets the progressbar to green color.

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

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

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

These two are the permissions we need .


This is the AndroidManifest file for this example.

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

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

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

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

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

Check the screen shot..

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

Download.

Date and TimePicker in ANDROID.

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

package AndroidDatePicker.pack;

import java.util.Calendar;

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

public class AndroidDatePicker extends Activity {

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

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

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

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

   @Override
   public void onClick(View v) {

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

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

   @Override
   public void onClick(View v) {

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

	 @Override
	 protected Dialog onCreateDialog(int id) {

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

	  }
	 }

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

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

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

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

Starting with NDK for Android – A Simple example. OR How to run a C code in android?

Hello Friends….

Today I am going to talk about how to use ndk in android to run c code.

Note : These steps are for Mac and Linux Users not for Windows users.

Follow these step exactly to set up and run ndk in android.

1. I think that you are having your eclipse and android uptodate.
2. Go to this place “http://developer.android.com/sdk/ndk/index.html” and download the ndk for your operating system.


3. After downloading the zip, extract it and save it in your own location.

4. Now we are going to create the android Project.
I am naming it “NDKDemo” and the activity is named “NDKDemoActivity”.

Now create a folder named “jni” in the project.

5. Click on jni folder-> then go to “Run Menu” > external tools > external tools configuration.

6. Click on Program and click on the new icon (first icon) on the top. On the right side Give the NDK a name.

In the Next Location textbox Click on “Browse File System” and located the ndk-build that you just downloaded from “developer.android.com

7. Now in the Workspace location > Click on Browse Workspace and select your “jni” folder in the “NDKDemo” project directory.

This dialog comes when you click the Browse Workspace button and select the jni folder in your project and click OK.

8. Now create a file named “Android.mk” file inside the “jni” folder.

copy this code to “Android.mk” file.

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_LDLIBS := -llog

LOCAL_MODULE    := ndkdemo
LOCAL_SRC_FILES := native.c

include $(BUILD_SHARED_LIBRARY)

9. Now create another file named “native.c” inside the jni folder and copy this code into it.
This is our c code.
This don’t look purely like a c code because it has some java elements inside it.

#include <jni.h>
#include <string.h>
#include <android/log.h>

#define DEBUG_TAG "NDKDemoActivity"

void Java_com_coderzheaven_pack__NDKDemoActivity_printLog(JNIEnv * env, jobject this, jstring logString)
{
    jboolean isCopy;
    const char * szLogString = (*env)->GetStringUTFChars(env, logString, &isCopy);

    __android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "NDK: %s", szLogString);

    (*env)->ReleaseStringUTFChars(env, logString, szLogString);
}

Note :
Please take a look the function name

Java_com_coderzheaven_pack__NDKDemoActivity_printLog

This naming should be in this format
“Java_packagename_funtionname(arguments)”

Also one more thing the “dots” (.) in the package name should be replaced by underscore in the function name”. This is important.

OK Everything needed for NDK is done.
10. Now what we have to do is to compile the c code. For that go to “Run” > external tools > select NDK you created and run.

Now the c code has been compiled.

11. Now in the java Activity copy this code

package com.coderzheaven.pack;

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

public class NDKDemoActivity extends Activity {
	  static {
	        System.loadLibrary("ndkdemo");
	    }

	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);
	        printLog("Hello Coderzheaven");
	    }

	    private native void printLog(String logThis);
}

12. Now run this project and check the Logcat for the message after calling the C function from android.

You can any number of c functions inside the native.c code and run it.
Make sure to put a declaration on top of the activity before calling.

Please leave your comments if this post was useful.

How to use Calendar in Android?

Hello all…….

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

Here is the java source code for this example.

package com.coderzheaven.pack;

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

public class CalendarTestDemo extends Activity {

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

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

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

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

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

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

    }

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

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

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

}

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_margin="10dp">
    >
	<TextView
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="Calendar Demo from Coderzheaven"
	    android:layout_margin="10dp"
	    />
	<EditText
		android:text=""
		android:id="@+id/EditText01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_margin="10dp">
	</EditText>
	<Button
		android:text="Show Calendar"
		android:id="@+id/Button01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_marginLeft="10dp">
	</Button>
</LinearLayout>

Please leave your valuable comments on this post.

ListView with Sections in android.

Hello all……….

We have seen many posts about ListViews like creating a listview, adding data to it, customizing a listview etc.

Take a look at some of these examples

1. Single Selection ListView in android
2. Flitering a ListView using an input from an EditText in Android.
3. How to create a custom ListView in android?
4. Android dialog with ListView.
5. Expandable ListView in ANDROID using SimpleExpandableListAdapter, a simple example.
6. Android listView with icons.
7. Creating scrolling ListView in android.

ListView with sections in android

ListView with sections in android

Today also we will see another customization of listviews.
Today I will show you how to create listviews with sections.

This is the main.xml layout file which contains 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"
    android:background="@drawable/orange"
    >
    <ListView
		 	android:id="@+id/list1"
			android:cacheColorHint="#00000000"
			android:scrollbars="none"
			android:background="@drawable/bg_transparent"
			android:fadingEdge="vertical"
			android:soundEffectsEnabled="true"
			android:divider="@drawable/green"
			android:dividerHeight="1px"
			android:padding="0dip"
			android:smoothScrollbar="true"
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content"
		    android:drawSelectorOnTop="false"
		    android:layout_marginTop="5dip"
		    android:layout_marginLeft="5dip"
		    android:layout_marginRight="5dip"
		    android:layout_marginBottom="5dip"
		    android:layout_weight="1"/>

</LinearLayout>

I am using some resources in this, one of which is the “customshape_header.xml” file which is saved in res/drawable directory.
This will ptovide the background for the section header.
customshape_header.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="3dp" />
    <solid android:color="#FFFFFF"/>
    <stroke
        android:width="1dip"
        android:color="#C0C0FF" />
</shape>

Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ListView with Sections</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="orange">#FFA500</drawable>
	<drawable name="darkgrey">#606060</drawable>
</resources>

This is the “lv_layout.xml” file which I am using for each row in 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"
    android:id="@+id/l1"
    >
</LinearLayout>

Now the main java file which implements the logic for creating the listview with sections.

package com.coderzheaven.pack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class SectionListViewDemo extends Activity {

	ListView L1;
	myAdapter myadp;
	String last_item = "B";
	static final String[] labels_array = new String[] {
		  "Afghanistan", "Albania",
		  "Bahrain", "Bangladesh",
		  "Cote d'Ivoire", "Cambodia",
		  "Estonia", "Ethiopia", "Faeroe Islands",
		  "Former Yugoslav Republic of Macedonia"
		};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        L1 = (ListView)findViewById(R.id.list1);
        myadp = new myAdapter(this,labels_array);
        L1.setAdapter(myadp);

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

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

  	   public View getView(int position, View convertView, ViewGroup parent)
  		{
  	 		   try{
  	 				LayoutInflater inflater=getLayoutInflater();
  	 				row = inflater.inflate(R.layout.lv_layout, parent, false);

  	 				LinearLayout L1 = (LinearLayout)row.findViewById(R.id.l1);
  	 				TextView header = new TextView(getApplicationContext());
  	 				L1.addView(header);
  	 				TextView label = new TextView(getApplicationContext());
  	 				L1.addView(label);
  					System.out.println("LAST : " + last_item);
  					header.setText(last_item);
  					label.setText(labels_array[position]);
  					label.setPadding(4, 1, 1, 1);
  					L1.setPadding(4, 4, 4, 4);

  					label.setTextColor(Color.BLACK);

  					if(!labels_array[position].substring(0,1).equalsIgnoreCase(last_item)){
  						System.out.println("ADD :  " + last_item);
  						header.setBackgroundResource(R.drawable.customshape_header);
  						header.setPadding(4, 1, 1, 1);
  						row.setEnabled(false);
  						header.setTextColor(Color.BLACK);
  						header.setText(labels_array[position].substring(0,1));
  						//label.setVisibility(View.GONE);
  						//position-=2;
  					}else{
  						System.out.println("REM :  " + last_item);
  						header.setVisibility(View.GONE);
  					}
  					last_item = labels_array[position].substring(0,1);

  	 		   }catch(Exception e){

  			   }
  		    return row;
  		}
    }
}

Now its ready to run the application.

Please leave your valuable comments on this post.

Custom Alert in android.

We can create any type of alert in android.
Today I will show a simple example showing how to create a custom alert in android.

i.e you can provide any layout to your alert dialog.

Now we will start.

First create an xml for your alert dialog.
Here I am creating an xml that contains a textView, an imageView, two editText, a ratingbar and a button.
All these are placed inside a scrollview.
create a new xml file named “custom_alert.xml” in the res/layout folder and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center|center_horizontal" >

<ScrollView
	android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:fadeScrollbars="true">

    <LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center|center_horizontal" >

		<TextView
			android:text="Custom Alert"
			android:id="@+id/TextView01"
			android:layout_width="fill_parent"
			android:gravity="center"
			android:layout_gravity="center|center_horizontal"
			android:layout_height="wrap_content">
		</TextView>

		<ImageView
			android:id="@+id/ImageView01"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_gravity="center|center_horizontal">
		</ImageView>

		<EditText
			android:text="CoderzHeaven"
			android:id="@+id/EditText01"
			android:layout_margin="5dp"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content">
		</EditText>

		<EditText
			android:text=""
			android:id="@+id/EditText02"
			android:layout_margin="5dp"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content">
		</EditText>

		<RatingBar
			android:id="@+id/RatingBar01"
			android:layout_width="wrap_content"
			android:layout_margin="5dp"
			android:layout_height="wrap_content">
		</RatingBar>

		<Button
			android:text="Close App"
			android:id="@+id/Button01"
			android:layout_gravity="center|center_horizontal"
			android:layout_width="fill_parent"
			android:layout_margin="5dp"
			android:layout_height="wrap_content">
		</Button>

	</LinearLayout>
</ScrollView>
</LinearLayout>

Now in your main java file copy this code.

package com.coderzheaven.pack;

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

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

        showAlert();
    }

    public void showAlert(){
    	 Dialog dialog = new Dialog(this);
         dialog.setContentView(R.layout.custom_alert);
         dialog.setTitle("This is a custom dialog box");
         dialog.setCancelable(true);

         TextView text = (TextView) dialog.findViewById(R.id.TextView01);
         text.setText("Custom alert demo");

         ImageView img = (ImageView) dialog.findViewById(R.id.ImageView01);
         img.setImageResource(R.drawable.android_3);

         Button button = (Button) dialog.findViewById(R.id.Button01);
         button.setOnClickListener(new OnClickListener() {
         @Override
             public void onClick(View v) {
                 finish();
             }
         });
         dialog.show();
    }
}

The showAlert function will create the Dialog with the custom layout and show it.

This is the main.xml. Actually we dont need this .

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

Here is the AndroidManifest.xml

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

Custom Alert in Android

Please leave your valuable comments on this post

Changing the style or theme of default alertDialog in Android.

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

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

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

package com.coderzheaven.pack;

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

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

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


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

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

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

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

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

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

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

</resources>

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


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


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

How to install an APK into your device or emulator through command prompt or shell.

In this post I will show you how to install an apk on to the emulator or the device through the shell or command prompt.
Before experimenting with this post I assume that you have these done

1. Installed the Android SDK.
2. Added the adb path to the environment path.

This is how you add the path to the environment variable.

On Linux, edit your ~/.bash_profile or ~/.bashrc file. Look for a line that sets the PATH environment variable and add the full path to your $SDK_ROOT/tools to it. If you don’t see a line setting the path, you can add one:

export PATH=${PATH}: On a Mac, look in your home directory for .bash_profile and proceed as for Linux. You can create the .bash_profile, if you haven’t already set one up on your machine.
On Windows, right click on My Computer, and select Properties. Under the Advanced tab, hit the Environment Variables button, and in the dialog that comes up, double-click on Path under System Variables, and add the full path to the tools/ directory under $SDK_ROOT to it.

Now In windows Go to command prompt and type

C: adb devices

if you have correctly set your path then your android devices will be listed here.

then copy your apk to the C: directory and issue this command

C:adb install your_apk.apk

Take a look at the screenshot. Here I am installing CreateTable.apk that is located in the C: directory.

Install the APK onto emulator.

Install the APK onto emulator or device

How to disable any input on the screen in android?

This is a simple example showing how will you disable any input on your current application screen in android.
This is done by showing a transparent overlay dialog on the screen.
This is how it is done.

package pack.coderzheaven;

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

public class DisableInputDemo extends Activity {

	Dialog overlayDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b = (Button)findViewById(R.id.Button01);
        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				disableAnyInput();
			}
		});
    }

    public void disableAnyInput(){
    	Toast.makeText(getApplicationContext(), "This will disable any input. Click the backbutton " +
    					"to enable any input.", Toast.LENGTH_LONG).show();
    	 overlayDialog = new Dialog(DisableInputDemo.this, android.R.style.Theme_Panel);
    	 overlayDialog.setCancelable(true);
         overlayDialog.show();
    }
}

The layout for the above java 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="How to disable any input on the screen? Coderzheaven Demo"
    />
<EditText
	android:text=""
	android:hint="Type anything"
	android:id="@+id/EditText01"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content">
</EditText>
<Button
	android:text="Click me to disable any input"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
</LinearLayout>
Disable any input in android

Disable any input in android

Android dialog with ListView

For implementing a ListView, we first create a xml which contains a ListView named list.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">

  <ListView
    android:id="@+id/listview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
</LinearLayout>

Next we create a Dialog Object and inflate the above xml and when the listItem is clicked then a Alert Dialog windows comes
The java file is listed below


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class DialoglistView extends Activity implements OnItemClickListener{
    /** Called when the activity is first created. */
	String[] val = {"sunday","monday","tuesday","thrusday","friday","wednesday","march"};
	ListView list;
	Dialog listDialog;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         showdialog();
    }

    private void showdialog()
    {
    	listDialog = new Dialog(this);
    	listDialog.setTitle("Select Item");
    	 LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    	 View v = li.inflate(R.layout.list, null, false);
    	 listDialog.setContentView(v);
    	 listDialog.setCancelable(true);
         //there are a lot of settings, for dialog, check them all out!

         ListView list1 = (ListView) listDialog.findViewById(R.id.listview);
         list1.setOnItemClickListener(this);
         list1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, val));
         //now that the dialog is set up, it's time to show it
         listDialog.show();
    }

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Delete item "+arg2)
		           .setPositiveButton("OK ", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   System.out.println("OK CLICKED");

		           }
		       });
		builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	        	 dialog.dismiss();
	        	 listDialog.cancel();

	           }
	       });

		AlertDialog alert = builder.create();
		alert.setTitle("Information");
		alert.show();
	}
}

The alert window look like this

When the Item is selected then