Destroying Box2D Physics Bodies in Corona SDK

Hi,

For destroying physics bodies in Corona SDK, use any of the following methods.

urBody:removeSelf()

OR

urBody.parent:remove( urBody )

Note :
While Box2D objects will be safely retained until the end of the current world step, their Lua references will be deleted immediately. Therefore, be careful not to accidentally delete the same Lua object more than once. This situation could occur when deleting objects involved in collisions, which can potentially have many event phases before the collision is fully resolved. The solution is simple:

local function onCollision( self, event )
        if ( event.phase == "began" ) then

                -- Check if body still exists before removing!
                if ( urBody ) then
                        urBody:removeSelf()
                        urBody = nil
                end

        end
end

:)

How to set a tilt based gravity using Corona accelerometer ?

Hi,

For setting a tilt based gravity using Corona Accelerometer, use the following sample of code.


local function urTiltFunc( event )
        physics.setGravity( 10 * event.xGravity, -10 * event.yGravity )
end

Runtime:addEventListener( "accelerometer", urTiltFunc )

:)

How to close All activities in your View Stack in android in one click?

Hello everyone…

Today I will show you how to close all views in android in a single click of a button.
Basically if you open a number of activities, each activity is stacked one above the other like a stack if you are not calling finish() on each activity.

But there is a way to close all these activities at once by clearing the stack.
Here is a simple in which it has two activities and after navigating to the second view, the button click will open the first activity and clear the stack.

CloseAllViews.java – This is the first activity.

package pack.coderzheaven;

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

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

        b = (Button)findViewById(R.id.Button01);
        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(CloseAllViewsDemo.this, Second.class));
			}
		});
    }
}

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="This is the First activity."
    />
<Button
	android:text="Go to Second Activity without closing"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
</LinearLayout>

Second.java – Second Activity.

package pack.coderzheaven;

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

public class Second extends Activity {
	Button b;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);

        b = (Button)findViewById(R.id.Button01);
        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				 Context context = v.getContext();
		            Intent intent = new Intent(context, CloseAllViewsDemo.class);
		            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// This flag ensures all activities on top of the CloseAllViewsDemo are cleared.
		            context.startActivity(intent);
			}
		});
    }
}

main2.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="This is the second activity. The button click will clear the stack. click the Backbutton to see."
    />
<Button
	android:text="Go to First Activity without closing"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
</LinearLayout>

The AndroidManifest.xml

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

	<activity android:name=".Second"
                  android:label="@string/app_name" />
    </application>
</manifest>

After coming back to the first activity from second Activity, hit the backbutton to see if any other activities are below. If there is an activity then you will be taken to that activity, otherwise your application will close.

Simple CountDown Timer in android.

Here is a simple example on using a countdown timer in android.

package pack.coderzheaven;

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

public class TimerDemo extends Activity {
	Button start, stop;
	TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        start = (Button)findViewById(R.id.start);
        stop = (Button)findViewById(R.id.stop);
        tv  = (TextView)findViewById(R.id.tv);
        tv.setText("10"); // startting from 10.

        final MyCounter timer = new MyCounter(10000,1000);
        start.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				timer.start();
			}
		});
        stop.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				timer.cancel();
			}
		});
    }

    public class MyCounter extends CountDownTimer{

    	public MyCounter(long millisInFuture, long countDownInterval) {
    		super(millisInFuture, countDownInterval);
    	}

		@Override
		public void onFinish() {
			System.out.println("Timer Completed.");
			tv.setText("Timer Completed.");
		}

		@Override
		public void onTick(long millisUntilFinished) {
			tv.setText((millisUntilFinished/1000)+"");
			System.out.println("Timer  : " + (millisUntilFinished/1000));
		}
    }
}

Here is the Layout 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"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="CountDown Timer Demo"
    />
<Button
	android:text="Start Timer"
	android:id="@+id/start"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
<Button
	android:text="Stop Timer"
	android:id="@+id/stop"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
<TextView
	android:id="@+id/tv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=""
    />
</LinearLayout>
Timer Demo

Timer Demo

How to get touch location in Corona ?

Hi,

For getting touch location in Corona, use the following code,


--Your touch event listener
 local function myTouchListener( event )
        if event.phase == "began" then
        --Touch coordinates can be accessed by event.x/event.y properties of touch event
            print( "Touched!" )
            print ("Touch X = #"..event.x)
            print ("Touch Y = #"..event.y)
        end
    end

