Android Series: GET, POST and Multipart POST requests

Posted by admin | Posted in Code Snippets, Mobile Development | Posted on 18-03-2010

11

Today I will describe shortly how to execute http GET and POST request on Android platform.
The code is very simple and straightforward, for post request with attachement, you would have to add apache-mime4j-0.6.jar and httpmime-4.0.1.jar to your build path.

HTTP GET

try {
        HttpClient client = new DefaultHttpClient();  
        String getURL = "http://www.google.com";
        HttpGet get = new HttpGet(getURL);
        HttpResponse responseGet = client.execute(get);  
        HttpEntity resEntityGet = responseGet.getEntity();  
        if (resEntityGet != null) {  
                    //do something with the response
                    Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
                }
} catch (Exception e) {
    e.printStackTrace();
}

HTTP POST

try {
        HttpClient client = new DefaultHttpClient();  
        String postURL = "http://somepostaddress.com";
        HttpPost post = new HttpPost(postURL);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("user", "kris"));
            params.add(new BasicNameValuePair("pass", "xyz"));
            UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
            post.setEntity(ent);
            HttpResponse responsePOST = client.execute(post);  
            HttpEntity resEntity = responsePOST.getEntity();  
            if (resEntity != null) {    
                Log.i("RESPONSE",EntityUtils.toString(resEntity));
            }
    } catch (Exception e) {
        e.printStackTrace();
    }

HTTP POST with File attachment

File file = new File("path/to/your/file.txt");
try {
         HttpClient client = new DefaultHttpClient();  
         String postURL = "http://someposturl.com";
         HttpPost post = new HttpPost(postURL);
     FileBody bin = new FileBody(file);
     MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
     reqEntity.addPart("myFile", bin);
     post.setEntity(reqEntity);  
     HttpResponse response = client.execute(post);  
     HttpEntity resEntity = response.getEntity();  
     if (resEntity != null) {    
               Log.i("RESPONSE",EntityUtils.toString(resEntity));
         }
} catch (Exception e) {
    e.printStackTrace();
}

Hope this helps!

Android Series: Using GPS data

Posted by admin | Posted in Code Snippets, Mobile Development | Posted on 15-03-2010

1

In this tutorial i will show you how to quickly get the gps data using your android device version 1.6+.

All you have to do is to implement one interface and acquire LocationMangager from the adnroid system service.

public class LocationExampleAct extends Activity implements LocationListener{


    private double latitude;
    private double longitude;
    private LocationManager locMgr = null;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
   
        locationTxt = (TextView)findViewById(R.id.location_id);
       
        locMgr = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
       
    }
   
    @Override
    public void onLocationChanged(Location location) {
        this.latitude = location.getLatitude();
        this.longitude = location.getLongitude();
        this.locationTxt.setText("Location: "+this.latitude +" : " + this.longitude);
        Log.i("Location change",""+latitude+ " : "+longitude) ;
    }
    @Override
    public void onProviderDisabled(String provider) {
       
    }
    @Override
    public void onProviderEnabled(String provider) {
       
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
       
    }
}

Android Series: Parsing JSON data with GSON

Posted by admin | Posted in Code Snippets, Mobile Development | Posted on 25-02-2010

7

Today I will describe how to parse json data using Gson open source library and how to convert it at the same time to java objects.
This is a typical cookbook example and should be very easy to follow.


1. Create an Android application with one activity, name it as you wish, if you are doing it in eclipse all the basic stuff will be generated for you which is exactly what we need.
2. Find an example url which responds in JSON, I have used Twitter Trends found here: http://search.twitter.com/trends.json
The example response looks like this:

{"as_of":"Thu, 25 Feb 2010 11:30:17 +0000","trends":[{"name":"#nowplaying","url":"http://search.twitter.com/search?q=%23nowplaying"},{"name":"#nothingworsethan","url":"http://search.twitter.com/search?q=%23nothingworsethan"},{"name":"Dubai Mall","url":"http://search.twitter.com/search?q=%22Dubai+Mall%22"},{"name":"iPad Gets","url":"http://search.twitter.com/search?q=%22iPad+Gets%22"},{"name":"#SuperJuniorTrot","url":"http://search.twitter.com/search?q=%23SuperJuniorTrot"},{"name":"Justin Bieber","url":"http://search.twitter.com/search?q=%22Justin+Bieber%22"},{"name":"Click","url":"http://search.twitter.com/search?q=Click"},{"name":"Jaebum","url":"http://search.twitter.com/search?q=Jaebum"},{"name":"#tosavemoney","url":"http://search.twitter.com/search?q=%23tosavemoney"},{"name":"Protection","url":"http://search.twitter.com/search?q=Protection"}]}



