Monthly Archives: May 2012

How to use Accelerometer in Android?

This is a simple post showing how to use accelerometer in android.

This java code prints the values of x,y and z axis in the console.

package com.coderzheaven.pack;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;

public class AccelerometerTest extends Activity  implements SensorEventListener{
	 private SensorManager sensorManager;
	 double ax,ay,az;   // these are the acceleration in x,y and z axis

    @Override
    public void onCreate(Bundle savedInstanceState) {
    	 super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
         sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    }
    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
         if (event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
             		 ax=event.values[0];
                     ay=event.values[1];
                     az=event.values[2];
                     System.out.println("X = " + ax + ", Y = " + ay +", Z = " + az);
             }
    }
 }

Leave your comments on this post.
Find Coderzheaven on facebook, twitter , google Plus and MySpace for more updates.

Facebook May Acquire Opera

It is rumoured that facebook is employing ex- Apple iPhone and iPad Engineers to build their own smartphone.

Now there is another rumour that facebook may acquire Opera.

Facebook could be set to pursue a deal for web browser firm Opera, as the social network seeks to unlock new business opportunities.

Flush with a $16bn (£10bn) war chest after a troubled initial public offering this month, Mark Zuckerberg’s company is understood to be readying its next major acquisition after the $1.17bn purchase of photo-sharing app Instagram.

Read more about it from here…

http://www.digitalspy.co.uk/tech/news/a383952/facebook-rumoured-for-opera-browser-acquisition.html

How to send email from Android Emulator?

Hello all…

Emailing may be a basic requirement in many of our applications. So I am showing you how to send email from your emulator in android.

For that you have to configure an email client in the emulator.

Follow these steps to configure an email client in the android emulator.

Send Mail in Android Emulator

Send Mail in Android Emulator

Send Mail in Android Emulator

Send Mail in Android Emulator

Send Mail in Android Emulator

Send Mail in Android Emulator

Send Mail in Android Emulator

Send Mail in Android Emulator

OK Now you are ready to send email from your emulator.

Check this post to find how to send an email from Andriod programatically.

http://www.coderzheaven.com/2011/05/16/send-email-from-and-android-application-programatically/

Please leave your valuable comments on this post.

Facebook releases new camera app for iPhone.

The company has announced Facebook Camera for iPhone, an app dedicated to shooting photos, applying filters, and batch uploading photos to your Timeline. The app was developed independently from Facebook for iOS by the Facebook Photos team, Photos product manager Dirk Stoop told me, and is focused on letting you share photos as quickly as possible and in higher-resolution than before.

Read more about this story from here.

http://www.washingtonpost.com/business/technology/facebook-camera-for-iphone-launches-with-filters-and-batch-photo-uploads/2012/05/25/gJQAWIAMpU_story.html

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

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

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

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

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

Single Choice List

Google didn’t infringe on Oracle patents, jury rules

A federal jury ruled Wednesday that Google didn’t infringe on Oracle’s patents when the Internet search leader developed its popular Android software for mobile devices.

Wednesday’s verdict comes about two weeks after the same jury, with two additional members, failed to agree on a pivotal issue in Oracle’s copyright-infringement case against Google. As a result, Google Inc. faced maximum damages of only $150,000 – not the hundreds of millions of dollars that Oracle Corp. was seeking.

Read more: http://www.foxnews.com/scitech/2012/05/24/google-didnt-infringe-on-oracle-patents-jury-rules/#ixzz1voVv0n3S

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.

Google Chrome overtaking Internet Explorer.

Google’s Chrome is now the most popular Web browser worldwide, surpassing Microsoft’s Internet Explorer for the first time, according to the latest figures from StatCounter. After years of slowly chipping away Internet Explorer’s market share, Chrome took the lead with 32.76 percent share, while IE dipped to 31.94 percent.

Read More from here
http://www.pcworld.com/article/255886/google_chrome_overtakes_internet_explorer.html

Apple again the most valuable brand.

Apple took the top spot for the second year in a row, beating out IBM, Google, and McDonald’s to assume the position of the world’s most valuable brand.

At $183 billion, Apple is the world’s most valuable brand, according to Millward Brown Optimor’s annual BrandZ study. Apple was last year’s most valuable brand, as well, though the company’s value jumped 19 percent over last year’s $153.3 billion tally.

Read more from here..

http://news.cnet.com/8301-1001_3-57439046-92/apple-again-the-worlds-most-valuable-brand-google-third/

How to create a Custom Toggle Button in android?

Hello everyone…

In today’s tutorial I will show you how to create a custom toggle button in android. Often in our applications we don’t need a default toggle button, so I will show you how to change that to make a toggle button according to your need.

First I will create a fresh project named “CustomToggleButton” and name the main activity “CustomToggleButtonDemo”.

Now These are the two images that I am using to create the toggle button.

add icon

delete icon

First the layout file main.xml that contains the toggle 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"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<ToggleButton 
	android:background="@drawable/btn_toggle_bg"
	style="@style/OurThemeName" 
	android:checked="true"
	android:id="@+id/ToggleButton01" 
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content">
</ToggleButton>

</LinearLayout>

This will create a toggle button.

Now we will make an xml that contains the resource definition that applies when the button toggles and the background of the button.
We will make the button background transparent and for toggle action we will create another xml that contains the “on” and “off” resource for the button.

Create a new file inside the drawable folder and name it “btn_toggle_bg.xml” and copy this code to 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" android:drawable="@android:color/transparent" />
    <item android:id="@+android:id/toggle" android:drawable="@drawable/btn_toggle" />
</layer-list>

Now create another xml inside the drawable folder and name it “btn_toggle.xml” and it contains …

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/add_icon" />
    <item android:state_checked="false" android:drawable="@drawable/delete_icon" />
</selector>

This means that when the button is on(true) the image will be “add_icon.png” and when “off” the image will be “delete_icon.png”.

Now we are going to write a theme that is to be applied to the toggle button that overrides the default android theme.

Create a new file called “themes.xml” inside the strings folder and copy this code to it.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Overwrite the ToggleButton style -->
<style name="Widget.Button.Toggle" parent="android:Widget">
    <item name="android:background">@drawable/btn_toggle_bg</item>
    <item name="android:textOn">Add</item>
    <item name="android:textOff">Del</item>
    <item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
</style>

<style name="OurThemeName"  parent="@android:Theme.Black">
    <item name="android:buttonStyleToggle">@style/Widget.Button.Toggle</item>
      <item name="android:textOn"></item>
    <item name="android:textOff"></item>
</style>
</resources>

Please look at the main.xml file where this theme has been applied.

Here

<ToggleButton 
	android:background="@drawable/btn_toggle_bg"
	<strong>style="@style/OurThemeName" </strong>
	android:checked="true"
	android:id="@+id/ToggleButton01" 
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content">
</ToggleButton>

OK now our custom toggle button is ready. Go on and run it.

Custom toggle button

Custom toggle button

Actually we dont need the activity java file because everything can be done in the xml itself.

Download the complete source code from here.

New iPhone may be getting Larger screens.

iPhone

The new iPhone that Apple Inc. is expected to unveil this year is likely to have a larger display than its current models have, with the company ordering bigger screens from its Asian suppliers, people familiar with the matter said.

The new screens measure at least 4 inches diagonally, the people said, compared with 3.5 inches on Apple’s latest model, the iPhone 4S. Production is set to begin next month, the people said. Analysts have predicted that the next iPhone will come out in the fall.

Read more from here..

http://online.wsj.com/article/SB10001424052702303360504577407610487811698.html?mod=googlenews_wsj

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

HTC Desire C specifications

The Desire C has a 3.5-inch screen with a resolution of 320 x 480. It uses a 600 MHz processor and is apparently being marketed as a 3.5 G device, presumably meaning HSDPA. Internal storage is 4 GB, and the phone has a five megapixel camera. The phone will run Android 4.0.

. It’ll run on the country’s 3.5G network (HSDPA to you and me) and you’ll find Ice Cream Sandwich sharing the room on that 4GB of on-board storage. It’s also reported to have a 1,320mAh battery and will retail for €200 ($260) once it’s finished enjoying the Iberian weather.

HTC desire C

PhoneEasy 740, the world’s simplest Android phone!

The latest device to be unveiled by Doro is probably their most interesting ever, as it combines Android’s functionality with an easy to use interface and pretty decent hardware. The PhoneEasy 740 is still in the last stages of pre-production, but the manufacturers are hoping to iron out all the little kinks in time for a US release before the end of the summer.

Sporting a 320-by-480 3.2-inch touchscreen, the PhoneEasy 740 has a slide-out keyboard and features 512 MB of RAM, 4 GB of on-board storage, a 5-megapixel rear-facing camera, 3G and WiFi connectivity, Bluetooth 4.0, and a microSD memory card slot. That’s not too shabby for a device that is set to be made available at a very affordable price, and the software is itself surprisingly functional.