--Adding an event listener for touch
Runtime:addEventListener( "touch", myTouchListener )

How to remove a Runtime event listener in Corona?

Hi,

Runtime events will not be removed automatically — EVER!

So for removing runtime events in Corona use the following line of code,

--Suppose you have an event 'urEventNew'
Runtime:removeEventListener("enterFrame", urEventNew)

:)

How to get touch 'began', 'moved' & 'ended' in Corona ?

Hi,

For getting touch ‘began’, ‘moved’ & ‘ended’ in Corona, use the following code.

--Your touch event listener
 local function myTouchListener( event )
        if event.phase == "began" then
            print( "Touched!" )
        elseif event.phase == "moved" then
            print( "Touches Moved!" )
        elseif event.phase == "ended" then
            print( "Touches Ended!" )
        end
    end

--Adding an event listener for touch
Runtime:addEventListener( "touch", myTouchListener )

:)

How to add label/text to image in Corona ?

Hi,

For adding a label/text to an image in Corona, using Lua, use the following code,


local urGroup = display.newGroup()

local urImage = display.newImageRect('sample.png',70,70)
urImage.x = 150
urImage.y = 250

local urText = display.newText( "SampleText", 0, 0, "Helvetica", 22 )
urText:setTextColor( 0, 0, 0, 255 )

-- insert items into group, in the order you want them displayed:
urGroup:insert( urImage )
urGroup:insert( urText )

:)

How to find a file size in KB in android?

This sample helps you to find the size of a file in KiloBytes.
Here I am pushing a video file on to the device using this method and trying to find it’s size.
Make sure you give the exact file name because file name is case sensitive and push the file only in the sdcard directory in the FileExplorer.
Here is the code.

package pack.coderzheaven;

import java.io.File;

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

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

        try{
             File file = new File("/sdcard/my_video.mp4");
             long length = file.length();
             length = length/1024;
             System.out.println("File Path : " + file.getPath() + ", File size : " + length +" KB");
        }catch(Exception e){
        	System.out.println("File not found : " + e.getMessage() + e);
        }
    }
}

Check the LogCat for the output.

How to use RadioButtonGroup in Android?

Hello everyone ,

In today’s tutorial I will show you how to how to use RadioButton group in Android.
Lets go directly to the code.

Let’s see the layout for the RadioGroup first.
The file is named main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
     <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Which company do you like the most?"
        android:id="@+id/tv"
        android:textSize="25dp"
        android:textStyle="bold"/>
    <RadioGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:checkedButton="@+id/lunch"
        android:id="@+id/menu">
        <RadioButton
            android:text="Google"
            android:id="@+id/google"
            android:checked="true"
            />
        <RadioButton
            android:text="Microsoft"
            android:id="@+id/ms" />
        <RadioButton
            android:text="Apple"
            android:id="@+id/apple" />
        <RadioButton
            android:text="Nokia"
            android:id="@+id/nokia" />
        <RadioButton
            android:text="Samsung"
            android:id="@+id/samsung" />
    </RadioGroup>

     <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:id="@+id/choice"
        android:textSize="25dp"
        android:padding="10dp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Clear CheckBoxes"
        android:id="@+id/clear" />
</LinearLayout>

This will create a layout file with a radioGroup with 5 radioButtons and a button to clear all checkboxes and a TextView to show the selected value.

Now let’s look at the java code.

package pack.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;

public class RadioGroupDemo extends Activity implements RadioGroup.OnCheckedChangeListener,
	View.OnClickListener{

	private TextView mChoice;
	private RadioGroup mRadioGroup;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mRadioGroup = (RadioGroup) findViewById(R.id.menu);
        // test listening to checked change events
        mRadioGroup.setOnCheckedChangeListener(this);
        mChoice = (TextView) findViewById(R.id.choice);
        // test clearing the selection
        Button clearButton = (Button) findViewById(R.id.clear);
        clearButton.setOnClickListener(this);
    }

    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if(checkedId == R.id.google){
        	 mChoice.setText("Selected Google");
        }
        if(checkedId == R.id.ms){
       	 	mChoice.setText("Selected Microsoft");
        }
        if(checkedId == R.id.apple){
       	 	mChoice.setText("Selected Apple");
        }
        if(checkedId == R.id.nokia){
       	 	mChoice.setText("Selected Nokia");
        }
        if(checkedId == R.id.samsung){
       	 	mChoice.setText("Selected Samsung");
        }
    }

    public void onClick(View v) {
        mRadioGroup.clearCheck();
    }
}

The onCheckedChanged function is called whenever you check a radioButton or uncheck it.
Then inside this function we compare the id of the clicked one to match with ours in the xml file to do a specific task.

RadioButtonGroup Demo

Please leave your valuable comments on this post.

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

Hello everyone,

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

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

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

Refer the image

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

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

package pack.coderzheaven;

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class FileUploadTest extends Activity {

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

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

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

    }

    public void openGallery(int req_code){

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

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

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

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

    private void doFileUpload(){

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

Now the layout for this file main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Multiple File Upload from CoderzHeaven"
    />
<Button
    android:id="@+id/Button01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get First File">
</Button>
<Button
    android:id="@+id/Button02"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get Second File">
</Button>
<Button
    android:id="@+id/upload"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start Upload">
</Button>
<TextView
	android:id="@+id/tv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Selected File path : "
    />

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

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

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">

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

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".FileUploadTest"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

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

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

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

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


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

How to get the current progress on your SeekBar in android?

I have already shown how to use seekBar in android.
This simple snippet helps you to get the current progress in the seekbar.
It’s same code from this
post, only thing is I added the getProgress method.

package com.coderzheaven;

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

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

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

        setContentView(R.layout.main);

        mSeekBar = (SeekBar)findViewById(R.id.seek);
        int p = mSeekBar.getProgress();
        System.out.println("Current Progress = " + p);
        mSeekBar.setOnSeekBarChangeListener(this);
        mProgressText = (TextView)findViewById(R.id.progress);
        mTrackingText = (TextView)findViewById(R.id.tracking);
    }

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

        System.out.println("onProgressChanged >> Current Progress = " + progress);
    }

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

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

Check the Logcat for the current progress or the TextView in which I am showing.
Take the xml from the This post

Please leave your valuable comments.

AutoComplete textView in android.

Here is a simple example to create an autocomplete textView in android.
After creating an array of values for the dropdown we will set it as adapter for the textView.
Check out the code.

package pack.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class AutoCompleteDemo extends Activity {
	 static final String[] COUNTRIES = new String[] {
			"India","America","Canada", "Indonesia","England","Britian"};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, COUNTRIES);
        AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit);
        textView.setAdapter(adapter);
    }
}

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Please type in a country name." />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Country : " />

        <AutoCompleteTextView android:id="@+id/edit"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>
</LinearLayout>
AutoCompleteDemo

AutoCompleteDemo

Get Unique deviceID in android? – Different Methods

Hello everyone..

I have shown one way to get the deviceID in android in this post.
Here are some other ways by which you can get the unique device ID of an android device.
First Method…

String deviceId = Settings.System.getString(getContentResolver(),Settings.System.ANDROID_ID);

Second Method

String deviceId = Secure.getString(this.getContext().getContentResolver(), Secure.ANDROID_ID);

Third Method

 final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

    final String tmDevice, tmSerial, tmPhone, androidId;
    tmDevice = "" + tm.getDeviceId();
    tmSerial = "" + tm.getSimSerialNumber();
    androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);

    UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
    String deviceId = deviceUuid.toString();

Make sure to add this permission in your AndroidManifest file

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

These codes may depend on your SDK version and the type of the device manufacturer. So try one by one.

How to align a text in Android Programatically?

This is a simple demo on aligning a text in Android. You can check out for more details at the developers site.
This code explains how to write a String or text on a canvas and how to give it a custom font or inbuilt font programatically, change the color of the text or canvas or change the size of the text etc.
Check out this example. You don’t need a layout for this since the view is created in the java code itself.
Now go on and copy the code into your project and you are done.

package pack.coderzheaven;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;

