ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Details About Methods or Functions Used in Mobile Twitter Search Application

Updated on December 23, 2011


In this j2me tutorial, I'll explain all those methods that were used in "Simple Mobile twitter Search Application" created by us in our last tutorial. Well, Some sections of code is already explained in our previous tutorial, so, I'll try excluding them in order to avoid confusions. Here, below is the list of methods (sorted from top to bottom) that were used in our j2me class (i.e. MIDlet) of our twitter application.

Publisher Comments

This is the fourth tutorial of "Simple Mobile Application Development in Java ME or J2ME" tutorial series that are being published by me. You can go here to read first tutorial of this series.

List of Methods Used in Mobile APP

1) Required at Minimum and Most Useful Methods of every j2me Application

  1. "HelloMIDlet()" - Constructor of our j2me Class i.e of "HelloMIDlet".
  2. "startApp()" - Most important function/method of every mobile application developed with j2me which initialize the execution of application.
  3. "pauseApp()" - Another important function/method of application, which gets executed when application goes in "PAUSE" state (The state in which application is running but user is busy in some other tasks in his/her mobile).

  4. "destroyApp(boolean unconditional)" - The third most important function of every j2me application, which gets executed when user exits application.

  5. "commandAction(Command c, Displayable s)" - The last most important function/method of every j2me application, which will handle commands generated by any j2me component (such as forms, lists etc.) on user interaction. In simple words, when User will click on commands such as "Exit", "Ok" etc. which are displayed at the bottom of mobile screen, then, Those commands will be handled by this method.

2) Custom Methods or Functions Created by Us in Order to Develop twitter APP

  1. "showTweets(String SearchKeyword)" - This method will parse and show tweets on screen that were fetched from twitter (i.e. from internet) via "getDATAhttp" method.
  2. "getDATAhttp(String keyword, String querydata)" - This method connects to internet and fetch data from there via "GET" method of HTTP.

Methods and functions to develop mobile twitter search app
Methods and functions to develop mobile twitter search app

HelloMIDlet() Method of our Class

In this Method of our j2me MIDlet or Class, We are assigning values to variables which are declared in global scope i.e. above current method. Here, below is the the part of our application code to understand this better.

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);

startApp() Method of our Class

This is the default method that will be invoked first when we start our application in any supported device. Here, we are are creating a search form with one "input" field that will accept "search term" from user who is using our application. Variables of this search form has already been declared in global scope to make it available for other methods of our class too. Then, we are assigning commands to this form which will get triggered by user after typing search "Keyword". Then, we are setting "CommandListner" value to "this" to tell system that our commands will be handled by default method ("commandAction()") exists our current class. After that, we are displaying form on screen by this "display.setCurrent(searchFORM)" statement.

    public void startApp() {
        //SEARCH FORM: Here we are creating our Search Form
        //SEARCH FORM: Search form creation ends here

commandAction() Method of our J2ME class

"pauseApp()" and "destroyApp()" methods of our j2me MIDlet or class are not of much importance in our application, so, we'll skip them (But don't remove them from our Class) and come directly to "commandAction()" method.

"commandAction()" method of our J2ME Midlet is default method for handling commands invoked by components of j2me. Here, we are using if-else loops to handle different types of commands.

In this Method,

  1. First condition will check if command generated is "exitCommand". If yes, then code inside this condition will do the work of exiting application.
  2. Second Condition will check if command generated is "searchCMD". if yes, then code inside this condition will fetch the search keyword from input field of search form and then, it'll pass it to "showTweets()" method to execute next task.
  3. Third condition will check for "Back" command. If yes, then it will display the search form back on screen via running the code inside this condition.

