任何人都可以帮助我。我想将edittext中的数据发送到JSONMessage中的另一个活动。我想在第二次活动中发送给IDDevice。
这是我的代码
这是我的第一个活动
et = (EditText) findViewById(R.id.editText1);
bt = (Button) findViewById(R.id.bAdd);
lv = (ListView) findViewById(R.id.listView);
arrayList = new ArrayList<String>();
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
lv.setAdapter(adapter);
onButtonClick();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String inputID = et.getText().toString();
Intent IDdevice = new Intent(MainActivity.this, ControlLed.class);
IDdevice.putExtra("ID", inputID);
startActivity(IDdevice);
}
});
}
第二项活动
public void device1on(){
String topic = "server/esp001";
MqttMessage message = new MqttMessage();
message.setPayload("{\"idDevice\":\"esp001\",\"status\":\"0\",\"data\":\"100\",\"address\":\"1\",\"function\":\"1\",\"user\":\"admin\"}".getBytes());// I want to send data from first activity to the idDevice
try {
client.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}
答案 0 :(得分:2)
在第二个活动中,使用getStringExtra
方法从Intent获取id,如下所述:
String id = getIntent().getStringExtra("ID");
然后将其设置为消息对象
JSONObject json = new JSONObject();
try {
json.put("idDevice", id);
json.put("status", "0");
json.put("data", "100");
json.put("address", "1");
json.put("function", "1");
json.put("user", "admin");
} catch (JSONException e) {
}
String payload = json.toString(); //"{\"idDevice\":\"value of id\",\"status\":\"0\",\"data\":\"100\",\"address\":\"1\",\"function\":\"1\",\"user\":\"admin\"}"
message.setPayload(payload.getBytes());
答案 1 :(得分:0)
String getvallue;
Intent i=i.getIntent();
getVallue=i.getStringExtra("name");
Textview txt=(Textview)findviewbyid(R.id.txt);
txt.setText(getVallue);