Monthly Archives: April 2012

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.

Zoom In animation between Two Activities.

Hello everyone…

I have already shown you how to override default animation between activities.
Today I will show a zoom in and out animation between activities.

Take a look at this post for another animation between activities.

Create files named zoom_enter.xml and zoom_exit.xml in the res/anim folder.

zoom_enter.xml file contents.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/decelerate_interpolator">
    <scale android:fromXScale="2.0" android:toXScale="1.0"
           android:fromYScale="2.0" android:toYScale="1.0"
           android:pivotX="50%p" android:pivotY="50%p"
           android:duration="@android:integer/config_mediumAnimTime" />
</set>

zoom_exit.xml file contents.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:zAdjustment="top">
    <scale android:fromXScale="1.0" android:toXScale=".5"
           android:fromYScale="1.0" android:toYScale=".5"
           android:pivotX="50%p" android:pivotY="50%p"
           android:duration="@android:integer/config_mediumAnimTime" />
    <alpha android:fromAlpha="1.0" android:toAlpha="0"
            android:duration="@android:integer/config_mediumAnimTime"/>
</set>

Now replace this is in the previous post

overridePendingTransition(R.anim.fade, R.anim.hold);

with this code

overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);

Now run the application and you are done.
You will see a zoom in animation between the activities.
Refer this post for the rest of the code

How to Play Audio using Corona SDK ?

Hi,

For playing audio – background music or sound effects – using Corona SDK, do the following,

1. Load the audio stream (background music or sound effects)

 backgroundMusic = audio.loadStream("bgm.mp3") 

2. Play the audio

backgroundMusicChannel = audio.play( backgroundMusic, { channel=1, loops=-1, fadein=5000 }  )  

It will play the background music on channel 1, loop infinitely, and fadein over 5 seconds. Loop 1 will set it to play once!
:)

How to move a body manually in Box2D? or Give a force to a body in Box2D, iPhone.

This is a sample code to move a body in Box2D .
First you have to make a body with variable name “moving_rec” and call the below function in a schedular at regular intervals.

-(void) moveBody{
       b2Vec2 force = b2Vec2(0,0);
       force = b2Vec2(0,3);       //Giving the x an y to negative will move the body in opposite direction.
       moving_rec->SetLinearVelocity(force); //set Linear velocity for moving in a constant speed.
}

Please leave your comments on this post.

Creating a JButton component in swing

Java swing provides a native look and feel that emulates the look and feel of several platforms.
Here i am going to create a Button and adding it to Frame.

For this first create a Jframe object,a JPanel object and a Container object

JFrame f = new JFrame();
JPanel panel1 = new JPanel();
Container con = f.getContentPane();

Then Create a button object and add this ti JPanel object

JButton panel1_but = new JButton();
panel1.add(panel1_but);

and finally add JPanel to JFrame

panel1.add(panel1_but);

