ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Developing, Creating Or Building Simple Mobile twitter Application to Search tweets

Updated on December 13, 2011

Publisher Comments

This J2ME Tutorial is a part of tutorial series on topic "Simple Mobile Application Development in Java ME" that are being published by Me and this holds the 3rd position in it. if you are really new in developing applications for mobile platform, then, You can go here to read my first tutorial of this series,

Introduction

In this tutorial, I'll help you developing your first twitter mobile application in Java ME (Programming Language for developing mobile apps) i.e. j2me. It is very easy to develop a simple twitter app for web (websites) but when we think about developing it for mobile platform, Minds of some programmers stops responding due to either lack of knowledge or having no knowledge at all. But don't worry, if you're really new and have no experience in this field, then, you can read my last two tutorial (listed below) to get started. This j2me tutorial is part (3rd one) of that article series.

Steps to Start Developing Mobile Twitter APP

Well, I already published steps required to create new project in Java ME SDK 3.0 in my first tutorial but I'll publish it again here to save your time.

  1. Go To "File" in Menu bar at top-left corner in you j2me IDE (Integrated Development Enviroment).
  2. Then, Click on "New Project", A new window will open.
  3. Then, proceed in this way Next -> Type "simpletwitterapp" in field labeled as "Project Name" and then click "Next" -> Finish. A new project will be created that will appear in projects section in left side of Java ME IDE, as shown in screenshot below.

Create-Develop-Build Mobile-Cellphone twitter apps
Create-Develop-Build Mobile-Cellphone twitter apps
Snapshot of our "simple twitter app" project
Snapshot of our "simple twitter app" project

Step 1 - Handling Network Connections

First of All, paste the code show below in our "helloMIDlet.java" file, just before last closing curly bracket. This Code will help us in connecting and retrieving content from internet i.e. from of twitter.com website. I'll explain this code to you later. After adding this code at appropriate place, then you need to import some core j2me classes in our project as shown below first code snippet.

Method/ Function that will help us in Connecting to internet

    public String getDATAhttp(String keyword, String querydata) throws IOException {
        keyword = URLEncoder.encode(keyword,"UTF-8");
        HttpConnection httpConn = null;
        String url = "http://search.twitter.com/search.json?q=" + keyword + querydata;

        InputStream is = null;
        OutputStream os = null;
        StringBuffer sb = new StringBuffer();

        try {
            // Open an HTTP Connection object
            httpConn = (HttpConnection) Connector.open(url);

            // Setup HTTP Request
            httpConn.setRequestMethod(HttpConnection.GET);
            httpConn.setRequestProperty("User-Agent",
                    "Mozilla/4.0");


            // This function retrieves the information of this connection
            //sb.append(getConnectionInformation(httpConn));

            /** Initiate connection and check for the response code. If the
            response code is HTTP_OK then get the content from the target
             **/
            int respCode = httpConn.getResponseCode();
            if (respCode == httpConn.HTTP_OK) {
                os = httpConn.openOutputStream();
                is = httpConn.openDataInputStream();
                int chr;	//int total = 0;
                //int lengthOfFile = is.available();
                while ((chr = is.read()) != -1) {
                    sb.append((char) chr);
                    //loading(lengthOfFile,total);//(int)((total*100)/lengthOfFile));
                }
                // Web Server just returns the birthday in mm/dd/yy format.
                //System.out.println(name+"'s Birthday is " + sb.toString());
            } else {
                //System.out.println("Error in opening HTTP Connection. Error#" + respCode);
                sb.append("Error in opening HTTP Connection. Error#" + respCode);
            }

        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
            if (httpConn != null) {
                httpConn.close();
            }
        }
        //ld.notify();
        return sb.toString();
    }

Libraries that needs to be imported after above code

package hello;

//Here, below is the code that will import core j2me libraries
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
//importing new libraries ends here

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

After finishing above work, "Go to Projects -> "simpletwitterapp" -> Source Packages -> hello". Right click on "hello", then, create new java class. A new window will appear on screen, then, replace the class name with this one "URLEncoder" and click on "finish" button. Now, Copy the code show below in that file by replacing the automatically created j2me code in it. This code will help us in encoding text that will sent in URL as query string.

Java ME Code of URLEncoder File

