Solved

Call 2nd program in j2me

Posted on 2008-06-10
8
822 Views
Last Modified: 2013-11-24
Hello Sir,

I am new to J2me,

Suppose there are 2 classes

Class1 and Class2.

Now i want to call class2 from class one. How it can be done.

in timer Run method i am trying to call the 2nd class. (ImageDemoCanvas) but problem is that it is not running.

I want to stop the parnet class as it show splash screen, after time control expire i want to remove splash and call actual program.




Thanks

Regards

Regards

import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

import java.util.Vector;

import java.io.IOException;

import java.io.DataInputStream;

import javax.microedition.io.HttpConnection;

import javax.microedition.io.ContentConnection;

import javax.microedition.io.Connector;

import java.util.*;
 
 

public class TimerTemplate extends MIDlet implements CommandListener

{

  private Display display;      // Our display

  private Form fmMain;         // Main form

  private Command cmExit;      // Exit midlet

  private Command cmStop;      // Stop the timer

  private Timer tm;          // Timer

  private TestTimerTask tt;       // Task

  private int count = 0;        // How many times has task run
 

  public TimerTemplate()

  {

    display = Display.getDisplay(this);
 

    // Create main form

    fmMain = new Form("Timer Test");

    fmMain.append("waiting...\n");
 

    // Create commands and add to form

    cmExit = new Command("Exit", Command.EXIT, 1);

    cmStop= new Command("Stop", Command.STOP, 2);

    fmMain.addCommand(cmExit);

    fmMain.addCommand(cmStop);

    fmMain.setCommandListener(this);

    

    //------------------------------------------------------

    // Option #1 - One time task with delayed start

    // Create a timer that will go off in 5 seconds

    //------------------------------------------------------

    tm = new Timer();

    tt = new TestTimerTask();

    tm.schedule(tt,5000);    
 

    //------------------------------------------------------

    // Option #2 - Fixed-delay repeating task with delayed start

    // Create a timer that will go off in 5 seconds

    // Repeating every 3 seconds

    //------------------------------------------------------

//    tm = new Timer();

//    tt = new TestTimerTask();

//    tm.schedule(tt,5000, 3000);    
 

    //------------------------------------------------------

    // Option #3 - Fixed-rate repeating task with delayed start

    // Create a timer that will go off in 5 seconds

    // Repeating every 3 seconds

    //------------------------------------------------------

//    timer = new Timer();

//    tt = new TestTimerTask();

//    timer.scheduleAtFixedRate(tt,5000, 3000);    
 

    //------------------------------------------------------

    // Option #4 - One time task at specified date

    // Create timer that starts at current date

    //------------------------------------------------------

//    timer = new Timer();

//    tt = new TestTimerTask();

//    timer.schedule(tt, new Date());    
 

    //------------------------------------------------------

    // Option #5 - Fixed-delay repeating task starting 

    //             at a specified date

    // Create timer that starts at current date

    // Repeating every 3 seconds

    //------------------------------------------------------

//    timer = new Timer();

//    tt = new TestTimerTask();

//    timer.schedule(tt, new Date(), 3000);    
 

    //------------------------------------------------------

    // Option #6 - Fixed-rate repeating task starting

    //             at a specified date

    // Create timer that starts at current date

    // Repeating every 3 seconds

    //------------------------------------------------------

//    timer = new Timer();

//    tt = new TestTimerTask();

//    timer.scheduleAtFixedRate(tt, new Date(), 3000);    

  }
 

  /*--------------------------------------------------

  * Show the main Form

  *-------------------------------------------------*/

  public void startApp ()

  {

    display.setCurrent(fmMain);

  }
 

  /*--------------------------------------------------

  * Shutting down. Cleanup all we created

  *-------------------------------------------------*/

  public void destroyApp (boolean unconditional)

  {

  }
 

  /*--------------------------------------------------

  * No pause code necessary

  *-------------------------------------------------*/

  public void pauseApp ()

  { }
 

  /*--------------------------------------------------

  * Process events for the main form

  *-------------------------------------------------*/

