Monthly Archives: July 2012

How to read a serialized object from a file in the raw folder in android?

In my previous post I showed how to serialize an object and save it in sdcard in a file and retrieve it.

Pull out the file from the sdcard and then create a folder named “raw” inside the “res” folder and copy it.

Serialization pull out file.
This example shows how to retreive it when it is in the res/raw folder.

Here is the code that does this.

 public void readFromResources(){
    	 try
         {
         	InputStream is = getResources().openRawResource(R.raw.save_object);
         	ObjectInputStream ois = new ObjectInputStream(is);
         	Person person = (Person)ois.readObject();
         	Log.v("Person : >> Name : ",person.getName() + ", Address : " + person.getAddress() + ", Number : " + person.getNumber());
         }
         catch(Exception ex)
         {
        	 Log.v("Serialization Error >> ",ex.getMessage());
         	 ex.printStackTrace();
         }
    }

You are done. Go on and run it.
Check the Logcat for the results.

Serialization in Android – A Simple example.

Serializing a class file provides a fast and efficeint way to store information produced by your application!

What is serialization?

Serialization is essentually taking a screenshot of a class file and its contents. For example, lets say you have the following class:


package com.coderzheaven.pack;

import java.io.Serializable;

public class Person implements Serializable //Added implements Serializable
{
	String name="";
	private String number="";
	private String address=""; 
	private static final long serialVersionUID = 46543445; 

	public void setName(String name)
    {
    	this.name = name;
    }
    
    public void setNumber(String number)
    {
    	this.number = number;
    }

    public void setAddress(String address)
    {
    	this.address = address;
    }
    
    public String getName()
    {
    	return name;
    }
    	
    public String getNumber()
    {
    	return number;
    }
    	
    public String getAddress()
    {
    	return address;
    }
}

Now we will save this data to a file in the SDCARD.
Make sure to add the write permission in the AndroidManifest.xml file.

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

Now the Activity class which does the saving and retrieving of the object.

package com.coderzheaven.pack;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

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

public class SerializationDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Person person = new Person();
        person.setName("CoderzHeaven");
        person.setAddress("CoderzHeaven India");
        person.setNumber("1234567890"); 
        
        //save the object
        saveObject(person);
        
        // Get the Object
        Person person1 = (Person)loadSerializedObject(new File("/sdcard/save_object.bin")); //get the serialized object from the sdcard and caste it into the Person class.
        System.out.println("Name : " + person1.getName());
    }
    
    public void saveObject(Person p){
    	 try
         {
         	ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("/sdcard/save_object.bin"))); //Select where you wish to save the file...
         	oos.writeObject(p); // write the class as an 'object'
         	oos.flush(); // flush the stream to insure all of the information was written to 'save_object.bin'
         	oos.close();// close the stream
         }
         catch(Exception ex)
         {
         	Log.v("Serialization Save Error : ",ex.getMessage());
         	ex.printStackTrace();
         }
    }
    
    public Object loadSerializedObject(File f)
    {
        try
        {
        	ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
        	Object o = ois.readObject();
        	return o;
        }
        catch(Exception ex)
        {
    	Log.v("Serialization Read Error : ",ex.getMessage());
        	ex.printStackTrace();
        }
        return null;
    }
}

Serialization pull out file.

These are the Rules of Serialization

    Always use variables that can actually be serialized
    Never change the class files source after you serialize a class file from it
    Do not use super large int[] arrays (bug described below)

Now check the Logcat for the output.
Please leave your comments on this example.

Download the sample project of this demo from here.

In the next post we will see how to read a serialized object from the raw folder.

How to remove title from AlertDialog in android?

Hello all..

Today I will show you two simple ways to remove title in an android alertdialog.

Actually you can do this in two methods.

Method 1

That takes a custom layot file, inflates it, gives it some basic text and icon, then creates it.

AlertDialog.Builder builder;
AlertDialog alertDialog;

Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater)
        mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog,
        (ViewGroup) findViewById(R.id.layout_root));

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);

builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();
alertDialog.show()

Method 2

Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

But it doesn’t work when creating an AlertDialog (or using the Builder), because it already disables the title and use a custom one internally.

Also, one can do that with a style, eg in styles.xml:

<style name="FullHeightDialog" parent="android:style/Theme.Dialog">
   <item name="android:windowNoTitle">true</item>
</style>

And then:

Dialog dialog = new Dialog(context, R.style.FullHeightDialog);

How to set line spacing in a textview in android?

This is really simple in android. TextViews has a property called “lineSpacingExtra” which you can change to set the line spacing.

   <TextView 
           android:text="Data" 
		  	android:id="@+id/textview" 
		  	android:layout_gravity="top"
		  	android:gravity="left"
		  	android:layout_width="fill_parent" 
		  	android:layout_height="wrap_content"
		  	android:layout_centerVertical="true"
		  	android:layout_margin="5dp"
		  	android:padding="5dp"
		  	android:textSize="20sp"
		  	android:lineSpacingExtra="10dp">
		  </TextView>