The app store (Doro Selection) only features 15 apps right now.

The internet-enabled handset extends support to the 3G network speed to ensure swift web browsing. It is accompanied by a charging cradle. Needless to say, the Android phone lets users access the Google Play store to download applications. The GPS certified gadget is deployed with Doro Experience, that’s a cloud based software for remotely managing the device with the assistance of a Windows PC. Relatives of the user can load or delete applications and control its features from anywhere on the globe.

It will be made available in summer this year

Doro Simplest Android Phone

Samsung Galaxy S III India launch in June first week

Samsung is expected to launch its all new Galaxy S III smartphone in India in the first week of June. According to NDTV Gadgets, India is in the first list of countries to get smartphone, which will see the launch starting May 29.

The smartphone will be priced at INR 38,000, while the street price is likely to be in the vicinity of INR 34,000.

Samsung Galaxy S III features a 4.8-inch Super AMOLED display, 1.4GHz quad core processor, 8MP rear camera, 1.9MP front camera and Android 4.0 with Touchwiz Nature UX.

S3

S3

Siri Says Nokia Lumia 900 is the best smartphone.

It’s like now Siri is also turning against Apple. Apple bought Siri to market their phone iPhone4S. And you will get Siri after buying iPhone4S for more than 800$. Isn’t that funny. However there are still many alternatives avaliable for android out there and for free.

We are not fools to buy a phone for a software.

Now Siri is also talking against apple.

Siri Loves Nokia Lumia 900

Credit : PCWorld

See this news here..

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 download a file from a remote site in android? – Another simple example – Method -3

Hello all …….

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

These are other methods for downloadign a file in android.

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

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

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

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

So this is the java code that downloads the file.

package com.coderzheaven.pack;

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

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

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

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

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

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

This is the xml file that contains the button.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="File Download Demo from Coderzheaven \n\nFile to download : http://coderzheaven.com/sample_folder/sample_file.png \n\nSaved Path : sdcard/\n"
    />
<Button 
	android:text="Download File" 
	android:id="@+id/Button01" 
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content">
</Button>
</LinearLayout>

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

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

download file android

download file android

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

CoderzHeaven on Facebook, Twitter, Google Plus and MySpace

Hello…….

Coderzheaven is now on MySpace also. PLease checkout our page at http://www.myspace.com/coderzheaven

Fore more news on updates and exciting code snippets please add Coderzheaven to your connections in Facebook

http://facebook.com/coderzheaven

and Also find us on twitter and get the latest tweets on recent and most popular posts.

http://twitter.com/coderzheaven

Also find us on Google PLus

We Coderz

How to check different Network status in Android?

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

package com.coderzheaven.pack;

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

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

Lowest Cost for LUMIA 900 on Amazon- Get it fast.

For AT&T customers eying one of Nokia’s Windows Phone 7 devices as an upgrade, Amazon is offering the stylish new Lumia 900 on the cheap… real cheap. So cheap, in fact, you have to wonder what’s up. Are Nokia’s phones failing on the market even though they’re getting great reviews? Or is Microsoft merely trying to saturate the market with this flagship device before the arrival of Apple’s iPhone 5, taking a hit in the wallet?

Lowest Cost for LUMIA 900

Lowest Cost for LUMIA 900

More from this link..

http://www.tomsguide.com/us/Amazon-Windows-Phone-7-Nokia-Microsoft-Lumia-900,news-15084.html

Best Budget phones in android market today.

Here are my choice of some of the best phones in android market today.

1. Sony ericsson Xperia Neo.

We know Sony always makes stylish phones. Here is another stylish phone from Sony Ericsson.

Specifications.

GENERAL
2G Network GSM 850 / 900 / 1800 / 1900
3G Network HSDPA 900 / 2100
HSDPA 850 / 1900 / 2100

BODY
Dimensions 116 x 57 x 13 mm
Weight 126 g

DISPLAY
Type LED-backlit LCD, capacitive touchscreen, 16M colors
Size 480 x 854 pixels, 3.7 inches (~265 ppi pixel density)
Multitouch Yes
Protection Scratch-resistant glass
- Sony Mobile BRAVIA Engine
- Timescape UI

