简体   繁体   中英

Java access a public variable outside a class, SecurityException: MIDlet not constructed by createMIDlet

I'm a newbie in java and I have a small problem. I want to access a variable in one class from another. I have three classes and I want to be able to access a variable in the main class to enable me read the array.

The error I am getting is

    java.lang.SecurityException: MIDlet not constructed by createMIDlet

Please see the example below. Please bear in mind they're all in the same package.

    package tungPackage;

    import com.sun.lwuit.*;
    import com.sun.lwuit.animations.CommonTransitions;
    import com.sun.lwuit.events.ActionEvent;
    import com.sun.lwuit.events.ActionListener;
    import javax.microedition.midlet.MIDlet;


    public class TungMidlet extends MIDlet implements ActionListener {
    private Command       back                = new Command("Back");
    private Command       ok                  = new Command("Ok");

    public ActionListener commandlistListener = new ActionListener() {
        public void actionPerformed(ActionEvent cmd) {

            // check which command cliked
            if (cmd.getCommand() == back) {

                // go back to previous form
                mainForm.show();
            } else if (cmd.getCommand() == ok) {

                // go forward
            }
        }
    };

    private List              list;
    private Form              mainForm;
    private Label             promptLabel;

    private housesClass houseClassObject = new housesClass();

    public int counter; //this is the variable I want to access in a class called calculate class object.

    private int sumAmmt;

    public TungMidlet tungMidletObject;
    public calculateClass calculateClassObject;



    public TungMidlet() {
        Display.init(this);
    }
    private ActionListener applistListener = new ActionListener() {
        public void actionPerformed(ActionEvent ae) {

            if(list.getSelectedIndex()==0){

                counter++;

                if (counter>5)
                {
                    //check sum price.
                    sumAmmt = calculateClassObject.calculateSum();
                    Dialog x = new Dialog("info");
                    Label label = new Label("Maximum reached.");
                    Label label2 = new Label("Sum ammt = "+sumAmmt);
                    x.addComponent(label);
                    x.addComponent(label2);
                    x.addCommand(ok);
                    x.show();
                }
                else

                {
                    //calculate the price
                    String info = houseClassObject.randomHouse();
                    Dialog x = new Dialog("info");
                    Label label = new Label(info);
                    x.addComponent(label);
                    x.addCommand(ok);
                    x.show();
                }

            }
        }
    };


    public void startApp() {
      //calculateClassObject = new calculateClass();

       //sumAmmt = calculateClassObject.calculate(sumAmmt);

        mainForm     = new Form("Investment Categories");
        promptLabel = new Label("choose category");

        list = new List();
        list.addItem("House");
        list.addItem("Cars");
        list.addItem("Schools");
        list.addItem("Schools");
        list.addItem("Supermarkets");
        list.addItem("Stocks");
        list.addItem("Land");

        list.addActionListener(applistListener);

        mainForm.addComponent(promptLabel);
        mainForm.addComponent(list);
        mainForm.addCommand(back);
        mainForm.addCommandListener(commandlistListener);
        mainForm.setTransitionInAnimator(CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, true, 1000));
        mainForm.show();
    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {}


    public void actionPerformed(ActionEvent ae) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    }

The class I want to access the "counter" variable using is shown below.

    package tungPackage;

     import java.util.Random;


     public class housesClass {
     public Random   generator  = new Random();
     public String[] houseArray = new String[5];
     public housesClass housesClassObject;

     public calculateClass calcobj;// = new calculateClass();

     public housesClass()
        {
        }

     public String randomHouse() {

       housesClassObject = new housesClass();

        houseArray[0] = "Bungalow - 20,000,000 Shillings";
        houseArray[1] = "Microhouse - 10,000,000 Shillings";
        houseArray[2] = "Flat - 200,000,000 shillings";
        houseArray[3] = "Garage apartment  - 7,000,000 shillings";
        houseArray[4] = "Studio apartment  - 13,000,000 shillings";

        int rnd = generator.nextInt(houseArray.length);

        housesClassObject.housePrices(rnd);///noma

        String house = houseArray[rnd];

        return house;
    }
     void housePrices(int houseNumber) {
     calcobj = new calculateClass();
     TungMidlet tungmidobj = new TungMidlet();
     int counter = tungmidobj.counter;
     int[] housePriceArray = new int[5];
     housePriceArray[0] = 20000000;
     housePriceArray[1] = 10000000;
     housePriceArray[2] = 200000000;
     housePriceArray[3] = 7000000;
     housePriceArray[4] = 13000000;

     int price = housePriceArray[houseNumber];

     calcobj.storePrice(counter,price);
    }
    }

The other supporting class is shown below.

     package tungPackage;

     public class calculateClass {
     int[] storeArray = new int[5];



     public calculateClass()
     { 
     }

     public void storePrice(int counter, int number2)
     {
     storeArray[counter] = number2;      
     }

    public int calculateSum()
    {
            int sum =0;

           for(int i=1; i<6; i++){
              sum= sum+storeArray[i];
         }
           return sum;
     }
    }

Are you getting an error? It looks like your access code should work.

I can't seem to find anywhere that you actually initialise counter though, so maybe your problem is that you need to put counter = 0; somewhere in your code.

Java is also object oriented so you should avoid accessing like the above and make some 'getter and setter' methods:

public int getCounter() {
    return counter;
}

and then call int counter = tungmidobj.getCounter();

  1. remove TungMidlet constructor. If there was something useful to do there, you could also declare it protected - but this is not the case with your code snippet, see below.
    Wherever you try to invoke that constructor directly, remove code that does this and find another way to do what you need. If needed, study code examples provided in LWUIT Tutorial - Introduction for how typical things are done in LWUIT.
  2. put statement Display.init() in the beginning of the startApp method,
    just like it is done in LWUIT Tutorial - Hello, LWUIT! example code

The reason why you are getting SecurityException is because you invoke TungMidlet constructor directly. Don't do that.

one way is

 TungMidlet tungMidlet=new TungMidlet();
System.out.println(tungMidlet.counter);

but know encapsulation

second way is

you can make counter private variable and provide setter and getters.

private int counter;

public void setCounter(int counter){
this.counter=counter;
}

public int getCounter(){
return counter;
}

second way is preferred way as it achieves encapsulation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM