Wednesday, 3 April 2013

Autoboxing and Unboxing

The Autoboxing and Unboxing  was released with the Java 5.

Autoboxing

During assignment, the automatic transformation of primitive  type(int, float, double etc.) into their object equivalents or wrapper type(Integer, Float, Double,etc) is known as Autoboxing.

Ex:

Integer intObject = 5; // autoboxing
auto-unboxing

During assignment or calling of constructor, the automatic transformation of wrapper types into their primitive equivalent  is known as Unboxing.
Ex:
int inative = 0;
inative = new Integer(5); // auto-unboxing

Autoboxing also works with comparison
int a = 10;
Integer b = 10;
System.out.println(a==b); // true

How to create read only List, Map and Set in Java

// creating List in Java
List<String>  names= new ArrayList<String>();

// initializing List in Java
names.add("Raja");
names.add("Ramesh");
names.add("Ramu");

Set<String> readOnlySet = new HashSet<String>(names);

 //Set is not yet read-only you can still add elements into Set
readOnlySet.add("Ravi");
//making Set readonly in Java - no add remove or set operation permitted
readOnlySet = Collections.unmodifiableSet(readOnlySet);

//trying to add element in read only Set - java.lang.UnSupportedOperationException
readOnlySet.add("You can not add element in read Only Set");

//trying to remove element from read only set
readOnlySet.remove("Ramu");

//you can not remove elements from read only Set

Map<StringString> agesmap = new HashMap<StringString>();
agesmap.put("raja", "24");

//Map is not read only yet, you can still add entries into
agesmap.put("ramesh", "22");

System.out.println("Map in Java before making read only: " + contries);

//Making Map read only in Java
Map readOnlyMap = Collections.unmodifiableMap(agesmap);

//you can not put a new entry in read only Map in Java
readOnlyMap.put("ra", "33"); //java.lang.UnSupportedOperation 

//you can not remove keys from read only Map in Java
readOnlyMap.remove("raja"); //java.lang.UnSupportedOperation

Why is Java not a pure OOP Language?

Java is a OOP language and it is not a pure Object Based Programming Language.

Many languages are Object Oriented. There are seven qualities to be satisfied for a programming language to be pure Object Oriented. They are:

  1. Encapsulation/Data Hiding

  2. Inheritance

  3. Polymorphism

  4. Abstraction

  5. All predefined types are objects

  6. All operations are performed by sending messages to objects

  7. All user defined types are objects.


Java is not because it supports Primitive datatype such as int, byte, long... etc, to be used, which are not objects.

Contrast with a pure OOP language like Smalltalk, where there are no primitive types, and boolean, int and methods are all objects.

Tuesday, 19 March 2013

Background Thread Running in Android

package com.raja.vedioapp;

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

public class MainActivity extends Activity

{

@Override
protected void onCreate(Bundle savedInstanceState)

{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
         Progress();
}

protected void Progress()

{
final ProgressDialog progress=ProgressDialog.show(MainActivity.this, "Progress Task", "Please Wait....",true);

new Thread(){
public void run()
{
try
{
Message ms=new Message();
ms.what=1111;
handler.sendMessage(ms);
}catch (Exception e)
{
System.out.println("error "+e);
}
progress.cancel();
}
}.start();

}
Handler handler=new Handler()
{

@Override
public void handleMessage(Message msg)
{
switch(msg.what)
{
case 1111:
for(int i=0;i<1000;i++)
{
System.out.println("Back Ground Thread Test"+i);
}
break;
}
}
};

Progress Dialog showing when Back Ground Task Running in Android

package com.raja.vedioapp;

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

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState)

{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new BackGround().execute("hi");
}
class BackGround extends AsyncTask<String, Void, String>
{
ProgressDialog progress;
@Override
protected String doInBackground(String... params)
{
for(int i=0;i<=10000;i++)
{
System.out.println("Background Task "+i);
}
return "success";
}

@Override
protected void onPostExecute(String result)
{
System.out.println("BackGround Task Completed Result is "+result);
progress.cancel();
}

@Override
protected void onPreExecute()
{
progress=ProgressDialog.show(MainActivity.this, "Progress", "Please Wait...",true);
}


}
}

Video recording in Android

public class Video extends Activity implements SurfaceHolder.Callback
{
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mrec = new MediaRecorder();
File video;
private Camera mCamera;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_surface);
Log.i(null , "Video starting");
mCamera = Camera.open();
surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add(0, 0, 0, "StartRecording");
menu.add(0, 1, 0, "StopRecording");
return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case 0:
try {
startRecording();
} catch (Exception e) {
String message = e.getMessage();
Log.i(null, "Problem Start"+message);
mrec.release();
}
break;

case 1: //GoToAllNotes
mrec.stop();
mrec.release();
mrec = null;
break;

default:
break;
}
return super.onOptionsItemSelected(item);
}

protected void startRecording() throws IOException
{
mrec = new MediaRecorder(); // Works well
mCamera.unlock();

mrec.setCamera(mCamera);

mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);

mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setOutputFile("/sdcard/zzzz.3gp");

mrec.prepare();
mrec.start();
}

protected void stopRecording() {
mrec.stop();
mrec.release();
mCamera.release();
}

private void releaseMediaRecorder(){
if (mrec != null) {
mrec.reset(); // clear recorder configuration
mrec.release(); // release the recorder object
mrec = null;
mCamera.lock(); // lock camera for later use
}
}

private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
if (mCamera != null){
Parameters params = mCamera.getParameters();
mCamera.setParameters(params);
}
else {
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
}
}
camera_surface.xml

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

<SurfaceView
android:id="@+id/surface_camera"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />

</RelativeLayout>

And of cource include these permission in manifest.

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

Audio Recording and playing in android

public void Audio()
{
final Intent audioIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
File audioFile = new File(Environment.getExternalStorageDirectory(), "videoTest.mp4");
Uri audioFileUri = Uri.fromFile(audioFile);
audioIntent.putExtra(MediaStore.EXTRA_OUTPUT, audioFileUri);
startActivityForResult(audioIntent, TAKE_AUDIO);
}

Monday, 11 March 2013

Regular Expressions for Validations

Regular Expressions for Validations

^[0-9]$      it allows only numbers without any limit

^[0-9]{0,10}$   it allows only numbers up-to  minimum 0 to  maximum 10 digits

^[0-9]{1,10}$   it allows only numbers up-to  minimum 1 to  maximum 10 digits

^[0-9.]{0,10}$   it allows only numbers and decimal numbers also up-to  minimum 1 to  maximum 10 digits

^[+]?\\d+(\\.{0,1}(\\d{0,3})\\%{0,1})?$   it allows +ve numbers only and also

 

^     allows(caret)

[]    specific numbers are symbols you want allow  like [0-9] it allows 0 to 9 all numbers

{}  specific limit for # chars appears in string {Min,Max}={0,1} means  in given String # may appears once or not appears

\\ this like OR condition

Count Char Occurrences in Java

public static int count_Chars(String given, char key)
{
int count = 0;
for (int i=0; i < given.length(); i++)
{
if (given.charAt(i) == key)
{
count++;
}
}
return count;
}

Start/Stop GPS Programmatically in Android

private void setGPSOn()
{
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

if(!provider.contains("gps"))
{
//if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}

private void setGPSOff(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

if(provider.contains("gps"))
{
//if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}