CodeByte

Write your code smartly

Tag Archives: java

AsyncTask Implementation using callback interface

Here in this post I will write about how AsyncTask can be created as a single class to make it re useable for other activities. There are some ways to handle the background operations well-known-ed for foreground apps (not services). AsyncTask allows you to execute a specific task such as downloading, loading content from web or communication to server without blocking the main thread (user interface). Writing the code for AsyncTask is quite simple, but what when you have more than one activity to process same piece of code/task in AsyncTask. Now here comes the greatest benefit of Object Oriented Programming concepts and mechanism to write a code which can be re-used. Thanks to an interview question which made me dive into this and get to know how can this be achieved. What we will do here is, create a single AsyncTask and put it in a separate class and make use of it in which ever activity we want. The main problem comes with handling the result of the AsyncTask operation. Lets have a look at how AsyncTask class can be extended to our custom class and we can perform operations required to be done in the background.
First you have to create ad simple class and extend it from AsyncTask

public class myCustomAsyncTask extends AsyncTask{
}

Now myCustomAsyncTask will have a compile time error, stating first suggestion to be : Add unimplemented methods. As you are performing inheritance here and extending the AsyncTask parent class, there is a method defined which must be implemented and that is doInBackground

@Override
protected Object doInBackground(Object... arg0){
    return null;
}

doInBackground is the method where the background operation is performed. There are other methods provided by AsyncTask such as onPreExecute, onPostExecute, onCancelled, onProgressUpdate having their own benefits.
If you want to perform some tasks prior to your main background operation such as some parameters initialization, load resources etc, you can do that in onPreExecute method

@Override
protected void onPreExecute(){
    // Your code
}

Once we execute AsyncTask, the first method called is onPreExecute and then doInBackground. Now what after the background operations are completed and you want to show some response or play with result. Here comes to use of onPostExecute

protected void onPostExecute(Object o){
       // Your code to handle data
}

Note: Updating any UI controls is not allowed in doInBackground method but can be done inside onPostExecute, like update text of a textview or progress bar etc…

So lets create a AsyncTask first.

public class YourAsyncTask extends AsyncTask<Object,Object,Object>{
    String s = "";

    public YourAsyncTask(){
    }
    
    @Override
    protected Object doInBackground(Object... arg0) {
        return null;
    }

    protected void onPostExecute(Object o){
    }
}

Here we have overridden two AsyncTask methods: doInBackground and onPostExecute. It also have a constructor to get the context of the activity invoking it.

Now there are several ways on handling the response, but without getting out of the Activity context (making activity class members dead (non-static fields)) is what meant here.
Making use of Interface is useful here. Interface helps you implement it when its required by simply using implement following your class name and Interface name.
But before that lets make an interface so we can handle the response of the AsyncTask by implementing its method.

public interface OnTaskCompleted {
    void onTaskCompleted(String response);
}

As the above interface shows, there is a method onTaskCompleted which takes an argument of String type must be implemented by any class implementing the interface.

We implement the interface through our activity using

public class MainActivity extends Activity implements OnTaskCompleted {
}

It will ask you to implement unimplemented methods so go ahead with it and you will see the method inside interface onTaskCompleted will be added to the activity class.

public class MainActivity extends Activity implements OnTaskCompleted {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    @Override
    public void onTaskCompleted(String response) {
    }
}

Now using AsyncTask from activity. We will do this inside onCreate method of the activity.

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        YourAsyncTask task = new YourAsyncTask(MainActivity.this);
        task.execute();
    }

Now lets add onTaskCompleted (interface) to the AsyncTask and return the response from onPostExecute. It is also the final code of AsyncTask implementation.

public class YourAsyncTask extends AsyncTask<Object,Object,Object>{
    String s = "";
    private onTaskCompleted taskCompleted;
    
    public YourAsyncTask(OnTaskCompleted activityContext){
        this.taskCompleted = activityContext;
    }
    
    @Override
    protected Object doInBackground(Object... arg0) {
        return null;
    }

    protected void onPostExecute(Object o){
        taskCompleted.onTaskCompleted(s);
    }
}

Add the response handling code in the implemented method onTaskCompleted inside activity.

@Override
public void onTaskCompleted(String response) {
    // Just showing the response in a Toast message
    Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}

Here is how your final Interface code looks

public interface OnTaskCompleted {
    void onTaskCompleted(String response);
}

Activity Full code

public class MainActivity extends Activity implements OnTaskCompleted {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        YourAsyncTask task = new YourAsyncTask(MainActivity.this);
        task.execute();
    }
    
    @Override
    public void onTaskCompleted(String response) {
        // Just showing the response in a Toast message
        Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
    }
}

You can contact me by visiting the about page and picking up the contact details.
Happy coding!

Android: Create Shortcut Icon

Here is how you can create a shortcut icon on Android device

try
{
//checking the shortcut icon is created or not
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false)) {
Intent shortcutintent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//repeat to create is forbidden
shortcutintent.putExtra("duplicate", false);
//set the name of shortCut
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "MinhaConexao");
//set icon
Parcelable icon = Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.shortcut);
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
//set the application to launch when you click the icon
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(getApplicationContext() , MinhaConexao.class));
//sendBroadcast,done
sendBroadcast(shortcutintent);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}