  public void commandAction(Command c, Displayable d)

  {

    if (c == cmStop)

    {

      tm.cancel();

    }

    else if (c == cmExit)

    {

      destroyApp(false);

      notifyDestroyed();

    }

  }
 

  /*--------------------------------------------------

  * TestTimerTask Class - Run the task

  *-------------------------------------------------*/  

  private class TestTimerTask extends TimerTask

  {

    public final void run()

    {

      fmMain.append("run count: " + ++count + "\n");

      ImageDemoCanvas im= new ImageDemoCanvas();

      im.run();

    }

  }

}
 
 

---------------
 

class ImageDemoCanvas extends MIDlet implements Runnable

{

   private Display display;

   private Thread thread;

   private Thread thread1;

   private Frame frame;

   Timer      timer = new Timer();
 

   public ImageDemoCanvas() {  

   display = Display.getDisplay(this);

      frame = new Frame();
 

      Thread thread = new Thread(this);

      thread.start();

      Thread thread1 = new Thread(this);

      thread1.start();

   }
 

   protected void startApp() {

//      display = Display.getDisplay(this);

//      frame = new Frame();

//

//      Thread thread = new Thread(this);

//      thread.start();

//      Thread thread1 = new Thread(this);

//      thread1.start();

   }
 

   protected void pauseApp() {

   }
 

   protected void destroyApp(boolean unconditional) {

   }
 

   private Image createImage(String name) throws IOException {
 

       HttpConnection c = null;

       DataInputStream is = null;

           

       try {

          c = (HttpConnection)Connector.open(name);

          int status = c.getResponseCode();

       

          if (status != 200) {

             throw new IOException("HTTP Response Code = " + status);

          }
 

          int len = (int)c.getLength();

          String type = c.getType();
 

          if (len > 0) {

             is = c.openDataInputStream();

             byte[] data = new byte[len];

             is.readFully(data);

             return Image.createImage(data, 0, len);

          } else {

             throw new IOException("Content length is missing");

          }
 

       } finally {

          if (is != null)

             is.close();
 

          if (c != null)

             c.close();

       }
 

   }
 
 

   public void run() {

      Image theimage = null;
 

      String name = "http://127.0.0.1:11001/image.jpg";  

     

      while(true) {

        try {

           //theimage = createImage(name);

          theimage = Image.createImage ("/logo.png");

        } catch (IOException e) {

          e.printStackTrace();

        }
 

        frame.setImages(theimage);

        display.setCurrent(frame);
 

      }

   }

}
 

class Frame extends Canvas {
 

    private Image image;

    private Thread tr;

    

    int i;

    Frame() {

       image = Image.createImage(getWidth(), getHeight());    

    }
 

    void setImages(Image theimage) {

       image = theimage;  

           i=1;
 

       repaint();

       serviceRepaints(); 

    }
 

    protected void paint(Graphics g) {

       g.drawImage(image, 10, 50, Graphics.LEFT|Graphics.TOP);

       g.drawString("vikas",100,50,Graphics.BOTTOM|Graphics.HCENTER);

       

       //for(i=1;i<1000;i++)

    	    //g.fillRect(0,0,i,50);

		    

	 

       

    }

   

}

Open in new window

0
Comment
Question by:vikas_maderna
  • 3
  • 3
8 Comments
 
LVL 13

Accepted Solution

by:
MicheleMarcon earned 500 total points
ID: 21757234
You can't start 2 MIDlet in one application...

You need to merge the code in one MIDlet:

-unify initialization code.
-call method directly (do not make assumption as to ImageDemoCanvas.startApp(), pauseApp() etc)

And of course, class ImageDemoCanvas must not extend MIDlet
0
 

Author Comment

by:vikas_maderna
ID: 21757427
Hello Sir,

This is complied code


import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.Vector;
import java.io.IOException;
import java.io.DataInputStream;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.ContentConnection;
import javax.microedition.io.Connector;
import java.util.*;

