Using another class method

Asked

Viewed 850 times

1

I need to execute a method that is in another class. I think the two are non-activityes classes.

The following class has a method called connect(). When this method is executed, at the end of it I want to call another method that is in another class. Next is the class that has the method connect(). Face time I click Connect (menu button), I need the program to also run the method publish()which belongs to another class.

    class ActionListener implements IMqttActionListener {

      enum Action {
        CONNECT,
        DISCONNECT,
        SUBSCRIBE,
        PUBLISH
      }

      private Action action;
      private String[] additionalArgs;
      private String clientHandle;
      private Context context;

      public ActionListener(Context context, Action action,
          String clientHandle, String... additionalArgs) {
        this.context = context;
        this.action = action;
        this.clientHandle = clientHandle;
        this.additionalArgs = additionalArgs;
      }

      @Override
      public void onSuccess(IMqttToken asyncActionToken) {
        switch (action) {
          case CONNECT :
            connect(); 
            break;
          case DISCONNECT :
            disconnect();

        }

      }


      private void disconnect() {
        Connection c = Connections.getInstance(context).getConnection(clientHandle);
        c.changeConnectionStatus(ConnectionStatus.DISCONNECTED);
        String actionTaken = context.getString(R.string.toast_disconnected);
        c.addAction(actionTaken);

      }


      //Daqui quero executar outro método em outra classe
      private void connect() { 

        Connection c = Connections.getInstance(context).getConnection(clientHandle);
        c.changeConnectionStatus(Connection.ConnectionStatus.CONNECTED);
        c.addAction("Client Connected");

         }


      @Override
      public void onFailure(IMqttToken token, Throwable exception) {
        switch (action) {
          case CONNECT :
            connect(exception);
            break;
          case DISCONNECT :
            disconnect(exception);
            break;

        }

      }


      private void disconnect(Throwable exception) {
        Connection c = Connections.getInstance(context).getConnection(clientHandle);
        c.changeConnectionStatus(ConnectionStatus.DISCONNECTED);
        c.addAction("Disconnect Failed - an error occured");

      }

        private void connect(Throwable exception) {
        Connection c = Connections.getInstance(context).getConnection(clientHandle);
        c.changeConnectionStatus(Connection.ConnectionStatus.ERROR);
        c.addAction("Client failed to connect");

        Listener var = new Listener();
        var.publish();

      }

    }

The object new Listener(); suggests the two builders of the class Listener. Being them onnectionDetails connectionDetails, String clientHandle and ClientConnections clientConnections. If you leave the constructor empty it returns nullpointerexception.