SOUND
Alert types Vibration; MP3 ringtones
Loudspeaker Yes
3.5mm jack Yes
MEMORY
Card slot microSD, up to 32GB, 8 GB included
Internal 320 MB storage, 512 MB RAM
DATA GPRS Yes
EDGE Yes
Speed HSDPA, 7.2 Mbps; HSUPA, 5.76 Mbps
WLAN Wi-Fi 802.11 b/g/n, DLNA, Wi-Fi hotspot
Bluetooth Yes, v2.1 with A2DP
USB Yes, microUSB v2.0
CAMERA Primary 8 MP, 3264×2448 pixels, autofocus, LED flash
Features
Video calling, touch focus, geo-tagging, face and smile detection
Video Yes, 720p@30fps, continuous autofocus, video light
Secondary Yes
FEATURES OS Android OS, v2.3.4 (Gingerbread), planned upgrade to v4.0
Chipset Qualcomm MSM8255 Snapdragon
CPU 1 GHz Scorpion
GPU Adreno 205
Sensors Accelerometer, proximity, compass
Messaging SMS (threaded view), MMS, Email, IM, Push Email
Browser HTML, Adobe Flash
Radio Stereo FM radio with RDS
GPS Yes, with A-GPS support
Java Yes, via Java MIDP emulator
Colors Blue Gradient, Red, Silver
- SNS integration
- HDMI port
- MP4/H.264/WMV player
- MP3/WMA/WAV/eAAC+ player
- TrackID music recognition
- Organizer
- Document viewer
- Voice memo/dial/commands
- Predictive text input
BATTERY Standard battery, Li-Ion 1500 mAh
Stand-by Up to 430 h (2G) / Up to 400 h (3G)
Talk time Up to 6 h 55 min (2G) / Up to 7 h (3G)
Music play Up to 31 h

Price Range $300 – $350 (ebay)

2. Sony Ericsson Xperia ray

Specifications

GENERAL 2G Network GSM 850 / 900 / 1800 / 1900
3G Network HSDPA 900 / 2100 – ST18i
HSDPA 850 / 1900 / 2100 – ST18a
Announced 2011, June
Status Available. Released 2011, August
BODY Dimensions 111 x 53 x 9.4 mm
Weight 100 g
DISPLAY Type LED-backlit LCD, capacitive touchscreen, 16M colors
Size 480 x 854 pixels, 3.3 inches (~297 ppi pixel density)
Multitouch Yes
Protection Scratch-resistant glass
- Bravia Mobile engine
- Touch sensitive controls
- Timescape UI
SOUND Alert types Vibration, MP3 ringtones
Loudspeaker Yes
3.5mm jack Yes
MEMORY Card slot microSD, up to 32GB, 4GB included
Internal 1 GB (300 MB user available), 512 MB RAM
DATA GPRS Up to 86 kbps
EDGE Up to 237 kbps
Speed HSDPA, 7.2 Mbps; HSUPA, 5.8 Mbps
WLAN Wi-Fi 802.11 b/g/n, DLNA, Wi-Fi hotspot
Bluetooth Yes, v2.1 with A2DP, EDR
USB Yes, microUSB v2.0
CAMERA Primary 8 MP, 3264×2448 pixels, autofocus, LED flash
Features Geo-tagging, face and smile detection, touch focus, image stabilization
Video Yes, 720p, video light
Secondary Yes
FEATURES OS Android OS, v2.3 (Gingerbread), planned upgrade to v4.0
Chipset Qualcomm MSM8255 Snapdragon
CPU 1 GHz Scorpion
GPU Adreno 205
Sensors Accelerometer, proximity, compass
Messaging SMS (threaded view), MMS, Email, Push email, IM
Browser HTML, Adobe Flash
Radio Stereo FM radio with RDS
GPS Yes, with A-GPS support
Java Yes, via Java MIDP emulator
Colors Black, Gold, White, Pink
- SNS integration
- MP4/H.263/H.264 player
- MP3/WAV player
- TrackID music recognition
- SensMe
- Google Search, Maps, Gmail,
YouTube, Calendar, Google Talk
- Document viewer
- Voice memo
- Predictive text input
BATTERY Standard battery, Li-Ion 1500 mAh
Stand-by Up to 430 h (2G) / Up to 440 h (3G)
Talk time Up to 6 h 50 min (2G) / Up to 7 h (3G)
Music play Up to 36 h

Price Below $300

3. Samsung Galaxy Ace S5830

Specifications

GENERAL 2G Network GSM 850 / 900 / 1800 / 1900
3G Network HSDPA 900 / 2100
HSDPA 850 / 1900 – Samsung Galaxy Ace S5830L
Announced 2011, January
Status Available. Released 2011, February
BODY Dimensions 112.4 x 59.9 x 11.5 mm
Weight 113 g
- Touch-sensitive controls
DISPLAY Type TFT capacitive touchscreen, 16M colors
Size 320 x 480 pixels, 3.5 inches (~165 ppi pixel density)
Multitouch Yes
Protection Corning Gorilla Glass
- TouchWiz v3.0 UI
SOUND Alert types Vibration; MP3, WAV ringtones
Loudspeaker Yes
3.5mm jack Yes
- DNSe sound enhancement
MEMORY Card slot microSD, up to 32GB, 2GB included
Internal 158 MB storage, 278 MB RAM
DATA GPRS Yes
EDGE Yes
Speed HSDPA, 7.2 Mbps
WLAN Wi-Fi 802.11 b/g/n, DLNA, Wi-Fi hotspot
Bluetooth Yes, v2.1 with A2DP
USB Yes, microUSB v2.0
CAMERA Primary 5 MP, 2592×1944 pixels, autofocus, LED flash
Features Geo-tagging, face and smile detection
Video Yes, VGA@24fps
Secondary No
FEATURES OS Android OS, v2.3
Chipset Qualcomm MSM7227
CPU 800 MHz ARM 11
GPU Adreno 200
Sensors Accelerometer, proximity, compass
Messaging SMS(threaded view), MMS, Email
Browser HTML
Radio Stereo FM radio with RDS
GPS Yes, with A-GPS support
Java Yes, via Java MIDP emulator
Colors Black, White, Hugo Boss Edition, La Fleur
- MP4/H.264/H.263 player
- MP3/WAV/eAAC+ player
- Organizer
- Document editor
- Image editor
- Google Search, Maps, Gmail,
YouTube, Calendar, Google Talk, Picasa integration
- Voice memo/dial
- Predictive text input (Swype)
BATTERY Standard battery, Li-Ion 1350 mAh
Stand-by Up to 640 h (2G) / Up to 420 h (3G)
Talk time Up to 11 h (2G) / Up to 6 h 30 min (3G)

Price Below $300

4. Motorola DEFY

Specifications

GENERAL 2G Network GSM 850 / 900 / 1800 / 1900
3G Network HSDPA 900 / 2100
HSDPA 1700 / 2100 or HSDPA 850 / 1900
Announced 2010, September
Status Available. Released 2010, October
BODY Dimensions 107 x 59 x 13.4 mm
Weight 118 g
- Dust and water resistant
- Touch-sensitive controls
DISPLAY Type TFT capacitive touchscreen, 16M colors
Size 480 x 854 pixels, 3.7 inches (~265 ppi pixel density)
Multitouch Yes
Protection Corning Gorilla Glass
- Touch sensitive controls
- MOTOBLUR UI with Live Widgets
SOUND Alert types Vibration; MP3, WAV ringtones
Loudspeaker Yes
3.5mm jack Yes
MEMORY Card slot microSD, up to 32GB, 2GB included
Internal 2 GB storage, 512 MB RAM
DATA GPRS Class 12 (4+1/3+2/2+3/1+4 slots), 32 – 48 kbps
EDGE Class 12
Speed HSDPA, 7.2 Mbps; HSUPA, 2 Mbps
WLAN Wi-Fi 802.11 b/g/n, DLNA, Wi-Fi hotspot (Android 2.2)
Bluetooth Yes, v2.1 with A2DP
USB Yes, microUSB v2.0
CAMERA Primary 5 MP, 2592х1944 pixels, autofocus, LED flash
Features Geo-tagging, image stabilization
Video Yes, VGA@30fps
Secondary No
FEATURES OS Android OS, v2.1 (Eclair), upgradable to v2.2
Chipset TI OMAP 3610
CPU 800 MHz Cortex-A8
GPU PowerVR SGX530
Sensors Accelerometer, proximity, compass
Messaging SMS (threaded view), MMS, Email, IM, Push Email
Browser HTML, Adobe Flash Lite
Radio Stereo FM radio with RDS
GPS Yes, with A-GPS support
Java Yes, via Java MIDP emulator
Colors Black, White
- Active noise cancellation with dedicated mic
- MP3/WAV/WMA/AAC+ player
- MP4/WMV/H.263/H.264 player
- Google Search, Maps, Gmail, YouTube, Google Talk
- Facebook, Twitter, MySpace integration
- Document viewer
- Photo viewer/editor
- Organizer
- Voice memo/dial/commands
- Predictive text input
BATTERY Standard battery, Li-Po 1540 mAh
Stand-by Up to 238 h
Talk time Up to 6 h 48 min

Price : $300 – $350 (ebay)