public class ImageDemoCanvas extends MIDlet implements CommandListener, Runnable
{
   private Display display;
   private Thread thread;
   private Thread thread1;
   private Frame frame;

   private Timer tm;          // Timer
   private TestTimerTask tt;       // Task
   private int Run2Start;
   private Command mExitCommand, mFindCommand, mCancelCommand,mNextCommand,mPrevCommand;
      
  private List mList;
  private TextBox mSubmitBox;
  private Form mProgressForm;
  private StringItem mProgressString;


   public ImageDemoCanvas() {
   
         String[] stringElements = { "English", "Hausa", "French" };
      mList = new List("Language Selection", List.IMPLICIT,stringElements,null);


      mNextCommand = new Command("Next", Command.SCREEN, 0);      
    mExitCommand = new Command("Exit", Command.EXIT, 0);
    mFindCommand = new Command("Find", Command.SCREEN, 0);
      mPrevCommand = new Command("Previous", Command.EXIT,1);      
      
      mList.addCommand(mNextCommand);
      mList.addCommand(mExitCommand);
      
    mSubmitBox = new TextBox("Enter the word", "", 32, 0);
    mSubmitBox.addCommand(mPrevCommand);
    mSubmitBox.addCommand(mFindCommand);
 
      mList.setCommandListener(this);
      mSubmitBox.setCommandListener(this);
   
    mProgressForm = new Form("Lookup progress");
    mProgressString = new StringItem(null, null);
    mProgressForm.append(mProgressString);
      Run2Start=0;
   
   }

   protected void startApp() {
      display = Display.getDisplay(this);
      frame = new Frame();

      Thread thread = new Thread(this);
      thread.start();
      Thread thread1 = new Thread(this);
      thread1.start();
      tm = new Timer();
    tt = new TestTimerTask();
    tm.schedule(tt,5000);    
      
   }

   protected void pauseApp() {
   }

   protected void destroyApp(boolean unconditional) {
   }

   private Image createImage(String name) throws IOException {

       HttpConnection c = null;
       DataInputStream is = null;
           
       try {
          c = (HttpConnection)Connector.open(name);
          int status = c.getResponseCode();
       
          if (status != 200) {
             throw new IOException("HTTP Response Code = " + status);
          }

          int len = (int)c.getLength();
          String type = c.getType();

          if (len > 0) {
             is = c.openDataInputStream();
             byte[] data = new byte[len];
             is.readFully(data);
             return Image.createImage(data, 0, len);
          } else {
             throw new IOException("Content length is missing");
          }

       } finally {
          if (is != null)
             is.close();

          if (c != null)
             c.close();
       }

   }

private void dismiss(){
        tm.cancel();
        System.out.println("Cancel");
        //display.setCurrent( next );
    }

 public void commandAction(Command c, Displayable s) {
        System.out.println(c.getLabel());
    if (c == mExitCommand) {
      destroyApp(false);
      notifyDestroyed();
    }
    else if(c==mNextCommand)
    {
          //Show the Next Form
            int index = mList.getSelectedIndex();
          
            display.setCurrent(mSubmitBox);
            mSubmitBox.setTitle("Enter the word in " + mList.getString(index));          
    }
    else if(c==mPrevCommand)
    {
          display.setCurrent(mList);      
    }
   
    else if (c == mFindCommand) {
      // Show the progress form.
      display.setCurrent(mProgressForm);
      // Kick off the thread to do the query.
      Thread t = new Thread(this);
      t.start();
    }
  }
 private String lookUp(String word) throws IOException
  {
        
              String definition="";
              
              word = word.toLowerCase();
            String Result="The apple is the pomaceous fruit of the apple tree, species Malus domestica in the rose family Rosaceae";      
            mProgressString.setText("Searching...");
            if(word.trim().compareTo("apple")==0)
            {
                  definition = Result;
            }
            else
            {
                  definition = "No match Found!! If you want we can Search the Results on Internet";
                  System.out.println(word);
            }

          return definition;
              
                      
       }

