Tuesday, November 29, 2011

Pass a custom class from one activity to another using Intent

In this article, I am going to discuss about sending a custom class from one activity to another or any custom class to send from one activity to another using Intent.

We can pass a custom class using two ways, rather using two interfaces that are provided by Android which are java.io.Serializable and android.os.Parcelable.

First create a custom class then implements the class with Serializable interface. To make the class serializable include two functions, which are writeObject() and readObject(). Whatever objects we need to pass has to write to the ObjectOutputStream in writeObject() and we have to read from readObject() using ObjectInputStream.
public class MyClass implements Serializable {
     
     String firstName;
     int empID;
     
     public MyClass(String name, int id) {
      firstName = name;
      empID = id;
     }
     
     private void writeObject(ObjectOutputStream out) {
      try {
    out.writeUTF(firstName);
   } catch (IOException e) {
    e.printStackTrace();
   }
     }
     
     private void readObject(ObjectInputStream in) {
      try {
    firstName = in.readUTF();
   } catch (IOException e) {
    e.printStackTrace();
   }
     }
     
     public String getName() {
      return firstName;
     }
     
     public int getEmpId() {
      return empID;
     }
    }
Next step is create an object of the custom class and put it into the intent using putExtra(). In the next activity we can get the custom class object using getIntent().getSerializableExtra()

You can get the full source code from here

Monday, November 28, 2011

Solution for the error "Method called after release()" in Android Camera API

Today when I am working on camera API in android, I got an error telling "ERROR/AndroidRuntime java.lang.RuntimeException: Method called after release()".



Solution

The solution for this is, I am trying to access the camera somewhere after I have released it. So in onResume() set the previewCallback to null. In my case this solved my problem. setPreviewCallback(null);


Happy Coding !!!

Sunday, November 27, 2011

Solution for the error "Debug certificate expired"

Today when I am working suddenly all my projects in eclipse got errors and nothing is compiling. I came to know the the error is "Debug certificate is expired".


Solution



The solution for this is, if you are in windows, then in user profile, you have a folder called ".android", that contains the debug certificate. Delete the debug certificate, then clean and build a project in eclipse. All started working fine.



Example
C:\Users\Nithin\.android

Happy Coding !!!

Access the features of Android device


To access the available features in an Android device, the code snippet,


PackageManager mPackageManager = getPackageManager();
FeatureInfo[] systemFeature = mPackageManager
.getSystemAvailableFeatures();
for (int i = 0; i < systemFeature.length; i++) {
String feature = systemFeature[i].name;
if (feature == null) {
feature = "OpenGL Version : " + systemFeature[i].reqGlEsVersion;
}
systemFeaturesList.add(feature);
}


I just list it into a list, the complete code is,


public class FeaturesListActivity extends Activity {

private final String TAG = "FeaturesListActivity";
private ListView mList;
private ArrayList systemFeaturesList = new ArrayList();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mList = (ListView) findViewById(R.id.list);
PackageManager mPackageManager = getPackageManager();
FeatureInfo[] systemFeature = mPackageManager
.getSystemAvailableFeatures();
for (int i = 0; i < systemFeature.length; i++) {
String feature = systemFeature[i].name;
if (feature == null) {
feature = "OpenGL Version : " + systemFeature[i].reqGlEsVersion;
}
systemFeaturesList.add(feature);
Log.i(TAG, "**************** System Feature = " + feature);
}
mList.setAdapter(new SystemFeatureListAdapter(this));
}

private class SystemFeatureListAdapter extends BaseAdapter {

private Context mContext;

public SystemFeatureListAdapter(Context context) {
mContext = context;
}

@Override
public int getCount() {
return systemFeaturesList.size();
}

@Override
public Object getItem(int index) {
return systemFeaturesList.get(index);
}

@Override
public long getItemId(int id) {
return id;
}

@Override
public View getView(int position, View view, ViewGroup parent) {
TextView text = new TextView(mContext);
text.setText(systemFeaturesList.get(position));
return text;
}
}
}


The screen-shot of the application is,

Saturday, November 26, 2011

Fetch the unique ID of Android device

To fetch the device ID of any android device, the code snippet is,


TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String android_id = telephonyManager.getDeviceId();


The screen-shot that I got from my HTC phone is,

Wednesday, November 16, 2011

Open Gallery and get the selected image in appplication

In this, the screen will have a button to open the android device Gallery and from there if we select any image, that image we can get it in the application.

The code snipped for opening the Gallery is,


Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);


We are opening the gallery as a sub activity of our application, because onActivityResult() will get called after selecting the image from gallery. So in onACtivityResult(), we will get the Uri of the selected image and from Mediastore contentprovider, we can get the selected image as bitmap. After that, for showing it in the application, just setting the image in a ImageView.

The complete code is,


public class GalWalActivity extends Activity {

private ImageView selectedImage;
private Bitmap currentImage;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
selectedImage = (ImageView) findViewById(R.id.selectedImage);
Button openGallery = (Button) findViewById(R.id.opengallery);

openGallery.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
Uri photoUri = data.getData();
if (photoUri != null) {
try {
currentImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
selectedImage.setImageBitmap(currentImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}



The catch here is if we open the gallery for first time from the applicaiotn, the applicaiton will work fine. But if we open gallery for second time and try to get the selected image, we will get an exception OutOfMemory Exception

This is because we are not free the bitmap memory or we need to recycle the bitmap. The solution for this is, every time when we open gallery from our application, onPause() and onStop() of the Activity lifecycle methods will get called. So in either onPause() or onStop(), we need to add the code snippet to recycle the bitmap and to free the memory.


if (currentImage != null) {
currentImage.recycle();
currentImage = null;
System.gc();
}


So onStop() will look like this.


public void onStop() {
super.onStop();
if (currentImage != null) {
currentImage.recycle();
currentImage = null;
System.gc();
}
}


The layout will look like this,


<?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:id="@+id/opengallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open Gallery"
/>
<ImageView android:id="@+id/selectedImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>


Happy Coding

Wednesday, November 9, 2011

Way to get Bluetooth Address in Android Phone

For getting bluetooth address first we need to enable bluetooth. The code snippet for getting bluetooth address is,


BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
String btMacAddress = btAdapter.getAddress();


The permission that we need to put in Manifest file is,


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

Way to get WiFi address in Android Phones

We will get the WiFi Mac address only if the WiFi is enabled in the device. The code snippet for getting the WiFi address is


WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String WifiMacAddress = info.getMacAddress();


The permission that we need to put in manifest file is,


<uses-permsission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permsission android:name="android.permission.CHANGE_WIFI_STATE" />

Androidians