Tuesday, May 28, 2013

Blackberry (Java) JSON tutorial

This post is about very basic level java implementation of Blackberry and json. I'm going to show how we can read json from URL and display in Blackberry. I'm going to use this URL to get the json response.

Quick demo


In Blackberry we cannot make a HTTP call in main thread, therefore we need to create separate thread to create the HTTP call.

1. First create a Blackberry application and name it as you want and also give a unique package name.

2. Then create a new class that extends Thread class. I named it as "ConnectJson". No matter you can use your own name.



Here is the code for ConnectJson class.

package com.jcode.json;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.ui.component.Dialog;

public class ConnectJson extends Thread {
 
 private String url;
 public String response;
 private String myinterface = ";interface=wifi";
 
  public void run() {
         HttpConnection conn = null;
         InputStream in = null;
         int code;
   
   try {
      conn = (HttpConnection) Connector.open(this.url + this.myinterface, Connector.READ);
         conn.setRequestMethod(HttpConnection.GET);
         code = conn.getResponseCode();

         if (code == HttpConnection.HTTP_OK) {
             in = conn.openInputStream();
             ByteArrayOutputStream out = new ByteArrayOutputStream();
             
             byte[] buffer = new byte[in.available()];
             int len = 0;

             while (-1 != (len = in.read(buffer))) {
                 out.write(buffer);                   
             }

             out.flush();
             this.response = new String(out.toByteArray());
            
             if (out != null){
                 out.close();
             }
             if (in != null){
                 in.close();
             }
             if (conn != null){
                 conn.close();
             }
         }

     } catch (Exception e) {
        Dialog.inform(e.toString());
     }
}  

public String jsonResult(String url){
  this.url = url;
  this.start();
  this.run();
  return response;
 }
} 

3. In your screen class extend the JsonConnet class and call the jsonResult method passing the URL.
Here is the code for MyScreen class

package com.jcode.json;

import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;

/**
 * A class extending the MainScreen class, which provides default standard
 * behavior for BlackBerry GUI applications.
 */
public final class MyScreen extends MainScreen
{
    /**
     * Creates a new MyScreen object
     */
    public MyScreen()
    {        
        // Set the displayed title of the screen       
        setTitle("MyTitle");
        
        ConnectJson connectJson = new ConnectJson();
        connectJson.jsonResult("http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo");
        LabelField jsonResult = new LabelField(connectJson.response);
        add(jsonResult);
    }
}

This is the code of MyApp class no need to change anything there.

package com.jcode.json;

import net.rim.device.api.ui.UiApplication;

/**
 * This class extends the UiApplication class, providing a
 * graphical user interface.
 */
public class MyApp extends UiApplication
{
    /**
     * Entry point for application
     * @param args Command line arguments (not used)
     */ 
    public static void main(String[] args)
    {
        // Create a new instance of the application and make the currently
        // running thread the application's event dispatch thread.
        MyApp theApp = new MyApp();       
        theApp.enterEventDispatcher();
    }
    /**
     * Creates a new MyApp object
     */
    public MyApp()
    {        
        // Push a screen onto the UI stack for rendering.
        pushScreen(new MyScreen());
    }    
}

Finally run your application on real device or on the simulator. If you are planning to use simulator to test this on simulator you need to tun on wifi of the simulator (see this).

Thank you!
Happy coding! :)

Monday, May 27, 2013

How to change the background color of Android activity

Here I'm going to show the way to change the background color of the Android activity.



In order to change the activity's background color we need to do two changes.
First we need to add color property to strings.xml. Open the strings.xml in res >> values directory


Then create color property and add the value for color as shown below. (Color codes)

#000000

Now your strings.xml should like this.


    BgColor
    Settings
    Hello world!
    #000000

After changing strings.xml file we need to add android:background property to the activity layout xml file.
First open the activity_main.xml in the res >> layout directory.

Then add this line in to your layout xml
android:background="@color/black"
Here is the complete code for activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@color/black"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
</RelativeLayout>

Resources:
 http://developer.android.com/guide/topics/resources/more-resources.html#Color

That's it, :)
Happy coding!
Your ideas are always welcome!!!