public class TextAlignDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new SampleView(this));
    }

    private static class SampleView extends View {
        private Paint   mPaint;
        private float   mX;
        private float[] mPos;

        private Path    mPath;
        private Paint   mPathPaint;

        private static final int DY = 30;
        private static final String TEXT_L = "Left";
        private static final String TEXT_C = "Center";
        private static final String TEXT_R = "Right";
        private static final String POSTEXT = "Positioned";
        private static final String TEXTONPATH = "Along a path";

        private static void makePath(Path p) {
            p.moveTo(10, 0);
            p.cubicTo(100, -50, 200, 50, 300, 0);
        }

        private float[] buildTextPositions(String text, float y, Paint paint) {
            float[] widths = new float1;
            // initially get the widths for each char
            int n = paint.getTextWidths(text, widths);
            // now popuplate the array, interleaving spaces for the Y values
            float[] pos = new float[n * 2];
            float accumulatedX = 0;
            for (int i = 0; i < n; i++) {
                pos[i*2 + 0] = accumulatedX;
                pos[i*2 + 1] = y;
                accumulatedX += widths[i];
            }
            return pos;
        }

        public SampleView(Context context) {
            super(context);
            setFocusable(true);

            mPaint = new Paint();
            mPaint.setAntiAlias(true);
            mPaint.setTextSize(30);
            mPaint.setTypeface(Typeface.SERIF);

            mPos = buildTextPositions(POSTEXT, 0, mPaint);

            mPath = new Path();
            makePath(mPath);

            mPathPaint = new Paint();
            mPathPaint.setAntiAlias(true);
            mPathPaint.setColor(0x800000FF);
            mPathPaint.setStyle(Paint.Style.STROKE);
        }

        @Override protected void onDraw(Canvas canvas) {
            canvas.drawColor(Color.WHITE);

            Paint p = mPaint;
            float x = mX;
            float y = 0;
            float[] pos = mPos;

            // draw the normal strings

            p.setColor(0x80FF0000);
            canvas.drawLine(x, y, x, y+DY*3, p);
            p.setColor(Color.BLACK);

            canvas.translate(0, DY);
            p.setTextAlign(Paint.Align.LEFT);
            canvas.drawText(TEXT_L, x, y, p);

            canvas.translate(0, DY);
            p.setTextAlign(Paint.Align.CENTER);
            canvas.drawText(TEXT_C, x, y, p);

            canvas.translate(0, DY);
            p.setTextAlign(Paint.Align.RIGHT);
            canvas.drawText(TEXT_R, x, y, p);

            canvas.translate(100, DY*2);

            // now draw the positioned strings

            p.setColor(0xBB00FF00);
            for (int i = 0; i < pos.length/2; i++) {
                canvas.drawLine(pos[i*2+0], pos[i*2+1]-DY,
                                pos[i*2+0], pos[i*2+1]+DY*2, p);
            }
            p.setColor(Color.BLACK);

            p.setTextAlign(Paint.Align.LEFT);
            canvas.drawPosText(POSTEXT, pos, p);

            canvas.translate(0, DY);
            p.setTextAlign(Paint.Align.CENTER);
            canvas.drawPosText(POSTEXT, pos, p);

            canvas.translate(0, DY);
            p.setTextAlign(Paint.Align.RIGHT);
            canvas.drawPosText(POSTEXT, pos, p);

            // now draw the text on path

            canvas.translate(-100, DY*2);

            canvas.drawPath(mPath, mPathPaint);
            p.setTextAlign(Paint.Align.LEFT);
            canvas.drawTextOnPath(TEXTONPATH, mPath, 0, 0, p);

            canvas.translate(0, DY*1.5f);
            canvas.drawPath(mPath, mPathPaint);
            p.setTextAlign(Paint.Align.CENTER);
            canvas.drawTextOnPath(TEXTONPATH, mPath, 0, 0, p);

            canvas.translate(0, DY*1.5f);
            canvas.drawPath(mPath, mPathPaint);
            p.setTextAlign(Paint.Align.RIGHT);
            canvas.drawTextOnPath(TEXTONPATH, mPath, 0, 0, p);
        }

        @Override
        protected void onSizeChanged(int w, int h, int ow, int oh) {
            super.onSizeChanged(w, h, ow, oh);
            mX = w * 0.5f;  // remember the center of the screen
        }
    }
}
TextAlign Demo

TextAlign Demo

Please leave your valuable comments on this post.

How to record an audio in android and email it as attachment?

This example shows how to record an audio in android and save it in your path and send it as an email attachment.
This example is taken from the developers website.
Note : You should run this on the device otherwise it will not work.

This example will open up an email client after recording and attach it to the email client.
Remember that your device should have the email client application and you should be logged in otherwise you will get the error as “No Application can perform this action

package pack.coderzheaven;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;


