- HubPages»
- Technology»
- Computers & Software»
- Computer Science & Programming»
- Programming Languages
Developing, Creating Or Building Simple Mobile twitter Application to Search tweets
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.
- Go To "File" in Menu bar at top-left corner in you j2me IDE (Integrated Development Enviroment).
- Then, Click on "New Project", A new window will open.
- 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.
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)
- First, I'll call functions as Methods because it is more popular notation (May be a standard too) in object oriented programming.
- 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.