package hello;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class URLEncoder {

    public static String encode(String s, String enc) throws IOException {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DataOutputStream dOut = new DataOutputStream(bOut);
        StringBuffer ret = new StringBuffer(); //return value
        dOut.writeUTF(s);
        ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
        bIn.read();
        bIn.read();
        int c = bIn.read();
        while (c >= 0) {
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '*' || c == '_') {
                ret.append((char) c);
            } else if (c == ' ') {
                ret.append('+');
            } else {
                if (c < 128) {
                    appendHex(c, ret);
                } else if (c < 224) {
                    appendHex(c, ret);
                    appendHex(bIn.read(), ret);
                } else if (c < 240) {
                    appendHex(c, ret);
                    appendHex(bIn.read(), ret);
                    appendHex(bIn.read(), ret);
                }
            }
            c = bIn.read();
        }
        return ret.toString();
    }

    private static void appendHex(int arg0, StringBuffer buff) {
        buff.append('%');
        if (arg0 < 16) {
            buff.append('0');
        }
        buff.append(Integer.toHexString(arg0));
    }
}

Step 2 - Converting default code of startApp function into comment

Now, Go to function named as "startApp()" and covert all the code inside it into comment like shown below by either using "/* */" or "//".

    public void startApp() {

        /*
	TextBox t = new TextBox("Hello", "Hello, World!", 256, 0);

        t.addCommand(exitCommand);
        t.setCommandListener(this);

        display.setCurrent(t);
	*/
    }

Step 3 : Creating Form to Request Search Keyword

Here, we'll create a form (Can be concluded as Search form) that will be displayed on screen at very first to request search keyword (for which search is to be performed) from User of application.

Declaring Variables and Assigning Values to Create our Search Form

First of all, we need to define variables and assign values to them that will be used in creating our form, after that we will create our form in "startApp()" function as shown in j2me code below. You can copy~paste this segments of code at appropriate places in you own "helloMIDlet" file of application. Code is commented out, so you can see changes easily.

    private Command exitCommand; // The exit command
    private Display display;     // The display for this MIDlet

    //SEARCH FORM: Search Form Variable Declaration Starts Here
    private Form searchFORM;
    private TextField inputFIELD;
    private Command searchCMD;
    //SEARCH FORM: Search Form Variable Declaration Ends Here

    public HelloMIDlet() {
        display = Display.getDisplay(this);
        exitCommand = new Command("Exit", Command.EXIT, 0);

        //SEARCH FORM: Assigning Values of Search Form Varibles starts here
        searchFORM = new Form("Type you Username Below");
        inputFIELD = new TextField("Search Keyword: ", null, 50, TextField.ANY);
        searchCMD = new Command("Start Search", Command.OK, 1);
        //SEARCH FORM: Assigning Values of Search Form Varibles ends here
    }

    public void startApp() {

        //SEARCH FORM: Here we are creating our Search Form
        searchFORM.append(inputFIELD);
        searchFORM.addCommand(exitCommand);
        searchFORM.addCommand(searchCMD);
        searchFORM.setCommandListener(this);
        display.setCurrent(searchFORM);
        //SEARCH FORM: Search form creation ends here

        /*
        TextBox t = new TextBox("Hello", "Hello, World!", 256, 0);

        t.addCommand(exitCommand);
        t.setCommandListener(this);

        display.setCurrent(t);
         */
    }

Step 4: Handling Search Form Data and Input

Here, We'll write code that will handle data (input) of "Search Form". We'll write this code inside "commandAction()" method/function of our "helloMIDlet" class/file.

Important Notes

(Kindly Read this if you are new to OOP (Object Oriented Programming) and if possible in General programming too)

  1. First, I'll call functions as Methods because it is more popular notation (May be a standard too) in object oriented programming.
  2. Second, I'll call "helloMIDlet class" instead of "helloMidlet file" because it'll be better to understand and it is our main class in which we are working.

To handle data submitted via "Search form", we will append (add) one more condition in if-else statement inside "commandAction" method but before that we will create one more method named as "showTweets" in our class that will going to be used in if-else statements of "commandAction" and here is the j2me code after changes.

Changes made in commandAction and creating showTweets Method

public void commandAction(Command c, Displayable s) {
        if (c == exitCommand) {
            destroyApp(false);
            notifyDestroyed();
        } else if (c == searchCMD){

            //SEARCH FORM: code below will handle data of SEARCH form
            String SearchKeyword = inputFIELD.getString();
            showTweets(SearchKeyword);
            //SEARCH FORM: data handling code ends here
        }
}

//Below is the method that will be used in if-else statements of "commandAction" Method
public void showTweets(String SearchKeyword){

}
//showTweets method ends here

Step 5: Adding or Writing j2me Code in "showTweets" Method to fetch and Display tweets on Screen

