Skip to content


Android: Working Asynchronously, AsyncTask

The AsyncTask class is a special class for Android development that encapsulates background processing and helps facilitate communication to the UI thread while managing the lifecycle of the background task within the context of the activity lifecycle .

AsyncTask is an abstract helper class for managing background operations that eventually post back to the UI thread. It creates a simpler interface for asynchronous operations than manually creating a Java Thread class. Instead of creating threads for background processing and using messages and message handlers for updating the UI, you can create a subclass of AsyncTask and implement the appropriate event methods.The onPreExecute() method runs on the UI thread before background processing begins.The doInBackground() method handles background processing, whereas publishProgress() informs the UI thread periodically about the background processing progress.When the background processing finishes, the onPostExecute() method runs on the UI thread to give a final update.

The following code demonstrates an example implementation of AsyncTask to perform the same functionality as the code for the Thread:

private class ImageLoader extends AsyncTask<URL, String, String> {
@Override
protected String doInBackground(
URL... params) {
// just one param
try {
URL text = params[0];
// ... parsing code {
publishProgress(
“imgCount = “ + curImageCount);
// ... end parsing code }
}
catch (Exception e ) {
Log.e(“Net”,
“Failed in parsing XML”, e);
return “Finished with failure.”;
}
return “Done...”;
}
protected void onCancelled() {
Log.e(“Net”, “Async task Cancelled”);
}
protected void onPostExecute(String result) {
mStatus.setText(result);
}
protected void onPreExecute() {
mStatus.setText(“About to load URL”);
}
protected void onProgressUpdate(
String... values) {
// just one value, please
mStatus.setText(values[0]);
}}

When launched with the AsyncTask.execute() method, doInBackground() runs in a background thread while the other methods run on the UI thread.There is no need to manage a Handler or post a Runnable object to it.This simplifies coding and debugging.

 

Posted in Android, Java, Open Source.

Tagged with , , , .


Android: Retrieving Network Status

For the network applications gathering the informations from network, it is useful to determine if a network connection is even available before trying to use a network resources. The ConnectivityManager class provides a number of methods to do this.The following code determines if the mobile (cellular) network is available and connected. In addition, it determines the same for the Wi-Fi network:

ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isWifiAvail = ni.isAvailable();
boolean isWifiConn = ni.isConnected();
ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isMobileAvail = ni.isAvailable();
boolean isMobileConn = ni.isConnected();
status.setText(“WiFi\nAvail = “+ isWifiAvail +
“\nConn = “ + isWifiConn +
“\nMobile\nAvail = “+ isMobileAvail +
“\nConn = “ + isMobileConn);

Figure shows the typical output for the emulator in which the mobile network is simulated but Wi-Fi isn’t available.

android network check image

For your application to read the status of the network, it needs explicit permission.The

following statement is required to be in its AndroidManifest.xml file:

<uses-permission
android:name=”android.permission.ACCESS_NETWORK_STATE”/>

Posted in Android, Java, Open Source.

Tagged with , , , .


Adding Logging support to Android Application

Logging is a valuable resource for debugging and learning Android applications. Android logging features are in the Log class of the android.util package.

Some helpful methods in the android.util.Log class are shown.

Log.e()  -> Log errors

Log.w()  -> Log warnings

Log.i()  ->  Log informational messages

Log.d()  -> Log Debug messages

Log.v()  -> Log Verbose mesages

To add logging support to android application, edit the file Activity Class. First, you must add the appropriate import statement for the Log class:

import android.util.Log;

Next, within the Activity class, declare a constant string that you use to tag all logging messages from this class.You can use the LogCat utility within Eclipse to filter  your logging messages to this debug tag:

private static final String DEBUG_TAG= “MyFirstAppLogging”;

Now, within the onCreate() method, you can log something informational:

Log.i(DEBUG_TAG, “Info about MyFirstAndroidApp”); 

Now you’re ready to run your application. Save your work and debug it in the emulator.You notice that your logging messages appear in the LogCat listing, with the Tag field MyFirstAppLogging as shown below.

android loggin image

 

 

Tip:

You might want to create a LogCat filter for only messages tagged with your debug tag. To do this, click the green plus sign button in the LogCat pane of Eclipse. Name your filter Just MyFirstApp, and fill in the Log Tag with your tag MyFirstAppLogging. Now you have a second LogCat tab with only your logging information shown.  

Posted in Android, Java, Open Source.

Tagged with , , , , , , .


Deleting android avd emulator

This site contains the pretty good usages of the avd commands for create, update, delete and move -avd.

http://wrestlingmind.blogspot.com/2009/08/more-commands-on-avd-to-create-delete.html

The deleting the avd that I have to come across can be achieved by:

android/android-sdk-linux_x86/tools$ ./android delete avd -n avd2.2

here, avd2.2 is the name of my avd, I wish to delete.

Check avd manager, avd2.2 should be deleted.

Posted in Android, Java.

Tagged with , , .


Transfering data from one android activity to another

In this tutorial, we’ll make a activity A that will invoke the activity B, and again the activity B will invoke activity C. The activity C in the end will, transfer some data to the activity B, and will straight open the Activity A.

This scenario is fairly important when we need to get back to the first/parent activity after calling the consecutive later activities including dialog boxes.

 

AvtivityB

@Override
 public void onClick(View v) {
 switch (v.getId()) {
 case R.id.button1:
 Intent intentC = new Intent(this, ActivityC.class);
 startActivityForResult(intentC, REQUEST_CODE);

 break;
default:
 break;
 }

 }

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
 if (data.hasExtra("returnKey1")) {
 Toast.makeText(this, data.getExtras().getString("returnKey1"),
 Toast.LENGTH_SHORT).show();

 finish();
 }
 }
 }

Activity C:

@Override
 public void onClick(View v) {
 switch (v.getId()) {
 case R.id.button1:

 Intent data = new Intent();
 // Return some hard-coded values
 data.putExtra("returnKey1", "Swinging on a star. ");
 data.putExtra("returnKey2", "You could be better then you are. ");
 setResult(RESULT_OK, data);
 super.finish();

 break;
default:
 break;
 }

 }

Find the total source code in the link below.

BetweenActivities

Posted in Uncategorized.


Convert .crt to .pem

The digital certificates have different formats. Often converting one format to other is necessary according to the application requirement.

For converting .crt to .pem, first of, install openssl. Then in terminal execute:

$ openssl x509 -in input.crt -out input.der -outform DER
$ openssl x509 -in input.der -inform DER -out output.pem -outform PEM

Posted in Java, linux.

Tagged with , , , , .


‘unknown’: unknown terminal type

I use Guake terminal for my ubuntu. Its just handy enough. I tried editing some files, it threw me a nasty error like:

'unknown': unknown terminal type.

After some googling, found the solution.

The default terminal type of my guake was ‘unknown’ for some reason.

echo $TERM

If it says, anything else than linux, do this:

export TERM=linux

Posted in linux, Open Source.

Tagged with , , , .


How to set JAVA_HOME in ubuntu

One way to do this is to set the JAVA_HOME variable and add to the PATH list. Edit /etc/bash.bashrc. You might need the root privileges for it. Add the following lines at the end of the file.
Set the java path to the actual java path you have in your machine.
For me, it is:

JAVA_HOME=/usr/lib/jvm/java-6-sun
export JAVA_HOME
PATH=$PATH:$JAVA_HOME/bin
export PATH

And reboot your system. Now checking if the path is correct:

echo $JAVA_HOME
/usr/lib/jvm/java-6-sun

Now, we are good to go.

Posted in Java, Open Source.

Tagged with , , , , .


Temperature Converter

Lets make a Temperature Converter Application. If you’ve read my previous blog on Hello World, this blog might not be a rocket science, but you would need some previous knowledge on the layouts and the controls! I’ll try explaining things as I go along!