public class AudioCaptureDemo extends Activity
{
    private static final String LOG_TAG = "AudioCaptureDemo";
    private static String mFileName = null;

    private RecordButton mRecordButton = null;
    private MediaRecorder mRecorder = null;

    private PlayButton   mPlayButton = null;
    private MediaPlayer   mPlayer = null;

    private void onRecord(boolean start) {
        if (start) {
            startRecording();
        } else {
            stopRecording();
        }
    }

    private void onPlay(boolean start) {
        if (start) {
            startPlaying();
        } else {
            stopPlaying();
        }
    }

    private void startPlaying() {
        mPlayer = new MediaPlayer();
        try {
            mPlayer.setDataSource(mFileName);
            mPlayer.prepare();
            mPlayer.start();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
    }

    private void stopPlaying() {
        mPlayer.release();
        mPlayer = null;
    }

    private void startRecording() {
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(mFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }

        mRecorder.start();
    }

    private void stopRecording() {
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;
        ArrayList<String> uris = new ArrayList<String>();
        mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
        mFileName += "/audiorecordtest.3gp";
        uris.add(mFileName);
        email(AudioCaptureDemo.this,"[email protected]","[email protected]","No Subject","Sample Email text",uris);

    }

    public static void email(Context context, String emailTo, String emailCC,
    	    String subject, String emailText, List<String> filePaths)
    	{
    	    //need to "send multiple" to get more than one attachment
    	    final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
    	    emailIntent.setType("plain/text");
    	    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
    	        new String[]{emailTo});
    	    emailIntent.putExtra(android.content.Intent.EXTRA_CC,
    	        new String[]{emailCC});
    	    //has to be an ArrayList
    	    ArrayList<Uri> uris = new ArrayList<Uri>();
    	    //convert from paths to Android friendly Parcelable Uri's
    	    for (String file : filePaths)
    	    {
    	        File fileIn = new File(file);
    	        Uri u = Uri.fromFile(fileIn);
    	        uris.add(u);
    	    }
    	    emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
    	    context.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
    }

    class RecordButton extends Button {
        boolean mStartRecording = true;

        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
                onRecord(mStartRecording);
                if (mStartRecording) {
                    setText("Stop recording");
                } else {
                    setText("Start recording");
                }
                mStartRecording = !mStartRecording;
            }
        };

        public RecordButton(Context ctx) {
            super(ctx);
            setText("Start recording");
            setOnClickListener(clicker);
        }
    }

    class PlayButton extends Button {
        boolean mStartPlaying = true;

        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
                onPlay(mStartPlaying);
                if (mStartPlaying) {
                    setText("Stop playing");
                } else {
                    setText("Start playing");
                }
                mStartPlaying = !mStartPlaying;
            }
        };

        public PlayButton(Context ctx) {
            super(ctx);
            setText("Start playing");
            setOnClickListener(clicker);
        }
    }

    public AudioCaptureDemo() {
        mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
        mFileName += "/audiorecordtest.3gp";
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        LinearLayout ll = new LinearLayout(this);
        mRecordButton = new RecordButton(this);
        ll.addView(mRecordButton,
            new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                0));
        mPlayButton = new PlayButton(this);
        ll.addView(mPlayButton,
            new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                0));
        setContentView(ll);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }

        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }
}

Please leave your valuable comments on this post.If you like it share it with your friends by clicking on the +1 button above the post.
Enjoy……….

Passing a Value to a Function in JavaScript – An Example

Hi,

Given below, is an example for passing a value to a function in JavaScript.

<html>
<head>
<title>Passing A Value To A Function</title>
<script language="JavaScript">
<!--
function yourFunc(urVal)
{
    alert(urVal);
}
//  -->
</script>
</head>
<body>
<P>Click <input type="button" value="this" onClick="yourFunc('CoderzHeaven')"> button for passing value!</p>
<br>
</body>
</html>

Converting String to Upper Case in JavaScript

Hi,

For converting a string to upper case in javascript, use the following code.


<html>
<head>
<title>Convert String</title>
<script type="text/javascript" language="javascript">
<!-- //
onload = function(){
    var str = new String("coderzheaven");
    var toUpperCase = str.toUpperCase();
    document.write(toUpperCase);
}
// -->
</script>
</head>
<body>

</body>
</html>

It will give you ‘CODERZHEAVEN’
:)