Here, below is the code of this method for reference purposes.

    public void commandAction(Command c, Displayable s) {
        if (c == exitCommand) {
        } else if (c == searchCMD){
            //SEARCH FORM: code below will handle data of SEARCH form
            String SearchKeyword = inputFIELD.getString();
            //SEARCH FORM: data handling code ends here
        } else if (c == Back){

showTweets() method of our J2ME Midlet or Class

This is a custom methode created by us in order to display tweets on screen after fetch it from relative method in our J2ME class. First of all, see the code of this function and it's code has been explained below.

    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);
        } catch (JSONException ex) {
        } catch (IOException ex) {
  1. First, we are declaring an String type of Array that will store our tweets with name "tweets".
  2. Second, We are declaring a list with name "tweetsList" that will used for displaying our tweets on screen.
  3. Then, We are writing all our code inside "Try-Catch" block to handle connection errors, so, that our application will perform smoothly in case of such errors.
  4. Inside try-catch block, we are declaring another variable of "String" data type to store data fetched from internet via "getDATAhttp()" method of our application MIDlet. In this method, first parameter is search keyword and second parameter is optional query string that will be appended to twitter URL along with search keyword.
  5. The data, we'll fetch from internet from internet will be in JSON format. So, to parse it, we did download a file as shown in our parent tutorial here. The next two statements in "showTweets()" methods are using that file. First, we are declaring a new object with name "jsonobj" (j2me is Case-Sensitive) of "JSONObject" type, simultaneously, assigning it a value. Then, we are filtering the web data and storing the results in new variable named as "resultsj" of "JSONArray" data type.
  6. After that, We are running "for loop" to store tweets in array variable named as "tweets" that has been declared in the top section of current method, simultaneously, appending it list "tweetsList".
  7. Then, we are adding commands to "tweetsList" and setting default method to handle commands by using "this" as value of "CommandListener".
  8. And Finally, We are displaying it on screen via "display.setCurrent(tweetsList)" statement of J2ME.

getDATAhttp() Method of our Application MIDlet/Class

This method acts as a bridge for our application for making HTTP connections inside our application, whose code is shown below. I called this as bridge because there is no guarantee of Connection "Success" and "Failure" as similar to that of real world objects (Real Bridges). Either connection will take place "smoothly" or "hardly" (with trial and errors) or "not at all" depends on health of ISP network in surroundings.

This methods accepts two parameters, first is search "keyword" and second is "querydata" (Which will be appended to URL before connecting).

  1. First, we are encoding the keyword to replace special characters with relative codes to make it send them in URL. J2ME doesn't have any such function which fulfills the task of URL encoding, So, I did downloaded a file which will help ours in doing this, whose code is shown here in our parent tutorial.
  2. Then, we are declaring a variable "url" of "String" data type, Simultaneously, assigning it a value containing both our method parameters.
  3. Then, we are declaring three different variable of respective data type. Here, "InputStream" is used to define variable for handling data stream coming from external sources, "OutputStream" is used to define variables for sending data stream from application to external sources and "StringBuffer" is used to define variable that will be able to store data in bits.
  4. Then, We are using "Try-Finally" block of j2me to start and close connection with specified URL. First, J2me will run the code of "Try" block and then, it'll try closing connections with code inside "Finally" block.
  5. Inside "Try" block, In first statement, we are opening the connection with specified URL.
  6. Then, We are adding headers that will be sent along with connection, which will be used by website of twitter in detecting connection type and to behave as accordingly.
  7. Then, we are storing the "HTTP Connection" response code in variable named as "respCode" of "int" data type.
  8. Then, we are checking the response code via "if" condition to check whether connection was successful or not. If connection was successful (default value of response code generated after successful connection is 200) which is matched by value of this "httpConn.HTTP_OK", then, we are assigning value of both types of data stream to predefined variables. After that, we are declaring a variable named as "chr" which will be used for reading every bit of input stream and appending it to "sb" (StringBuffer). If connection was not successful, then, code inside else block will get executed.
  9. And Finally, at the end of this method, we are returning the retrieved data using the "return" keyword of j2me.

    public String getDATAhttp(String keyword, String querydata) throws IOException {
        keyword = URLEncoder.encode(keyword,"UTF-8");
        HttpConnection httpConn = null;
        String url = "" + keyword + querydata;
        InputStream is = null;
        OutputStream os = null;
        StringBuffer sb = new StringBuffer();
        try {
            // Open an HTTP Connection object
            httpConn = (HttpConnection);
            // Setup HTTP Request
            // This function retrieves the information of this connection
            /** 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 = != -1) {
                    sb.append((char) chr);
                // 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) {
            if (os != null) {
            if (httpConn != null) {
        return sb.toString();

And that's all which you need to know about methods used in our simple mobile twitter search application.


    0 of 8192 characters used
    Post Comment

    • profile image

      PARVEEN SAINI 5 years ago

      can you explain what is the roll of "results" in getJSonArray("results");

    • profile image

      guest 4 years ago

      much technical

    Click to Rate This Article