Step1: File → New → Project → Android Project → [Name the project: TemperatueConverter] → [Select Build Target: Android 2.2 for me for now! ] → [Package Name:com.aniXification.temperatureConverter, Minimum SDK:8for me for now] → FINISH.

New Android project

New Android project

Step2: The final Temperature Converter will look somewhat like this! The following is the main.xml layout view.

final App

final App

Its xml data is:

<?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” >

<LinearLayout

android:id=“@+id/linearLayout1″

android:layout_width=“match_parent”

android:layout_height=“wrap_content” >

<EditText

android:id=“@+id/editTextTemp”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:layout_weight=“0.39″

android:inputType=“numberDecimal|numberSigned” >

</EditText>

<Button

android:id=“@+id/up”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:onClick=“onUpButtonClicked”

android:text=“@string/up” />

<Button

android:id=“@+id/down”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:onClick=“onDownButtonClicked”

android:text=“@string/down” />

</LinearLayout>

<RadioGroup

android:id=“@+id/radioGroup1″

android:layout_width=“wrap_content”

android:layout_height=“wrap_content” >

<RadioButton

android:id=“@+id/celsiusRButton”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:checked=“true”

android:text=“@string/toCelsius” />

<RadioButton

android:id=“@+id/fahrenheitRButton”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:text=“@string/toFahrenheit” />

</RadioGroup>

<Button

android:id=“@+id/convertButton”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:onClick=“onConverterButtonClicked”

android:text=“@string/convert” />

</LinearLayout>

The layout consists of:

  1. The parent Vetrical LinearLayout

    1. The subparent Horizontal Layout

      1. A EditText

      2. Up Button

      3. Down Button

    2. RadioGroup

      1. to Celsius RadioButton

      2. to Fahrenheit RadioButton

    3. Convert Button

If you see in the buttons above the onClick event is called which will be handled in our main Java class.

Before using the above xml file, copy the following xml file to strings.xml in res → values

<?xml version=“1.0″ encoding=“utf-8″?>

<resources>

<string name=“hello”>Hello World, TemperatureConverterActivity!</string>

<string name=“app_name”>TemperatureConverter</string>

<string name=“up”>up</string>

<string name=“down”>down</string>

<string name=“toCelsius”>to Celsius</string>

<string name=“toFahrenheit”>to Fahrenheit</string>

<string name=“convert”>Convert</string>

<string name=“temtToConvert”>Enter the temperature</string>

</resources>

These are the strings names used for the controls in the main.xml

Step3: Now. Lets look into the TemperatureConverterActivity.java class. Its is the main java class for me.

package com.aniXification.temperatureConverter;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.EditText;

import android.widget.RadioButton;

import android.widget.Toast;

public class TemperatureConverterActivity extends Activity {

/** Called when the activity is first created. */

private EditText editTextGetTemp;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

editTextGetTemp = (EditText)findViewById(R.id.editTextTemp);

}

//The Convert Button Event Handler

public void onConverterButtonClicked(View view){

switch(view.getId()){

case R.id.convertButton:

RadioButton celsiusRButton = (RadioButton)findViewById(R.id.celsiusRButton);

RadioButton fahrenheitRButton = (RadioButton)findViewById(R.id.fahrenheitRButton);

//when the user clicks the button with empty EditText

if (editTextGetTemp.getText().length() == 0){

Toast.makeText(this, “Please enter some valid value”,Toast.LENGTH_LONG).show();

return;

}

//when valid value is entered

float inputTemp = Float.parseFloat(editTextGetTemp.getText().toString());

if(celsiusRButton.isChecked()){

editTextGetTemp.setText(String.valueOf(convertFahrenheitToCelsius(inputTemp)));

celsiusRButton.setChecked(false);

fahrenheitRButton.setChecked(true);

}

else{

editTextGetTemp.setText(String.valueOf(convertCelsiusToFahrenheit(inputTemp)));

fahrenheitRButton.setChecked(false);

celsiusRButton.setChecked(true);

}

}

}

//On Up Button Clicked

public void onUpButtonClicked(View view){

//when the user clicks the button with empty EditText

if (editTextGetTemp.getText().length() == 0){

Toast.makeText(this, “Please enter some valid value first”,Toast.LENGTH_LONG).show();

return;

}

else{

float inputTemp = Float.parseFloat(editTextGetTemp.getText().toString());

inputTemp ++ ;

editTextGetTemp.setText(“”+ inputTemp);

}

}

//On Down Button Clicked

public void onDownButtonClicked(View view){

//when the user clicks the button with empty EditText

if (editTextGetTemp.getText().length() == 0){

Toast.makeText(this, “Please enter some valid value first”,Toast.LENGTH_LONG).show();

return;

}

else{

float inputTemp = Float.parseFloat(editTextGetTemp.getText().toString());

inputTemp –;

editTextGetTemp.setText(“”+ inputTemp);

}

}

//Convert Fahrenheit to celsius

private float convertFahrenheitToCelsius(float fahrenheit){

return ((fahrenheit -32)*5/9);

}

//Convert to Fahrenheit to Celsius

private float convertCelsiusToFahrenheit(float celsius){

return ((9*celsius)/5)+ 32;

}

}

Now lets look what the above piece of code does,

  1. The EditText must not NULL to increase the counter, decrease the counter and the Temperature Conversion

  2. Enter any decimal or integer to the EditText check the radioButton to convert the temperature to and click the convert Button. And have the temperature converted!

The snapshot of the final application.

Final Application

Final Application

Download the pdf version in here! temperature converter

Posted in Android, Open Source.

Tagged with , , , .


Hello World!

What programming language has started with no Hello World? And we HELLO WORLD here too! Get the Android development environment set up and lets rock n roll!

Step1: File → New → Project → Android Project → [Name the project: Hello World] → [Select Build Target: Android 4.0 for me for now! ] → [Package Name:com.aniXification.HelloWorld, Minimum SDK:14 for me for now] → FINISH. And we are done! C ya in next blog! Lol.

Well, we have created a empty project and the project directory will look somewhat like this:

helloworld-project directory

helloworld-project directory

Step 2: Before jumping into anything, lets run the application to see what has happened!

Select the project [Hello World] → Right Click → Run As Android Application.

 If you have AVD, setup correctly, you will have Android phone emulator up and running in a couple of minutes! [I know it feels like years! ;) ]

helloworld-initial snapshot

helloworld-initial snapshot

And here we go, our application already says hello world! How come?? Lets see how?

Step 3: Lets see the code in HelloWorldActivity.java

helloworld-activityjava

helloworld-activityjava

When our application is first launched, it launches the HelloWorldActivity activity, which the project created while we made an empty project! This activity names the package, the couple import files and the activity class. As soon as this activity launches, the onCreate() function gets called and fills the content [UI in the phone] with whats there defined in Resource -> layout -> main xml file.

 Step 4: Open the main.xml file located in res Folder → layout Sub folder → main.xml

mainxmlfirst

mainxmlfirst

 Okay, here we have the design layout of the application. This view can be switched with the xml view from the tabs at the left bottom corner! For now we are good to go with the design layout.

If you observer it, it contains the TEXTVIEW with value “Hello World, HelloWorldActivity!”. This was what show when we ran the application. New lets make a button that shows “Hello World!!” on our terms!

Lets drag the button from the [Palette Window → Form Widget → Button] to the phone canvas!

Shift to the XML view and change

android:text=“Button” to android:text=“Click me”

From the Graphic layout, right click the button, → Other Properties → All By Name → on Click → [ButtonClick] to name the onClick event handler!

To tally with the xml file, android:onClick=“ButtonClick” will be present in the attribute of the button tag!

Write the button click event after the onCreate()function.

onclick event handler

onclick event handler

When the button is clicked, it shows “Hello World!!”

And thats it. “Hello World! ” Its a start, at least of a long journey.

Download the pdf version of this tutorial in here! Hello World pdf

Posted in Android, Open Source.

Tagged with , , .