This full code is given below

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class mainframe implements WindowListener
{
	JFrame f = new JFrame();
	Container con = f.getContentPane();
	JPanel panel1 = new JPanel();
	mainframe()
	{
		createpanel1();
		f.addWindowListener(this);
		f.setSize(900, 600);
		f.setVisible(true);
		f.setLocationRelativeTo(null);
		f.setResizable(false);    ///cannot maximize
	   	f.setVisible(true);
	}
	public static void main(String args[])
	{
		new mainframe();
	}
	private void createpanel1()
	{
		JButton panel1_but = new JButton();
		panel1_but.setBounds(new Rectangle(450,400,200,40));
		panel1_but.setText("Continue");

		panel1.add(panel1_but);
		panel1_but.addActionListener(new java.awt.event.ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				//action to be performed....
			}
			}
		);
		panel1.setLayout(new BorderLayout());
		panel1.setBackground(Color.white);
		panel1.setVisible(true);
		con.add(panel1);
	}

	@Override
	public void windowActivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowClosed(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowClosing(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
}

How to include multiple c files to compile in android NDK?

I ran into problem when I had multiple C files in my project. Single C file was OK for me.
I was getting undefined reference error while doing this.
Then I found out the solution after a lot of search in google.

You can check this post before going through this post.
This is about setting up NDK in MAC.
Starting with NDK for Android – A Simple example. OR How to run a C code in android?

I have to make the change in the Android.mk file to include other files to compile.

This is the content of my Android.mk file

LOCAL_PATH := $(call my-dir)
 
include $(CLEAR_VARS)
 
LOCAL_LDLIBS := -llog
 
LOCAL_MODULE    := ndksetup
LOCAL_SRC_FILES := native.c test.c test_2.c
 
include $(BUILD_SHARED_LIBRARY)

Here is my native.c code in which I am including those two files test.c and test2.c


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

// my test file 
#include "test.h"
#include "test_2.h"

#define DEBUG_TAG "NDKSetupActivity"
 
void Java_com_ndksetup_NDKSetupActivity_printLog(JNIEnv * env, jobject this, jstring logString)
{
    jboolean isCopy;
    const char * szLogString = (*env)->GetStringUTFChars(env, logString, &isCopy);
 
    __android_log_print(ANDROID_LOG_DEBUG, "TAGGGGG", "NDK: %s", szLogString);
 
    (*env)->ReleaseStringUTFChars(env, logString, szLogString);
}
int Java_com_ndksetup_NDKSetupActivity_fibonacci(int value)
{
	int p = 8;
	printMe();
	printMe2();
	return p;
}

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

Hello all….

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

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

These are for downloading files from the server.

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

Now we will see another method.

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

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

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<Button  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="Upload File"
	    android:id="@+id/but"
    />
    
	<TextView  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="@string/hello"
	    android:id="@+id/tv"
	    android:textColor="#00FF00"
	    android:textStyle="bold"
    />
 </LinearLayout>

Now the java code.
UploadImageDemo.java

package com.coderzheaven.pack;

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

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

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

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

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

OK Our Android part is over.

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

So the path is like this.

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

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


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

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

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


Please leave your valuable comments on this post.

Pause And Resume iPhone Game Using Cocos2D

More than usually we need to apply the functions of Pause and Resume/Play for our games. In Mac’s cocos2D programming it’s more than simple. Simply use the following code for Pause & Resume where ever you want!

/*For Pausing the game*/

[[CCDirector sharedDirector] pause];
[self pauseSchedulerAndActions]; //Call for pausing all schedulers and actions

/*For Resuming/Playing back the game*/

[[CCDirector sharedDirector] resume];
[self resumeSchedulerAndActions]; // Call for resuming all schedulers and actions

:)

How to Refresh a HTML Page Using JavaScript ?

Hi,

Most probably you may have encountered a situation where you have to refresh the web page in your code.
Here is, how it could be done using JavaScript.











Here on button click it will call the function ‘refresh_yourPage()’, and it will refresh the page!

:)

How to enable retina Mode in Corona SDK? or How to work with images in retina Mode in Corona?

To enable retina mode in your application you have to first find the config.lua file in your project folder.

Then edit this file to include the contents like this.

application =
{
	content =
	{
		width = 320,
		height = 480,
		scale = "letterbox",
		imageSuffix =
			{
				["-x15"] = 1.5,		-- A good scale for Droid, Nexus One, etc.
				["-x2"] = 2,		-- A good scale for iPhone 4 and iPad
			},
	}
}

You have to include images twice the size(["-x2"] = 2) and about 1.5 the size (["-x15"] = 1.5) in your project folder. These images should have correspondingly these suffixes at the end.
your_image_name-x2.png or jpg for x2(double size) images and
your_image_name-x15.png or jpg for x15 (1.5 size images) images

Corona SDK will automatically detect the right images for retina display according to the device. For example if the device has no retina display then it will take images with no x2 suffix and like that.

Please leave your valuable comments if this post was useful.

JSON IN ANDROID.

Complex JSON String parsing in ANDROID

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

Parsing JSON Object in ANDROID.

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

How to explicitly free memory in android OR Release unwanted memory in Android?

If you are writing memory consuming applications there is a bigger chance that your application may be running out of memory after sometime. So there are some methods in android that invokes the garbage collector explicitly.