Now, we'll write code in our newly created method named as "showTweets" inside "helloMIDlet" class. This code will do task of fetching tweets from official twitter website and displaying them on screen as list. When our application will contact twitter via internet connection, Twiiter will send data to us in "json" format, So, we need a library to parse/handle it. It would be nice to create our own library but it is time consuming, complex and lengthy task and you'd not be able to understand it. Therefore, I found a precompiled library named as "JSON ME" for this task that can be downloaded from here.

After downloading, Go to "Projects->'simpletwitterapp'->Resources" and right click on it, then, click on "ADD Jar/Zip". After that, A new window will appear on screen. Inside that window, Go to location where your downloaded file exist, then, Add it to our project. After that, You need to import this file in our project as shown in code snippet below.

package hello;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

//This j2me statement/line will import our downloaded file
import org.json.me.*; 

Here, below is the j2me code of "showTweets" Method but before that, we need to define a command named as "Back" which will allow application users to go back on Search form. This command will be declared in the same section where search form variables have been declared (To make it available in global scope) and we will add one more condition in "commandAction" method to handle/process this "Back" command, as shown below.

Code Snippet Showing the Declaration of "Back" Command

    private Command exitCommand; // The exit command
    private Display display;     // The display for this MIDlet

    //SEARCH FORM: Search Form Variable Declaration Starts Here
    private Form searchFORM;
    private TextField inputFIELD;
    private Command searchCMD;
    //SEARCH FORM: Search Form Variable Declaration Ends Here

    //Declaring variable for "Back" command
    private Command Back;
    //tweets handling variables ends here


    public HelloMIDlet() {
        display = Display.getDisplay(this);
        exitCommand = new Command("Exit", Command.EXIT, 0);

        //SEARCH FORM: Assigning Values of Search Form Varibles starts here
        searchFORM = new Form("Type you Username Below");
        inputFIELD = new TextField("Search Keyword: ", null, 50, TextField.ANY);
        searchCMD = new Command("Start Search", Command.OK, 1);
        //SEARCH FORM: Assigning Values of Search Form Varibles ends here

        //assigning value to variable declared for "Back" Command
            Back = new Command("Back",Command.BACK,2);
    }

Adding One More if-else Condition in "commandAction" method to process "Back" Command

    public void commandAction(Command c, Displayable s) {
        if (c == exitCommand) {
            destroyApp(false);
            notifyDestroyed();
        } else if (c == searchCMD){

            //SEARCH FORM: code below will handle data of SEARCH form
            String SearchKeyword = inputFIELD.getString();
            showTweets(SearchKeyword);
            //SEARCH FORM: data handling code ends here
        } else if (c == Back){
            display.setCurrent(searchFORM);
        }
    }