As you can see this json data contains date attribute called ‘as_of’ as well as array of items, each consisting of name and url attributes.
We will create two simple java classes wich will hold that information.
First one is TwitterTrends.java

package com.softwarepassion.jsonexample;

import java.util.Date;
import java.util.List;

public class TwitterTrends {

    private String as_of;
    private List<TwitterTrend> trends;
   
    public String getAs_of() {
        return as_of;
    }
    public void setAs_of(String asOf) {
        as_of = asOf;
    }
    public List<TwitterTrend> getTrends() {
        return trends;
    }
    public void setTrends(List<TwitterTrend> trends) {
        this.trends = trends;
    }
   
   
   
}

And the second one is a simple TwitterTrend.java

package com.softwarepassion.jsonexample;

public class TwitterTrend {
    private String name;
    private String url;
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
}

TwitterTrends contains a list of TwitterTrend objects, both of them are simple beans and are very similar to the json response if you look closely :) .

Now the fun part begins.

Download the Gson library from http://code.google.com/p/google-gson/ and add it to your java build path in eclipse.
Once you do that, you can now transform your json response to Java object on Android Platform:
Get the response as InputStream:

public InputStream getJSONData(String url){
        DefaultHttpClient httpClient = new DefaultHttpClient();
        URI uri;
        InputStream data = null;
        try {
            uri = new URI(url);
            HttpGet method = new HttpGet(uri);
            HttpResponse response = httpClient.execute(method);
            data = response.getEntity().getContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
       
        return data;
    }

Then use that input stream to create your java objects:

public void runJSONParser(){
        try{
        Log.i("MY INFO", "Json Parser started..");
        Gson gson = new Gson();
        Reader r = new InputStreamReader(getJSONData("http://search.twitter.com/trends.json"));
        Log.i("MY INFO", r.toString());
        TwitterTrends objs = gson.fromJson(r, TwitterTrends.class);
        Log.i("MY INFO", ""+objs.getTrends().size());
        for(TwitterTrend tr : objs.getTrends()){
            Log.i("TRENDS", tr.getName() + " - " + tr.getUrl());
        }
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

Easy ha!

Android Series: Custom ListView items and adapters

Posted by admin | Posted in Mobile Development | Posted on 20-05-2009

80

This is a short tutorial on how to populate your android list view, with data downloaded from the internet or other sources, using ArrayAdapter. ListView items view is declared in a separate XML file and displayed using custom adapter class.
First things first, so go ahead and create a new project using Eclipse equipped with ADT plugin.
The project described below assumes you have a list of objects created, this can be either downloaded from the internet as XML and parsed to create ArrayList of your custom objects or anything you imagine. I will not go into details on this tutorial how to create such an ArrayList but your imagination is the limit. Parsing XML downloaded from the net will be covered in the next tutorial coming up soon.


Click File -> New -> Project and select the ‘Android Project’ wizard:

android11

Click next and fill out the next screen with the following values:

android21

Once you have filled out all the necessary data you can click finish.
Your new project has just been created. Now lets modify it a bit to display our custom made list.
Open up SoftwarePassionView.java in the eclipse editor and change the class file to the following:

1. Define necessary member variables we will use later in our class

private ProgressDialog m_ProgressDialog = null;
    private ArrayList<Order> m_orders = null;
    private OrderAdapter m_adapter;
    private Runnable viewOrders;

m_ProgressDialog is a small pop up displaying information that your data is being downloaded or retrieved other way.
m_orders is an ArrayList which will hold our data downloaded from the internet or acquired other way
m_adapter is our custom class extending ArrayAdapter
viewOrders is a runnable for downloading data from the internet in a separate thread

To import whatever you can at this point click Ctrl+Shit+O, some classes like Order or OrderAdapter are not created yet but don’t worry we will come to that point soon.
Another important note at this point is that your SoftwarePassoinView should extend ListActivity instead of simple Activity.
Your class should look more or less something like this now:

package com.softberries.lve;

import java.util.ArrayList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;

public class SoftwarePassionView extends ListActivity{
   
    private ProgressDialog m_ProgressDialog = null;
    private ArrayList<Order> m_orders = null;
    private OrderAdapter m_adapter;
    private Runnable viewOrders;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Now lets create our simple Order class holding single order.
Right click on the project and and select ‘New’ -> ‘Class’, name it order and open it up in the editor.
The source code for our orders looks like this:

package com.softberries.lve;

public class Order {
   
    private String orderName;
    private String orderStatus;
   
    public String getOrderName() {
        return orderName;
    }
    public void setOrderName(String orderName) {
        this.orderName = orderName;
    }
    public String getOrderStatus() {
        return orderStatus;
    }
    public void setOrderStatus(String orderStatus) {
        this.orderStatus = orderStatus;
    }
}

The Order class is very simple and contains only 2 strings with getters and setter generated for them
Now lets change our main.xml file to hold our custom list items:

<?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"
   >
<ListView
    android:id="@+id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
<TextView
    android:id="@+id/android:empty"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="@string/main_no_items"/>
</LinearLayout>

This layout will display our list items if any and if the list is empty it will display ‘No orders to display’ string defined in string.xml resource file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, SoftwarePassionView!</string>
    <string name="app_name">Software Passion</string>
    <string name="main_no_items">No orders to display</string>
</resources>



Our list item (single row on the list) have a custom layout as well, defined in row.xml file:

<?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="?android:attr/listPreferredItemHeight"
    android:padding="6dip">
    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="6dip"
        android:src="@drawable/icon" />
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="0dip"
        android:layout_weight="1"
        android:layout_height="fill_parent">
        <TextView
            android:id="@+id/toptext"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1"
            android:gravity="center_vertical"
        />
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1"
            android:id="@+id/bottomtext"
            android:singleLine="true"
            android:ellipsize="marquee"
        />
    </LinearLayout>
</LinearLayout>

Single row example has been borrowed from the romain Guy website here

Ok, so we have all our layouts defined in the res folder under layout. Now its time to go back to our code and create our custom OrderAdapter class which will manage our list of orders:

private class OrderAdapter extends ArrayAdapter<Order> {

        private ArrayList<Order> items;

        public OrderAdapter(Context context, int textViewResourceId, ArrayList<Order> items) {
                super(context, textViewResourceId, items);
                this.items = items;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.row, null);
                }
                Order o = items.get(position);
                if (o != null) {
                        TextView tt = (TextView) v.findViewById(R.id.toptext);
                        TextView bt = (TextView) v.findViewById(R.id.bottomtext);
                        if (tt != null) {
                              tt.setText("Name: "+o.getOrderName());                            }
                        if(bt != null){
                              bt.setText("Status: "+ o.getOrderStatus());
                        }
                }
                return v;
        }
}

This is a private class and should be added to our SoftwarePassionView. This is extended ListAdapter which inside overriden getView method returns our row with assigned string values to the textfields defined in row.xml.

A huge part of our application is already done. Now we have to add some modifications to the onCreate method to initialize everything properly and add a method retrieving our orders from somewhere, lets start with the latter:

private void getOrders(){
          try{
              m_orders = new ArrayList<Order>();
              Order o1 = new Order();
              o1.setOrderName("SF services");
              o1.setOrderStatus("Pending");
              Order o2 = new Order();
              o2.setOrderName("SF Advertisement");
              o2.setOrderStatus("Completed");
              m_orders.add(o1);
              m_orders.add(o2);
                 Thread.sleep(2000);
              Log.i("ARRAY", ""+ m_orders.size());
            } catch (Exception e) {
              Log.e("BACKGROUND_PROC", e.getMessage());
            }
            runOnUiThread(returnRes);
        }



Instead of creating our simple orders in the method above you could of course download them from somewhere and assign the result to the m_orders array list. The method runOnUIThread is a utility method for running tasks back on the main UI thread after the job is done on the separate thread created for long running tasks. We will call our getOrders method from a separate thread.

The returnRes runnable adds newly retrieved Order object to our custom Adapter and notifies it of the data change:

private Runnable returnRes = new Runnable() {

            @Override
            public void run() {
                if(m_orders != null && m_orders.size() > 0){
                    m_adapter.notifyDataSetChanged();
                    for(int i=0;i<m_orders.size();i++)
                    m_adapter.add(m_orders.get(i));
                }
                m_ProgressDialog.dismiss();
                m_adapter.notifyDataSetChanged();
            }
          };

Now lets move to our overriden onCreate method. We will initialize here all the member variables as well as start a new thread retrieving our orders:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        m_orders = new ArrayList<Order>();
        this.m_adapter = new OrderAdapter(this, R.layout.row, m_orders);
                setListAdapter(this.m_adapter);
       
        viewOrders = new Runnable(){
            @Override
            public void run() {
                getOrders();
            }
        };
    Thread thread =  new Thread(null, viewOrders, "MagentoBackground");
        thread.start();
        m_ProgressDialog = ProgressDialog.show(SoftwarePassionView.this,    
              "Please wait...", "Retrieving data ...", true);
    }

After initialization, we start new thread using the viewOrders runnable and show the progress dialog which we close once the orders are retrieved.
Now you should be able to run your application. After the application starts it spawns new thread and displays the loader:

screen_load screen1

And thats it. You can add an Item Click Listener to your list to start new activities etc.
Full source code for the SoftwarePassionView below:

package com.softberries.lve;

import java.util.ArrayList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class SoftwarePassionView extends ListActivity{
   
    private ProgressDialog m_ProgressDialog = null;
    private ArrayList<Order> m_orders = null;
    private OrderAdapter m_adapter;
    private Runnable viewOrders;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        m_orders = new ArrayList<Order>();
        this.m_adapter = new OrderAdapter(this, R.layout.row, m_orders);
        setListAdapter(this.m_adapter);
       
        viewOrders = new Runnable(){
            @Override
            public void run() {
                getOrders();
            }
        };
        Thread thread =  new Thread(null, viewOrders, "MagentoBackground");
        thread.start();
        m_ProgressDialog = ProgressDialog.show(SoftwarePassionView.this,    
              "Please wait...", "Retrieving data ...", true);
    }
    private Runnable returnRes = new Runnable() {

        @Override
        public void run() {
            if(m_orders != null && m_orders.size() > 0){
                m_adapter.notifyDataSetChanged();
                for(int i=0;i<m_orders.size();i++)
                m_adapter.add(m_orders.get(i));
            }
            m_ProgressDialog.dismiss();
            m_adapter.notifyDataSetChanged();
        }
    };
    private void getOrders(){
          try{
              m_orders = new ArrayList<Order>();
              Order o1 = new Order();
              o1.setOrderName("SF services");
              o1.setOrderStatus("Pending");
              Order o2 = new Order();
              o2.setOrderName("SF Advertisement");
              o2.setOrderStatus("Completed");
              m_orders.add(o1);
              m_orders.add(o2);
              Thread.sleep(5000);
              Log.i("ARRAY", ""+ m_orders.size());
            } catch (Exception e) {
              Log.e("BACKGROUND_PROC", e.getMessage());
            }
            runOnUiThread(returnRes);
        }
    private class OrderAdapter extends ArrayAdapter<Order> {

        private ArrayList<Order> items;

        public OrderAdapter(Context context, int textViewResourceId, ArrayList<Order> items) {
                super(context, textViewResourceId, items);
                this.items = items;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.row, null);
                }
                Order o = items.get(position);
                if (o != null) {
                        TextView tt = (TextView) v.findViewById(R.id.toptext);
                        TextView bt = (TextView) v.findViewById(R.id.bottomtext);
                        if (tt != null) {
                              tt.setText("Name: "+o.getOrderName());                            }
                        if(bt != null){
                              bt.setText("Status: "+ o.getOrderStatus());
                        }
                }
                return v;
        }
}
}