See the following function which invokes the garbage collector to free a lot of memory.

public void freeMemory(){		
    System.runFinalization();
    Runtime.getRuntime().gc();
    System.gc();
}

A little explanation about the methods.

Java.Lang.Runtime.RunFinalization Method
Provides a hint to the VM that it would be useful to attempt to perform any outstanding object finalization.

Both System.gc() is effectively equivalent to Runtime.gc(). System.gc() internally calls Runtime.gc().
The only diff is System.gc() is a class method where as Runtime.gc() is an instance method. So, System.gc() is more convenient.

Using Tabbars in ANDROID, A Simple Example……….

This is a simple example showing how to use tabbars in ANDROID.
First create a new project and copy this code to it.

package com.coderzheaven;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

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

        /** TabHost will have Tabs */
        TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

        /** TabSpec used to create a new tab.
         * By using TabSpec only we can able to setContent to the tab.
         * By using TabSpec setIndicator() we can set name to tab. */

        /** tid1 is firstTabSpec Id. Its used to access outside. */
        TabSpec firstTabSpec = tabHost.newTabSpec("tab_id1");
        TabSpec secondTabSpec = tabHost.newTabSpec("tab_id2");
        TabSpec thirdTabSpec = tabHost.newTabSpec("tab_id3");

        /** TabSpec setIndicator() is used to set name for the tab. */
        /** TabSpec setContent() is used to set content for a particular tab. */
        firstTabSpec.setIndicator("First").setContent(new Intent(this,FirstTab.class));
        secondTabSpec.setIndicator("Second ").setContent(new Intent(this,SecondTab.class));
        thirdTabSpec.setIndicator("Third").setContent(new Intent(this,ThirdTab.class));

        /** Add tabSpec to the TabHost to display. */
        tabHost.addTab(firstTabSpec);
        tabHost.addTab(secondTabSpec);
        tabHost.addTab(thirdTabSpec);

    }
}

Now create three another java files by right clicking the src folder and name it FirstTab.java, SecondTab.java, ThirdTab.java.

Now copy the following code to FirstTab.java.

package com.coderzheaven;

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

public class FirstTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* First Tab Content */
		TextView textView = new TextView(this);
		textView.setText("First Tab");
		setContentView(textView);
	}
}

SecondTab.java

package com.coderzheaven;

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

public class SecondTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Second Tab");
		setContentView(textView);

	}
}
 

Now ThirdTab.java.

package com.coderzheaven;

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

public class ThirdTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Third Tab");
		setContentView(textView);

	}
}
 

Main.xml file

<?xml version="1.0" encoding="utf-8"?>
<TabHost android:layout_width="fill_parent"
	android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@android:id/tabhost">
	<LinearLayout android:id="@+id/LinearLayout01"
		android:orientation="vertical" android:layout_height="fill_parent"
		android:layout_width="fill_parent">
		<TabWidget android:id="@android:id/tabs"
			android:layout_height="wrap_content" android:layout_width="fill_parent"></TabWidget>
		<FrameLayout android:id="@android:id/tabcontent"
			android:layout_height="fill_parent" android:layout_width="fill_parent"></FrameLayout>
	</LinearLayout>
</TabHost>

AndroidManifest.xml

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

TabBar in ANDROID Demo

You can place anything in each tab by setting the contentView or dynamically adding controls.
You can do anything with this tabbar by editing the xml, like placing it below or giving images for each tab etc etc….

Please leave your valuable comments…

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

Hi all…..

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

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

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

String     res  =    null;
try {

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

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

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

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

Want More then

Follow this link

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

Please leave your comments on this post.

Java Applet MouseEvents

A simple event based applet applications is described below
First importing the necessary header files
// Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=”MouseEvents” width=300 height=100>
</applet>
*/
Next step is to create a class which implements the “MouseListener” and “MouseMotionListener ”
public class MouseEvents extends Applet implements MouseListener,
MouseMotionListener {
String msg = “”;
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = “Mouse clicked.”;
repaint();
}
Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = “Mouse entered.”;
repaint();
}
Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = “Mouse exited.”;
repaint();
}
Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = “Down”;
repaint();
}
Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = “Up”;
repaint();
}
Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = “*”;
showStatus(“Dragging mouse at ” + mouseX + “, ” + mouseY);
repaint();
}
Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus(“Moving mouse at ” + me.getX() + “, ” + me.getY());
}
Display msg in applet window at current X,Y location. This “paint” method is called when JVM execute “repaint()” function . The “paint” method will refresh the screen
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}