Java ME (j2me) code of "showTweets" Method

    public void showTweets(String SearchKeyword){

        String[] tweets = new String[20];
        List tweetsList = new List("Latest Tweets 
Found",List.IMPLICIT);
        try {

	    /*Belowing we are retrieving and storing data 
	     *from twitter website in "twitterDATA" variable*/ 
            String twitterDATA = getDATAhttp(SearchKeyword, "&rpp=20&result_type=mixed");
            
//Downloaded file is used in two lines below to parse json data
            JSONObject jsonobj = new JSONObject(twitterDATA);
            JSONArray resultsj = jsonobj.getJSONArray("results");
//json parsing code ends here

            for (int i = 0; i < jsonobj.length(); i++) {
                tweets[i] = resultsj.getJSONObject(i).getString("text");
                tweetsList.append(tweets[i], null);
            }

            tweetsList.addCommand(exitCommand);
            tweetsList.addCommand(Back);
            tweetsList.setCommandListener(this);
            display.setCurrent(tweetsList);

        } catch (JSONException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

All-in-One Code of Our Mobile Twitter Search Application

package hello;

//Here, below is the code that will import core j2me libraries
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
//importing new libraries ends here

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

//This j2me statement/line will import our downloaded file
import org.json.me.*;

public class HelloMIDlet extends MIDlet implements CommandListener {

    private Command exitCommand; // The exit command
    private Display display;     // The display for this MIDlet

    //SEARCH FORM: Search Form Variable Declaration Starts Here
    private Form searchFORM;
    private TextField inputFIELD;
    private Command searchCMD;
    //SEARCH FORM: Search Form Variable Declaration Ends Here

    //Declaring variable for "Back" command
    private Command Back;
    //tweets handling variables ends here


    public HelloMIDlet() {
        display = Display.getDisplay(this);
        exitCommand = new Command("Exit", Command.EXIT, 0);

        //SEARCH FORM: Assigning Values of Search Form Varibles starts here
        searchFORM = new Form("Type you Username Below");
        inputFIELD = new TextField("Search Keyword: ", null, 50, TextField.ANY);
        searchCMD = new Command("Start Search", Command.OK, 1);
        //SEARCH FORM: Assigning Values of Search Form Varibles ends here

        //assigning value to variable declared for "Back" Command
            Back = new Command("Back",Command.BACK,2);
    }

    public void startApp() {

        //SEARCH FORM: Here we are creating our Search Form
        searchFORM.append(inputFIELD);
        searchFORM.addCommand(exitCommand);
        searchFORM.addCommand(searchCMD);
        searchFORM.setCommandListener(this);
        display.setCurrent(searchFORM);
        //SEARCH FORM: Search form creation ends here

        /*
        TextBox t = new TextBox("Hello", "Hello, World!", 256, 0);

        t.addCommand(exitCommand);
        t.setCommandListener(this);

        display.setCurrent(t);
         */
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable s) {
        if (c == exitCommand) {
            destroyApp(false);
            notifyDestroyed();
        } else if (c == searchCMD){

            //SEARCH FORM: code below will handle data of SEARCH form
            String SearchKeyword = inputFIELD.getString();
            showTweets(SearchKeyword);
            //SEARCH FORM: data handling code ends here
        } else if (c == Back){
            display.setCurrent(searchFORM);
        }
    }

    //Below is the method that will be used in if-else statements of "commandAction" Method
    public void showTweets(String SearchKeyword){
        String[] tweets = new String[20];
        List tweetsList = new List("Latest Tweets Found",List.IMPLICIT);
        try {

            String twitterDATA = getDATAhttp(SearchKeyword, "&rpp=20&result_type=mixed");
            
            JSONObject jsonobj = new JSONObject(twitterDATA);
            JSONArray resultsj = jsonobj.getJSONArray("results");

            for (int i = 0; i < jsonobj.length(); i++) {
                tweets[i] = resultsj.getJSONObject(i).getString("text");
                tweetsList.append(tweets[i], null);
            }

            tweetsList.addCommand(exitCommand);
            tweetsList.addCommand(Back);
            tweetsList.setCommandListener(this);
            display.setCurrent(tweetsList);

        } catch (JSONException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    //showTweets method ends here

    /*//handleTWdata starts: this function will parse data fetched from twitter website
    public String[] handleTWdata(String twitterDATA){
        String[] result = null;
        return result;
    }
    //handleTWdata ends here*/

    public String getDATAhttp(String keyword, String querydata) throws IOException {
        keyword = URLEncoder.encode(keyword,"UTF-8");
        HttpConnection httpConn = null;
        String url = "http://search.twitter.com/search.json?q=" + keyword + querydata;

        InputStream is = null;
        OutputStream os = null;
        StringBuffer sb = new StringBuffer();

        try {
            // Open an HTTP Connection object
            httpConn = (HttpConnection) Connector.open(url);

            // Setup HTTP Request
            httpConn.setRequestMethod(HttpConnection.GET);
            httpConn.setRequestProperty("User-Agent",
                    "Mozilla/4.0");


            // This function retrieves the information of this connection
            //sb.append(getConnectionInformation(httpConn));

            /** Initiate connection and check for the response code. If the
            response code is HTTP_OK then get the content from the target
             **/
            int respCode = httpConn.getResponseCode();
            if (respCode == httpConn.HTTP_OK) {
                os = httpConn.openOutputStream();
                is = httpConn.openDataInputStream();
                int chr;	//int total = 0;
                //int lengthOfFile = is.available();
                while ((chr = is.read()) != -1) {
                    sb.append((char) chr);
                    //loading(lengthOfFile,total);//(int)((total*100)/lengthOfFile));
                }
                // Web Server just returns the birthday in mm/dd/yy format.
                //System.out.println(name+"'s Birthday is " + sb.toString());
            } else {
                //System.out.println("Error in opening HTTP Connection. Error#" + respCode);
                sb.append("Error in opening HTTP Connection. Error#" + respCode);
            }

        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
            if (httpConn != null) {
                httpConn.close();
            }
        }
        //ld.notify();
        return sb.toString();
    }

}

And finally, Mobile twitter search application is ready, which will show the latest tweets that has been posted on twitter containing our search terms/keywords. If you need to learn more about methods or functions used in this tutorial, then, you should read my next tutorial (1401 words), where I tried to explain every line of code.

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)