Listener.java:245 points to String topic = ((EditText) connectionDetails.findViewById...

(ActionListener.java:163) for var.publish();

(ActionListener.java:92) for case CONNECT: connect();

The second class is following. The method I want to use is the PUBLISH()

public class Listener implements OnMenuItemClickListener{

  private String clientHandle = null;
  private ConnectionDetails connectionDetails = null;
  private ClientConnections clientConnections = null;
  private Context context = null;
  static boolean logging = false;

  public Listener(ConnectionDetails connectionDetails, String clientHandle)
  {
    this.connectionDetails = connectionDetails;
    this.clientHandle = clientHandle;
    context = connectionDetails;
  }

    public Listener(ClientConnections clientConnections) {
    this.clientConnections = clientConnections;
    context = clientConnections;
  }

    @Override
  public boolean onMenuItemClick(MenuItem item) {

    int id = item.getItemId();

    switch (id)
    {
      case R.id.publish :
        publish();
        break;
      case R.id.subscribe :
        subscribe();
        break;
          }

    return false;
  }



  private void subscribe()
  {
    String topic = ((EditText) connectionDetails.findViewById(R.id.topic)).getText().toString();
    ((EditText) connectionDetails.findViewById(R.id.topic)).getText().clear();

    RadioGroup radio = (RadioGroup) connectionDetails.findViewById(R.id.qosSubRadio);
    int checked = radio.getCheckedRadioButtonId();
    int qos = ActivityConstants.defaultQos;

    switch (checked) {
      case R.id.qos0 :
        qos = 0;
        break;
      case R.id.qos1 :
        qos = 1;
        break;
      case R.id.qos2 :
        qos = 2;
        break;
    }

    try {
      String[] topics = new String[1];
      topics[0] = topic;
      Connections.getInstance(context).getConnection(clientHandle).getClient()
          .subscribe(topic, qos, null, new ActionListener(context, Action.SUBSCRIBE, clientHandle, topics));
    }
    catch (MqttSecurityException e) {
      Log.e(this.getClass().getCanonicalName(), "Failed to subscribe to" + topic + " the client with the handle " + clientHandle, e);
    }
    catch (MqttException e) {
      Log.e(this.getClass().getCanonicalName(), "Failed to subscribe to" + topic + " the client with the handle " + clientHandle, e);
    }
  }


  //Método a ser chamado 
  private void publish()
  {    

    String topic = ((EditText) connectionDetails.findViewById(R.id.lastWillTopic))
        .getText().toString();


    String message = ((EditText) connectionDetails.findViewById(R.id.lastWill)).getText()
        .toString();


    RadioGroup radio = (RadioGroup) connectionDetails.findViewById(R.id.qosRadio);
    int checked = radio.getCheckedRadioButtonId();
    int qos = ActivityConstants.defaultQos;

    switch (checked) {
      case R.id.qos0 :
        qos = 0;
        break;
      case R.id.qos1 :
        qos = 1;
        break;
      case R.id.qos2 :
        qos = 2;
        break;
    }

    boolean retained = ((CheckBox) connectionDetails.findViewById(R.id.retained))
        .isChecked();

    String[] args = new String[2];
    args[0] = message;
    args[1] = topic+";qos:"+qos+";retained:"+retained;

    try {
      Connections.getInstance(context).getConnection(clientHandle).getClient()
          .publish(topic, message.getBytes(), qos, retained, null, new ActionListener(context, Action.PUBLISH, clientHandle, args));
    }
    catch (MqttSecurityException e) {
      Log.e(this.getClass().getCanonicalName(), "Failed to publish a messged from the client with the handle " + clientHandle, e);
    }
    catch (MqttException e) {
      Log.e(this.getClass().getCanonicalName(), "Failed to publish a messged from the client with the handle " + clientHandle, e);
    }

  }  

}

Logcat:

--------- beginning of /dev/log/system
09-28 11:32:15.745  25770-25770/org.eclipse.paho.android.service.sample E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: org.eclipse.paho.android.service.sample, PID: 25770
    java.lang.NullPointerException
            at org.eclipse.paho.android.service.sample.Listener.publish(Listener.java:245)
            at org.eclipse.paho.android.service.sample.ActionListener.connect(ActionListener.java:163)
            at org.eclipse.paho.android.service.sample.ActionListener.onSuccess(ActionListener.java:92)
            at org.eclipse.paho.android.service.MqttTokenAndroid.notifyComplete(MqttTokenAndroid.java:124)
            at org.eclipse.paho.android.service.MqttAndroidClient.simpleAction(MqttAndroidClient.java:1370)
            at org.eclipse.paho.android.service.MqttAndroidClient.connectAction(MqttAndroidClient.java:1325)
            at org.eclipse.paho.android.service.MqttAndroidClient.onReceive(MqttAndroidClient.java:1265)
            at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:297)
            at android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)
            at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:116)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)

1 answer

1

Change the declaration of the Publish method from private to public, then you can access from other classes, or you can switch to protected, if both classes are in the same package:

public void publish() {} 

Or

protected void publish() {}

Then, within your conect method you create the object of the Listener class and call the Publish method. You can still make Publish to be Static, then you won’t need to create the object.

  • Placed publish() as public. If I did right, I left inside connect the following: Listener var = new Listener(); var.publish(); But there was an error "cannot resolved constructor Listener()" asking to create a constructor. I tried to do publish()as Static, but some items within the method publish() turned red.

  • You have no empty constructor in the Listener class to create a void and use. Declare one and try again: public Listener() {}

  • I declared one and tried. By calling the publish() program gives error. But if I put a System.out.println in Listener he calls normal. But calling the publish() error. logcat has some messages, I can edit and post to see if it helps something.

  • Now that I’ve seen it, that’s probably why the method publish() uses the connectionDetails but if you don’t pass an instance of it in the constructor, it will be null because of this private ConnectionDetails connectionDetails = null;, that is, you cannot use the empty constructor, you have to use the one that receives an instance of ConnectionDetails and pass that instance.

  • I understood what you said and it makes sense. But could you please show me how? I couldn’t do it.

  • If the intention is only to use in the same package, it need not be protected. Not using modifier (default access control) is enough.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.