Collision detection in Box2D

Hi,

Collision can be detected simply using the following lines of code with box2D.

if((contact.fixtureA == aimFixture && contact.fixtureB == tarFixture) ||
     (contact.fixtureA == tarFixture&& contact.fixtureB == aimFixture ))
     {
        NSLog(@"Collision between aim fixture and target fixture detected!");
     }

Here aimFixture & tarFixture are two custom fixtures whose collision you want to find out.
:)

How to show preview of older posts at random in Blogger ?

Hi,
If you want to show the preview of your older posts at random in blogger page then use the following steps
1. Go to your blogger ‘Design’
2. Click ‘Add A Gadget’
3. Add ‘HTML/JavaScript’
4. Paste the following JavaScript code into it and save

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<style media="screen" type="text/css">
<!--

#spylist {
overflow:hidden;
margin-top:5px;
padding:0px 0px;
height:350px;
}
#spylist ul{
width:218px;
overflow:hidden;
list-style-type: none;
padding: 0px 0px;
margin:0px 0px;
}
#spylist li {
width:204px;
padding: 5px 5px;
margin:0px 0px 5px 0px;
list-style-type:none;
float:none;
height:70px;
overflow: hidden;
background:#fff url(http://i879.photobucket.com/albums/ab351/bloggerblogimage/blogger/post.jpg) repeat-x;
border:1px solid #ddd;
}

#spylist li a {
text-decoration:none;
color:#4B545B;
font-size:11px;
height:18px;
overflow:hidden;
margin:0px 0px;
padding:0px 0px 2px 0px;
}
#spylist li img {
float:left;
margin-right:5px;
background:#EFEFEF;
border:0;
}
.spydate{
overflow:hidden;
font-size:10px;
color:#0284C2;
padding:2px 0px;
margin:1px 0px 0px 0px;
height:15px;
font-family:Tahoma,Arial,verdana, sans-serif;
}

.spycomment{
overflow:hidden;
font-family:Tahoma,Arial,verdana, sans-serif;
font-size:10px;
color:#262B2F;
padding:0px 0px;
margin:0px 0px;
}

-->
</style>

    <script language="JavaScript">

imgr = new Array();

imgr[0] = "http://i43.tinypic.com/orpg0m.jpg";

imgr[1] = "http://i43.tinypic.com/orpg0m.jpg";

imgr[2] = "http://i43.tinypic.com/orpg0m.jpg";

imgr[3] = "http://i43.tinypic.com/orpg0m.jpg";

imgr[4] = "http://i43.tinypic.com/orpg0m.jpg";
showRandomImg = true;

boxwidth = 555;

cellspacing = 6;

borderColor = "#232c35";

bgTD = "#000000";

thumbwidth = 70;

thumbheight = 70;

fntsize = 12;

acolor = "#666";

aBold = true;

icon = " ";

text = "Your Opinions ?";

showPostDate = true;

summaryPost = 400;

summaryFontsize = 10;

summaryColor = "#666";

icon2 = " ";

numposts = 45;

home_page = "http://coderzheaven.com/";

limitspy=4
intervalspy=4000

</script>

<div id="spylist">
    <script src="http://infution.byethost22.com/recentpostthumb.js" type="text/javascript"></script>
</div>

5. Done!

Note : Replace your blogger url in the “http://coderzheaven.com/” part! You can also change different parameters like number of random posts, font size, color etc.

Select an Image from gallery in ANDROID and show it in an ImageView.

Hi all
In this tutorial I will show you how to get an image from your phone gallery and show it in an imageview.
Here we use intents to open up the image gallery and get the image URI.
Here I am setting the image type as “image” to get only the images.
And on onActivityResult if the result is OK, then get the data using getData() function and converting the imageURI to the stringPath.
Then show the image in the imageview using setImageURI.

