?
Solved

Call 2nd program in j2me

Posted on 2008-06-10
8
Medium Priority
?
838 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
8 Comments
 
LVL 13

Accepted Solution

by:
MicheleMarcon earned 2000 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
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 
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

Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Tired of waiting for your show or movie to load?  Are buffering issues a constant problem with your internet connection?  Check this article out to see if these simple adjustments are the solution for you.
In this article we have discussed about the OS X EI Capitan and how to fix Wi-Fi issue in OS X El Capitan. We have explained how to delete system level preferences and create a new Wi-Fi location to resolve Wi-Fi issue.
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month15 days, 3 hours left to enroll

771 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