Enjoy!

New discovery for MIDP development

Posted by admin | Posted in Mobile Development | Posted on 17-01-2009

1


Just wanted to spread the word about my new discovery. About a year ago I was adding finishing touches to my final year project on University of Greenwich and I remember that one of the biggest problems was to come up with a nicely looking UI for my mobile application. I’ve used SVG and I have to say that the effect was ‘ok’, could be much better but building up applications with svg was in my opinion difficult. I had to concentrate my efforts on the web services but spent most of my time building up GUI. Well, after a year I’ve incidently found a nice and promising open source project which would solve this using CSS techniques and two small libraries, the project is named KUIX and you can find out more about it on the kalmeo.org website. I have to add that I tried Java ME Polish and for me KUIX way of doing things is much simpler.
You can check out the demo here
Enjoy!

Java ME menu with SVG-tiny.

Posted by admin | Posted in Code Snippets, Mobile Development | Posted on 08-10-2007

5

Finally I did it! All the trial versions of Adobe Illustrator, Ikivo Animator, Beatware Mobile Designer and God knows whats more got expired and I really did start looking for other solutions to create Java ME menu (different than the standard solutions from the J2ME libraries) when finally I did something really simple – I just took a similar thing found on java.net and carefully examined the XML code behind the picture.
Looking for a similar solutions was my latest nightmare, I have to prepare my Final Year Project, the project itself is not about mobile GUI’s so I don’t want to spend much time on it but I just didn’t want to go for a demo with those ugly standard java components.
There are a number of tutorials how to add svg tiny files in Netbeans Mobility Pack but it is very difficult to find a tutorial describing how to create such a file. Nevertheless, I have found myself in a situation where I have just decided to write such a file from scratch and forget about all those fancy tools as they are almost zero compatible between each other (even when each of them produces “standard” svgt file as an output ;) ), and because of the fact that I couldn’t find enough resources on the net about using them for this purpose.
Speaking about the tools, I have found very strange thing about Beatware Mobile Designer software, so many times seen on the Sun’s/NetBeans tutorias or screencasts, this software is almost impossible to find, maybe my ISP blocks access to their servers for some reason which I can’t imagine, but I had to digg in some very dusty corners of the net to obtain the trial version of this software.
Anyway, maybe sometimes is just best to stick with the simplest tool – text editor!
After a while, when experimenting with the svg document I started to realize that it is not actually that difficult to follow.
Check out the tutorial “Adding and Editing Scalable Vector Graphic (SVG) Files in the Mobility Pack” @:
http://www.netbeans.org/kb/55/svg-tutorial.html
The necessary files for this tutorial you can download from:
http://wiki.netbeans.info/wiki/attach/NBDemoSVG/svgs.zip
When you download the svgs.zip and unpack it you will find a file named “menu.svg”,
Open the file in any text editor and you can play with it, checking in Netbeans if it’s still svgt compilant ;)
The menu is pretty simple, consist of two layers, one with graphics beneath menu elements and another one with menu itself :
To create the your own menu just delete the layer with the graphics if you don’t like it and add another one.
You can easily sort out the menu elements, how they are organised and how they work.
1. First thing to remember is that all menu elements must be named with the pattern:
menuItem_blahblah, this is necessary if you want netbeans to recognize the element as an actual menu item.
2. The menu itself consists of simple animated text elements, if you want to add/remove another menu item just copy the existing one and change the element name plus the values in “values” attribute accordingly, you can sort out what values you have to enter there by looking at previous elements.
3. To make the moving box work with additional menu elements you have to put some more work into it, first remove all existing “animateTransform” elements nested within element and insert there new transforms which will work with any number of menu items. The new transforms for my menu look like this:

begin="menuItem_0_download.focusin" dur="0.3s"end="menuItem_0_download.focusout" fill="freeze"/> begin="menuItem_1_animate.focusin" dur="0.3s"end="menuItem_1_animate.focusout" fill="freeze"/>begin="menuItem_2_about.focusin" dur="0.3s"end="menuItem_2_about.focusout" fill="freeze"/> begin="menuItem_3_exit.focusin" dur="0.3s"end="menuItem_3_exit.focusout" fill="freeze"/>begin="menuItem_4_test.focusin" dur="0.3"end="menuItem_4_test.focusout" fill="freeze"/>
etc. with “values” element increasing every time by 30.
Here you have transformed, very simple menu –>
Anyone interested in JSR-226 know that there is a problem with SVGt if you want to use components like TextFields etc, as there is on support for these elements in the specs so far, at least I have never hear of it.
If you read this post you are probably looking for solution with custom J2ME GUI or you are one of my curious friends and probably you don’t understand much of this anyway, but if you are the first kind, and you know about any valuable tutorials, tools or simply anything JSR-226 related please post it in comments, any kind of collaboration would be appreciated!