package pack.GetImage;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class GetImageActivity extends Activity {

	private static final int SELECT_PICTURE = 1;

	private String selectedImagePath;
	private ImageView img;

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

	    img = (ImageView)findViewById(R.id.ImageView01);

	    ((Button) findViewById(R.id.Button01))
	            .setOnClickListener(new OnClickListener() {
	                public void onClick(View arg0) {
	                    Intent intent = new Intent();
	                    intent.setType("image/*");
	                    intent.setAction(Intent.ACTION_GET_CONTENT);
	                    startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
	                }
	            });
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode == RESULT_OK) {
	        if (requestCode == SELECT_PICTURE) {
	            Uri selectedImageUri = data.getData();
	            selectedImagePath = getPath(selectedImageUri);
	            System.out.println("Image Path : " + selectedImagePath);
	            img.setImageURI(selectedImageUri);
	        }
	    }
	}

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

Here is the main.xml file


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

Please leave your valuable comments if you found this post useful.

How to Check if File Exists in C Sharp/C# ?

Hi,

Use the following simple lines of code to check whether a particular file exists or not using C#/C Sharp.

using System;
using System.IO;

static class MainClass
{
    static void Main(string[] args)
    {
           Console.WriteLine(File.Exists("c:yourFile.txt"));
    }
}

It will return either True or False depending on whether your file exists or not.
:)

Using of CCWaves in iPhone

CCWaves is one of the interesting functionalities in Cocos2D iphone.
Check out this following snippet to see how it works.

id my_wavesAction = [CCWaves actionWithWaves:7 amplitude:25 horizontal:NO
                                                               vertical:YES grid:ccg(15,10) duration:10];
[my_sprite runAction: [CCRepeatForever actionWithAction:my_wavesAction n]];

Please leave your valuable comments on this post………………….

JComboBox in Java swing

This shows you how to add JcomboBox to JPanel

import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;

import javax.imageio.ImageIO;
import javax.swing.*;

public class Example implements WindowListener
{
  JFrame content_frame = new JFrame();
  JPanel panel = new JPanel();
  JComboBox Combonote;
  public Example()
  {
  	    content_frame.setTitle("Contents");
		content_frame.addWindowListener(this);
		content_frame.setSize(300, 300);
		content_frame.setVisible(true);
		content_frame.setLocationRelativeTo(null);
		content_frame.setResizable(false);    ///cannot maximize
		content_frame.setVisible(true);

		showComboBox();
  }
  private void showComboBox()
  {
	  String test[]= {"[select Exercise...]","Exercise1","Exercise2","Exercise3","Exercise4","Exercise5"};
	  panel.setBackground(Color.lightGray);
	  panel.setVisible(true);
	  Combonote = new JComboBox(test);
	  Combonote.setBounds(250, 240, 250, 30);
	  panel.add(Combonote);

	  panel.setBounds(250, 240, 250, 30);
	  content_frame.getContentPane().add(panel);
	  Combonote .addItemListener(new ItemListener()
	  {
	  	  public void itemStateChanged(ItemEvent ie)
	      {
	      	  if(ie.getStateChange() == ie.SELECTED)
	      	  {
	      		    if(Combonote.getSelectedItem().equals("Exercise1"))
	  		  		{
	                                          //code...
	                }
	          }
	      }
	  });
  }

  public static void main(String[] args)
  {
    new Example();
  }

@Override
public void windowActivated(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowClosed(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowClosing(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowDeactivated(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowDeiconified(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowIconified(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowOpened(WindowEvent arg0) {
	// TODO Auto-generated method stub

}
}


How to change the hint text color in android?

Hello all..

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

Here is the java code to simply do this.

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

here is a sample project to view the difference.

This is the contents of the main java file.

package com.coderzheaven.pack;

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

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

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

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

The main.xml file

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

     <TextView
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="@string/hello" />

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

          <requestFocus />
     </EditText>

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


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

Please leave your comments if you found this useful.