调用另一个类方法

时间:2015-09-27 15:25:24

标签: java android

我试图运行publish()方法Class Listener。

但每当发生错误时。通过创建访问Listener var = new Listener (); var.publish ()。他在Listener class中要求建筑师。公开的Listener(){}留空了。我可以在System.out.printl ("blabla")中调用Listener,但发布()不会。

也许是因为publish () Listener中的方法Class使用了connectionDetails,我可能不得不将其传递给构造函数。

有助于从Publish()致电ActionListener/Connect()

班级听众:



package org.eclipse.paho.android.service.sample;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.android.service.sample.ActionListener.Action;
import org.eclipse.paho.android.service.sample.Connection.ConnectionStatus;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.logging.LogManager;

/**
 * Deals with actions performed in the {@link ClientConnections} activity
 * and the {@link ConnectionDetails} activity and associated fragments
 *
 */
public class Listener implements OnMenuItemClickListener {

  /** The handle to a {@link Connection} object which contains the {@link MqttAndroidClient} associated with this object **/
  private String clientHandle = null;

  /** {@link ConnectionDetails} reference used to perform some actions**/
  private ConnectionDetails connectionDetails = null;
  /** {@link ClientConnections} reference used to perform some actions**/
  private ClientConnections clientConnections = null;
  /** {@link Context} used to load and format strings **/
  private Context context = null;

  /** Whether Paho is logging is enabled**/
  static boolean logging = false;

  /**
   * Constructs a listener object for use with {@link ConnectionDetails} activity and
   * associated fragments.
   * @param connectionDetails The instance of {@link ConnectionDetails}
   * @param clientHandle The handle to the client that the actions are to be performed on
   */
  public Listener(ConnectionDetails connectionDetails, String clientHandle)
  {
    this.connectionDetails = connectionDetails;
    this.clientHandle = clientHandle;
    context = connectionDetails;
  }

  /**
   * Constructs a listener object for use with {@link ClientConnections} activity.
   * @param clientConnections
   */
  public Listener(ClientConnections clientConnections) {
    this.clientConnections = clientConnections;
    context = this.clientConnections;
  }

  
public Listener( ) {

  }
  
  /**
   * Perform the needed action required based on the button that
   * the user has clicked.
   *
   * @param item The menu item that was clicked
   * @return If there is anymore processing to be done
   *
   */
  @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;
  }
  
  
  /**
   * Publish the message the user has specified
   */
  
  public 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);
    }
  }

}




类ActionListener



    package org.eclipse.paho.android.service.sample;

    import android.content.Context;
    import android.widget.Toast;

    import org.eclipse.paho.android.service.sample.Connection.ConnectionStatus;
    import org.eclipse.paho.client.mqttv3.IMqttActionListener;
    import org.eclipse.paho.client.mqttv3.IMqttToken;

    /**
     * This Class handles receiving information from the
     * {@link MqttAndroidClient} and updating the {@link Connection} associated with 
     * the action
     */
    class ActionListener implements IMqttActionListener {

      /**
       * Actions that can be performed Asynchronously <strong>and</strong> associated with a
       * {@link ActionListener} object
       * 
       */
      enum Action {
        /** Connect Action **/
        CONNECT,
        /** Disconnect Action **/
        DISCONNECT,
        /** Subscribe Action **/
        SUBSCRIBE,
        /** Publish Action **/
        PUBLISH
      }

      /**
       * The {@link Action} that is associated with this instance of
       * <code>ActionListener</code>
       **/
      private Action action;
      /** The arguments passed to be used for formatting strings**/
      private String[] additionalArgs;
      /** Handle of the {@link Connection} this action was being executed on **/
      private String clientHandle;
      /** {@link Context} for performing various operations **/
      private Context context;

      /**
       * Creates a generic action listener for actions performed form any activity
       * 
       * @param context
       *            The application context
       * @param action
       *            The action that is being performed
       * @param clientHandle
       *            The handle for the client which the action is being performed
       *            on
       * @param additionalArgs
       *            Used for as arguments for string formating
       */
      public ActionListener(Context context, Action action,
          String clientHandle, String... additionalArgs) {
        this.context = context;
        this.action = action;
        this.clientHandle = clientHandle;
        this.additionalArgs = additionalArgs;
      }

      /**
       * The action associated with this listener has been successful.
       * 
       * @param asyncActionToken
       *            This argument is not used
       */
      
    @Override
      public void onSuccess(IMqttToken asyncActionToken) {
        switch (action) {
          case CONNECT :
            connect();
            break;
          case DISCONNECT :
            disconnect();
            break;
        }
      }

      /**
       * A disconnection action has been successfully completed, update the
       * connection object associated with the client this action belongs to and
       * then notify the user of success.
       */
      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);

      }

      /**
       * A connection action has been successfully completed, update the
       * connection object associated with the client this action belongs to and
       * then notify the user of success.
       */
      

    private void connect() {

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


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

      }

    }
&#13;
&#13;
&#13;

我的Logcat:

&#13;
&#13;
09-27 11:22:21.824    3324-3324/org.eclipse.paho.android.service.sample D/dalvikvm﹕ GC_FOR_ALLOC freed 232K, 9% free 3239K/3552K, paused 6ms, total 12ms
09-27 11:22:22.304    3324-3494/org.eclipse.paho.android.service.sample D/AlarmPingSender﹕ Register alarmreceiver to MqttServiceMqttService.pingSender.Quarto
09-27 11:22:22.304    3324-3494/org.eclipse.paho.android.service.sample D/AlarmPingSender﹕ Schedule next alarm at 1443367352311
09-27 11:22:22.324    3324-3324/org.eclipse.paho.android.service.sample D/AndroidRuntime﹕ Shutting down VM
09-27 11:22:22.324    3324-3324/org.eclipse.paho.android.service.sample W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb3ce0b20)
09-27 11:22:22.334    3324-3324/org.eclipse.paho.android.service.sample D/dalvikvm﹕ GC_FOR_ALLOC freed 353K, 12% free 3401K/3832K, paused 9ms, total 10ms
    --------- beginning of /dev/log/system
09-27 11:22:22.344    3324-3324/org.eclipse.paho.android.service.sample E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: org.eclipse.paho.android.service.sample, PID: 3324
    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:164)
            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)
&#13;
&#13;
&#13;

0 个答案:

没有答案