Estou tendo uma grande dificuldade para realizar uma tarefa talvez até simples, para os que estão mais habituados com a linguagem Java no Android.
Tenho uma aplicação que dispões de menus com opções. Uma delas é a de enviar os dados de TextView
's à um servidor na net. Nesses TextView
's há dois campos: um tópico e uma mensagem. Porém, para enviar eu preciso usar a opção via menu, mas eu queria substituir ela por um botão com evento onClick()
, estando ele no próprio layout em que a opção do menu fica visível. Minha intenção é atribuir ao botão os dados que seriam preenchidos nos TextView
, de modo a não precisar mais preencher eles (geralmente dados fixos). Com isso, quero embutir no evento do botão.
Tenho a classe que faz o tratamento da leitura dos TextView
e envio dos dados ao servidor.
Tentei algumas formas: onClick
, listener
, mas nada funcionou. O programa rodava nem dava erro de execução, mas o botão ficava sem ação.
Quero usar o método publish da classe Listener
.
Abaixo seque a classe Listener completa:
/**
* 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);
}
}
}
Segue também o xml do layout Activity_publish
no qual inseri o botão para realizar o evento do menu.
<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>