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


      6 years ago

      much technical

    • profile image


      6 years ago

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


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, 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:

    Show Details
    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 or domains, for performance and efficiency reasons. (Privacy Policy)
    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)
    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.
    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)