   public void run()
   {
         
         Image theimage = null;

  System.out.println("Run2Start = " + Run2Start);
     
     if (Run2Start==0)
     {
     
     
      String name = "http://127.0.0.1:11001/image.jpg";  
     
      while(true)
      {
     
        try
        {
           //theimage = createImage(name);
          theimage = Image.createImage ("/logo.png");
        frame.setImages(theimage,Run2Start);

        } catch (IOException e)
        {
          e.printStackTrace();
        }

        display.setCurrent(frame);
        System.out.println("Run2Start = " + Run2Start);
            
       }
       
       }
        else
        {
            
             String word = mSubmitBox.getString();
    String definition;

    try { definition = lookUp(word); }
    catch (IOException ioe) {
      Alert report = new Alert(
          "Sorry",
          "Something went wrong and that " +
          "definition could not be retrieved.",
          null, null);
      report.setTimeout(Alert.FOREVER);
      display.setCurrent(report, mSubmitBox);
      return;
    }
    Alert results = new Alert("Definition", definition,
        null, null);
    results.setTimeout(Alert.FOREVER);
    display.setCurrent(results, mSubmitBox);

                        
        }
       
            
      }
   
   
   private class TestTimerTask extends TimerTask
  {
    public final void run()
    {
     
     // frame = null;
      Run2Start=1;
            dismiss();
      
//   tm.cancel();
 //  tt.cancel();
  System.out.println("hi");
                    display.setCurrent(mList);
  frame=null;
    }
  }

 }
 


class Frame extends Canvas
 {

    private Image image;
    private Thread tr;
   
    int i;
    Frame() {
       image = Image.createImage(getWidth(), getHeight());    
    }

    void setImages(Image theimage,int show)
     {
       System.out.println("show = " + show);
       if (show==0)
       {
             
       image = theimage;
       repaint();
       serviceRepaints();
     
             }
       else
       {
       
       return;
       //image = null;
       
       }  
           
            
    }

    protected void paint(Graphics g) {
       g.drawImage(image, 10, 50, Graphics.LEFT|Graphics.TOP);
     //  g.drawString("vikas",100,50,Graphics.BOTTOM|Graphics.HCENTER);
       
       //for(i=1;i<1000;i++)
              //g.fillRect(0,0,i,50);
               
      
       
    }
   
}


Now in this i have the following error

Uncaught exception java/lang/NullPointerException.

This error i think is coming due to this statment in timer Run function
  frame=null;

Actually once the splash image is loaded, and timer is expired i want to remove the frame and run the 2nd program but it is not happening and it is calling again and again the pain method. so i set the frame=null so that it dont call.

Please suggest me how to do, as i dont want to load the splash screen again and again. Also how can i stop the paint method calling.

thanks




0
 

Author Comment

by:vikas_maderna
ID: 21757831
Hello Sir,

I have modified the program.

Now i am not able to start the timer, can you please help me

import java.io.*;

import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.lang.*;
import java.util.*;