OR

you can call

textView.setLineSpacing()

in the java code itself.

A Simple FlashLight Application.

Here is a simple Application on how to use flashlight in android.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class FlashLightActivity extends Activity {

	//flag to detect flash is on or off
	private boolean isLighOn = false;

	private Camera camera;

	private Button button;

	@Override
	protected void onStop() {
		super.onStop();

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

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

		button = (Button) findViewById(R.id.buttonFlashlight);

		Context context = this;
		PackageManager pm = context.getPackageManager();

		// if device support camera?
		if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
			Log.e("err", "Device has no camera!");
			return;
		}
		try{
			camera = Camera.open();
			final Parameters p = camera.getParameters();
	
			button.setOnClickListener(new OnClickListener() {
	
				@Override
				public void onClick(View arg0) {
	
					if (isLighOn) {
	
						Log.i("info", "torch is turn off!");
	
						p.setFlashMode(Parameters.FLASH_MODE_OFF);
						camera.setParameters(p);
						camera.stopPreview();
						isLighOn = false;
	
					} else {
	
						Log.i("info", "torch is turn on!");
	
						p.setFlashMode(Parameters.FLASH_MODE_TORCH);
	
						camera.setParameters(p);
						camera.startPreview();
						isLighOn = true;
	
					}
	
				}
			});
		}catch(Exception e){
			Toast.makeText(this, "Your device doesnot have FlashLight capability", Toast.LENGTH_LONG).show();
		}

	}
}

Now the layout file main.xml.

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

    <Button
        android:id="@+id/buttonFlashlight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       	android:layout_centerVertical="true"
       	android:layout_centerHorizontal="true"
        android:text="Torch" />

</RelativeLayout>

AndroiManifest.xml file contents.

Make sure to add the permissions.

<?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-sdk android:minSdkVersion="5" />

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />

    <application
        android:debuggable="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".FlashLightActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Download the android java source code from here.

please leave your valuable comments on this post.

How to make a http call repeatedly from a service in android?

We may have applications in which we may have to make repeated calls to a webservice. At that time services may be useful.

This is such an example in which we will be creating a Service in android to create a repeated call to a webservice in a time delay of some seconds or milliseconds.

OK We will start.

First We will create a new android project named “AcessWebFromService” and in the main java file copy this code.

package com.coderzheaven.pack;

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

public class AcessWebFromServiceDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        startService(new Intent(AcessWebFromServiceDemo.this, MyService.class));
    }
}

You may be getting some errors after this. Now we will clear all the errors.

Now create another class and name it “MyService.java“. This is our Service file that extends Android Service.

Paste this code into this file .

package com.coderzheaven.pack;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service{
	
	private static String TAG = MyService.class.getSimpleName();
	private MyThread mythread;
	public boolean isRunning = false;
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "onCreate");		
		mythread  = new MyThread();
	}

	@Override
	public synchronized void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy");
		if(!isRunning){
			mythread.interrupt();
			mythread.stop();
		}		
	}

	@Override
	public synchronized void onStart(Intent intent, int startId) {
		super.onStart(intent, startId); 
		Log.d(TAG, "onStart");
		if(!isRunning){
			mythread.start();
			isRunning = true;
		}
	}
	
	public void readWebPage(){
          HttpClient client = new DefaultHttpClient();
          HttpGet request = new HttpGet("http://google.com");
          // Get the response
          ResponseHandler<String> responseHandler = new BasicResponseHandler();
          String response_str = null;
		  try {
			 response_str = client.execute(request, responseHandler);
			 if(!response_str.equalsIgnoreCase("")){
				 Log.d(TAG, "Got Response");
			 }
		  } catch (Exception e) {
			 e.printStackTrace();
		  }
	}
	
	class MyThread extends Thread{
		static final long DELAY = 3000;
		@Override
		public void run(){			
			while(isRunning){
				Log.d(TAG,"Running");
				try {					
					readWebPage();
					Thread.sleep(DELAY);
				} catch (InterruptedException e) {
					isRunning = false;
					e.printStackTrace();
				}
			}
		}
		
	}

}

We have called this service to start running in the main java file using this code.

startService(new Intent(AcessWebFromServiceDemo.this, MyService.class));

Now the important thing is for this service to run we have to declare it in the AndroidManifest file.

This is how the AndroidManifest file looks.

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

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

OK Now you are done. When you run this application you can see the Log coming every three seconds in the LogCat. PLease make sure that you have internet connection in the Emulator or Device.

This is how the Log looks in the Logcat.

Service

Please leave your valuable comments on this post and also share it by hitting a plus(+1) button.