Calling another class method in the same application

Asked

Viewed 1,471 times

2

I’m having a great difficulty to perform a task maybe even simple, for those who are more used to the Java language on Android.

I have an application that has menus with options. One of them is to send the data of TextView's is a server on the net. In these TextView's there are two fields: a topic and a message. However, to send I need to use the menu option, but I wanted to replace it with an event button onClick(), being on his own layout where the menu option is visible. My intention is to assign to the button the data that would be filled in TextView, so that you no longer need to fill them (usually fixed data). With this, I want to embed in the button event.

I have the class that does the treatment of reading TextView and sending the data to the server.

I tried some ways: onClick, listener, but nothing worked. The program ran or ran error, but the button ran out of action.

I want to use the method Publish class Listener.

Below dry the complete Listener class:

/**
 * Deals with actions performed in the {@link ClientConnections} activity
 * and the {@link ConnectionDetails} activity and associated fragments
 */

public class Listener extends 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 The instance of {@link ClientConnections}
     */
    public Listener(ClientConnections clientConnections) {
        this.clientConnections = clientConnections;
        context = clientConnections;
    }

    /**
     * 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;
            case R.id.newConnection:
                createAndConnect();
                break;
            case R.id.disconnect:
                disconnect();
                break;
            case R.id.connectMenuOption:
                reconnect();
                break;
            case R.id.startLogging:
                enablePahoLogging();
                break;
            case R.id.endLogging:
                disablePahoLogging();
                break;
        }

        return false;
    }

    /**
     * Reconnect the selected client
     */
    private void reconnect() {
        Connections.getInstance(context).getConnection(clientHandle).changeConnectionStatus(ConnectionStatus.CONNECTING);

        Connection c = Connections.getInstance(context).getConnection(clientHandle);
        try {
            c.getClient().connect(c.getConnectionOptions(), null, new ActionListener(context, Action.CONNECT, clientHandle, null));
        } catch (MqttSecurityException e) {
            Log.e(this.getClass().getCanonicalName(), "Failed to reconnect the client with the handle " + clientHandle, e);
            c.addAction("Client failed to connect");
        } catch (MqttException e) {
            Log.e(this.getClass().getCanonicalName(), "Failed to reconnect the client with the handle " + clientHandle, e);
            c.addAction("Client failed to connect");
        }
    }

    /**
     * Disconnect the client
     */
    private void disconnect() {
        Connection c = Connections.getInstance(context).getConnection(clientHandle);

        //if the client is not connected, process the disconnect
        if (!c.isConnected()) {
            return;
        }

        try {
            c.getClient().disconnect(null, new ActionListener(context, Action.DISCONNECT, clientHandle, null));
            c.changeConnectionStatus(ConnectionStatus.DISCONNECTING);
        } catch (MqttException e) {
            Log.e(this.getClass().getCanonicalName(), "Failed to disconnect the client with the handle " + clientHandle, e);
            c.addAction("Client failed to disconnect");
        }

    }

    /**
     * Subscribe to a topic that the user has specified
     */
    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);
        }
    }
}

Also follows the xml layout Activity_publish where I inserted the button to perform the menu event.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:id="@+id/topicGroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/topictextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="35dip"
        android:text="@string/topic" />

    <EditText
        android:id="@+id/lastWillTopic"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="0.22"
        android:ems="10"
        android:hint="@string/topicHint"
        android:inputType="text" />
</LinearLayout>

<LinearLayout
    android:id="@+id/messageGroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/topicGroup"
    android:layout_marginTop="25dp">

    <TextView
        android:id="@+id/messageTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="15dip"
        android:text="@string/message" />

    <EditText
        android:id="@+id/lastWill"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="0.22"
        android:ems="10"
        android:hint="@string/messageHint"
        android:inputType="textMultiLine" />
</LinearLayout>

<LinearLayout
    android:id="@+id/qosGroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/messageGroup"
    android:layout_marginTop="25dp">

    <TextView
        android:id="@+id/qosTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="40dp"
        android:layout_marginTop="10dp"
        android:text="@string/qos" />

    <RadioGroup
        android:id="@+id/qosRadio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/qos0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="@string/qos0" />

        <RadioButton
            android:id="@+id/qos1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/qos1" />

        <RadioButton
            android:id="@+id/qos2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/qos2" />
    </RadioGroup>

</LinearLayout>

<LinearLayout
    android:id="@+id/retainedGroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/qosGroup"
    android:layout_marginTop="25dp">

    <TextView
        android:id="@+id/retainedTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:text="@string/retained" />

    <CheckBox
        android:id="@+id/retained"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/empty" />
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/retainedGroup"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="86dp"
    android:orientation="vertical">

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Enviar" />
</LinearLayout>

1 answer

1

It would not simply add a button to the layout to assign the System?

     final Button button = (Button) findViewById(R.id.id_do_botao);
     button.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
             publish();
         }
     });

Note that the above language uses an "anonymous subclass" of Onclicklistener, avoiding having to declare a class just for this.

  • I added the following snippet just below the Listener class. It does not generate an execution error, but the button does not perform any action. No logcat appeared anything indicating possible problem.

  • The code suggestion above should go on onCreate().

  • Yes, I had inserted in an onCreate. protected void onCreate(Bundle saveInstanceState) { super.onCreate(saveInstanceState);&#xA;setContentView(R.layout.activity_publish);&#xA;final button = (Button) findViewById(R.id.button1);&#xA;button.setOnClickListener(new View.Onclicklistener() {&#xA;&#xA; public void onClick(View v) {&#xA; Publish();&#xA; }&#xA; });&#xA; }`

  • You would have to log into the onClick() method itself to see if at least it is running, if yes it remains to see what happens in Publish()

  • I did what you said. I tried to display a Toast by onClick(), but to no avail. Strange, as it was all stated correctly. It seems that the button has no action in relation to the method. I realized that the Publish() method has the following structure connectionDetails.findViewById(R.id.id_do_layout). I tried to use it like this, but it stayed exactly the way it was, no action. It would be inconvenient for me to edit my question by adding the entire class and layout information to try to help in the evaluation?

  • Better edit and include more details anyway... to see what we can do

Show 1 more comment

Browser other questions tagged

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