public class MobileDemo extends MIDlet
  implements CommandListener, Runnable {
        
  Form mForm;      
  private Display mDisplay;

  private Command mExitCommand, mFindCommand, mCancelCommand,mNextCommand,mPrevCommand;
      
  private List mList;
  private TextBox mSubmitBox;
  private Form mProgressForm;
  private StringItem mProgressString;
 // private Timer tm;          // Timer
  private TestTimerTask tt;       // Task
  Timer      timer = new Timer();
  public MobileDemo() {
 
       String[] stringElements = { "English", "Hausa", "French" };
      mList = new List("Language Selection", List.IMPLICIT,stringElements,null);


      mNextCommand = new Command("Next", Command.SCREEN, 0);      
    mExitCommand = new Command("Exit", Command.EXIT, 0);
    mFindCommand = new Command("Find", Command.SCREEN, 0);
      mPrevCommand = new Command("Previous", Command.EXIT,1);      
      
      mList.addCommand(mNextCommand);
      mList.addCommand(mExitCommand);
      
    mSubmitBox = new TextBox("Enter the word", "", 32, 0);
    mSubmitBox.addCommand(mPrevCommand);
    mSubmitBox.addCommand(mFindCommand);
 
      mList.setCommandListener(this);
      mSubmitBox.setCommandListener(this);
   
    mProgressForm = new Form("Lookup progress");
    mProgressString = new StringItem(null, null);
    mProgressForm.append(mProgressString);
           

  }

  public void startApp() {
      mForm = new Form("");
    mDisplay = Display.getDisplay(this);
      timer = new Timer();
    tt = new TestTimerTask();
    timer.schedule(tt,5000);
      try

      {

            Image im = Image.createImage("/image_bw.png");
            mForm.append(new ImageItem(null, im, ImageItem.LAYOUT_CENTER , null));
            mDisplay.setCurrent(mForm);

      }
      catch (java.io.IOException e)
      {
            System.err.println("Unable to locate or read .png file");
      }
      
    //mDisplay.setCurrent(mList);
  }

  public void pauseApp() {}

  public void destroyApp(boolean unconditional) {}

  public void commandAction(Command c, Displayable s) {
        System.out.println(c.getLabel());
    if (c == mExitCommand) {
      destroyApp(false);
      notifyDestroyed();
    }
    else if(c==mNextCommand)
    {
          //Show the Next Form
            int index = mList.getSelectedIndex();
          
            mDisplay.setCurrent(mSubmitBox);
            mSubmitBox.setTitle("Enter the word in " + mList.getString(index));          
    }
    else if(c==mPrevCommand)
    {
          mDisplay.setCurrent(mList);      
    }
   
    else if (c == mFindCommand) {
      // Show the progress form.
      mDisplay.setCurrent(mProgressForm);
      // Kick off the thread to do the query.
      Thread t = new Thread(this);
      t.start();
    }
  }

  public void run() {
        System.out.println("hi");
    String word = mSubmitBox.getString();
    String definition;

    try { definition = lookUp(word); }
    catch (IOException ioe) {
      Alert report = new Alert(
          "Sorry",
          "Something went wrong and that " +
          "definition could not be retrieved.",
          null, null);
      report.setTimeout(Alert.FOREVER);
      mDisplay.setCurrent(report, mSubmitBox);
      return;
    }
    Alert results = new Alert("Definition", definition,
        null, null);
    results.setTimeout(Alert.FOREVER);
    mDisplay.setCurrent(results, mSubmitBox);
  }

 private class TestTimerTask extends TimerTask
  {
    public final void run()
    {
     // fmMain.append("run count: " + ++count + "\n");
      //ImageDemoCanvas im= new ImageDemoCanvas();
      //im.run();
      System.out.println("In Timer");
      mDisplay.setCurrent(mList);
      tm.cancel();
      
    }
  }

  private String lookUp(String word) throws IOException
  {
        
              String definition="";
              
              word = word.toLowerCase();
            String Result="The apple is the pomaceous fruit of the apple tree, species Malus domestica in the rose family Rosaceae";      
            mProgressString.setText("Searching...");
            if(word.trim().compareTo("apple")==0)
            {
                  definition = Result;
            }
            else
            {
                  definition = "No match Found";
                  System.out.println(word);
            }

          return definition;
              
                      
       }
}

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 13

Expert Comment

by:MicheleMarcon
ID: 21758434
display.setCurrent(//your display here
0
 

Author Comment

by:vikas_maderna
ID: 21758718
Hello Michele,

I didnt understand, Could you please explain in more detail.


Regards


Vikas
0
 
LVL 13

Expert Comment

by:MicheleMarcon
ID: 21760144
If you change your current display, then the paint() method will not be called any more.

You display a different Display (you have one, haven't you?) ;)
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This paper addresses the security of Sennheiser DECT Contact Center and Office (CC&O) headsets. It describes the DECT security chain comprised of “Pairing”, “Per Call Authentication” and “Encryption”, which are all part of the standard DECT protocol.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn how to connect to a wireless network using the network security key. They will also learn how to access the IP address and DNS server for connections that must be done manually. After setting up a router, find the network security…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now