The shared preferences are in application memory having a life cycle equal to application life cycle. Calling the shortcut creating code every time will popup a system Toast (irritating) which cannot be controlled. Making use of Shared Preferences can help you log the status of shortcut icon. If it is the first time application is launched then shortcut creating code will be executed as according to the code above else create the icon. The icon will appear on the main screen of the Android device.

Don’t forget to add permissions in AndroidManifest.xml

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />

Happy Coding !

Simple TCP Client Server Communication using Android

The following post is about simple TCP Client Server communication sample using Java code for Android. The steps are simple as defined below. TCP communication is done over inter-network or internal network (not necessary internet working). There must be an IP-Address for destination and a unique port (with unique I mean is not one which is used for standard protocols such as File Transfer Protocol (FTP) uses port number 21, TCP uses port 80) list can be found here for more reference. The port range is from 1 to 65535. Selecting a port from this range and an IP address, you can simply transmit data over network directly to the destination port.

TCP Client connection to TCP server to send data


try{
// Creating new socket connection to the IP (first parameter) and its opened port (second parameter)
Socket s = new Socket("192.168.1.1", 5555);

// Initialize output stream to write message to the socket stream
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

String outMsg = "";

outMsg = "This is Client";

// Write message to stream
out.write(outMsg);

// Flush the data from the stream to indicate end of message
out.flush();

// Close the output stream
out.close();

// Close the socket connection
s.close();
}

catch(Exception ex){
//:TODO Handle exceptions
}

A simple TCP server to receive the TCP packet from client.

TCP Server receive the data using the port as IP address is just mentioned from the source and not required anywhere for TCP Server.


try{

ServerSocket ss = null;

// Initialize Server Socket to listen to its opened port
ss = new ServerSocket(5555);

// Accept any client connection
Socket s = ss.accept();

// Initialize Buffered reader to read the message from the client
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

// Get incoming message
String incomingMessage = in.readLine() + System.getProperty("line.separator");

// Use incomingMessage as required
System.out.print(incomingMessage);

// Close input stream
in.close();

// Close Socket
s.close();

// Close server socket
ss.close();

}
catch(Exception ex){
//:TODO Handle exceptions
}

You can utilize the received message accordingly.

To test the working example on Android devices you must add permissions to AndroidManifest.xml

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

Cheers !

 

XML Parsing Android JAVA

I am going to explain and show how you can easily parse a normal xml response using DOM Parsing concept. There are other parsing methods such as Pull Parsing and SAX Parsing and its on the choice of the developer in which way they want to parse.

Here is a simple XML response which can be a local file or accessible from the web.


<?xml version="1.0" encoding="utf-8"?>
<settings>
 <woeid>
  <countrywoeid>2211096</countrywoeid>
  <countryname>Asia/Karachi</countryname>
 </woeid>
 <woeid>
  <countrywoeid>2211177</countrywoeid>
  <countryname>Asia/Karachi</countryname>
 </woeid>
 <woeid>
  <countrywoeid>2459115</countrywoeid>
  <countryname>America/New_York</countryname>
 </woeid>
 <woeid>
  <countrywoeid>1940345</countrywoeid>
  <countryname>Asia/Dubai</countryname>
 </woeid>
 <woeid>
  <countrywoeid>1105779</countrywoeid>
  <countryname>Australia/Sydney</countryname>
 </woeid>
 <woeid>
  <countrywoeid>2251945</countrywoeid>
  <countryname>Asia/Tehran</countryname>
 </woeid>
</settings>

This is a local file inside the sdcard of the Android device. Using the code below we can access the XML file on the root of the sdcard.


InputStream filename = null;
//parse the local XML file

filename=new FileInputStream("/sdcard/weatherFile.xml");
InputSource is = new InputSource(filename);

Using the InputStream class we can easily set the location of the xml file in the sdcard as shown in the code above. InputSource uses the instance of the InputStream to utilize it in further parsing. Here is how we can use DocumentBuilder class to create a document of the xml response to parse its all nodes.


DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc=db.parse(new InputSource(is.getByteStream()));
doc.getDocumentElement().normalize();

Document builder helps to create a tree structure with nodes in normalized form. The list of the nodes can be collected in the NodeList instance for further traversing.


NodeList nodeList = doc.getElementsByTagName("woeid");
for (int i = 0; i < nodeList.getLength(); i++)
{
  Node node = nodeList.item(i);
  Element fstElmnt = (Element) node;
  pointer++;

  woeid=Integer.parseInt(fstElmnt.getElementsByTagName("countrywoeid").item(0).getTextContent());
  timeZone=fstElmnt.getElementsByTagName("countryname").item(0).getTextContent();
}

You can collect the all the nodes text in an array or you can get in a string variable and upon your requirement, it is easily used further.

So here is how the final code looks

InputStream filename = null;
//parse the local XML file

filename=new FileInputStream("/sdcard/weatherFile.xml");
InputSource is = new InputSource(filename);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc=db.parse(new InputSource(is.getByteStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("woeid");
for (int i = 0; i < nodeList.getLength(); i++)
{
  Node node = nodeList.item(i);
  Element fstElmnt = (Element) node;
  pointer++;

  woeid=Integer.parseInt(fstElmnt.getElementsByTagName("countrywoeid").item(0).getTextContent());
  timeZone=fstElmnt.getElementsByTagName("countryname").item(0).getTextContent();
}
Design a site like this with WordPress.com
Get started