おはようみんなでMainActivityの変数を変更する方法。 EditTextコンポーネントがあり、MainActivityの変数に入力されたテキストを取得したいと考えています。私はあなたが私を助けることができるでしょう願ってい</p> <p>私はAlertDialogでいくつかの問題が発生した、AlertDialogアンドロイド
private void showDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
final EditText input = new EditText(MainActivity.this);
builder.setTitle(R.string.title);
builder.setMessage(R.string.enter_comment);
builder.setView(input);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// name is the variable I want to change. It has been declared as String name; at the beginning of my MainActivity class.
name = input.getText().toString();
showToast(name);
}
});
builder.setNegativeButton(R.string.annuler, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
this.runOnUiThread(new Runnable() {
public void run() {
builder.show();
}
});
// This line makes the app crash. It doesn't print "Null String" as it should.
//showToast(name);
}
private void showToast(String str) {
if (str != null) {
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Null String", Toast.LENGTH_SHORT).show();
}
}
:
は、ここに私のコードです。 ありがとうございます!
EDIT - を追加しました完全なコード(輸入を除く - >あまりにも多くの)
package com.example.ghost.boxmonitor;
public class MainActivity extends Activity {
public final String ACTION_USB_PERMISSION = "com.ghost.boxmonitor.USB_PERMISSION";
Button startButton, clearButton, stopButton;
TextView textView;
UsbManager usbManager;
UsbDevice device;
UsbSerialDevice serialPort;
UsbDeviceConnection connection;
LinkedList<Box> list;
String text,name;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
@Override
public void onReceivedData(byte[] arg0) {
String data = null;
try {
data = new String(arg0, "UTF-8");
data.concat("/n");
tvAppend(textView, data);
buildString(data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { //Broadcast Receiver to automatically start and stop the Serial connection.
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = intent.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) {
connection = usbManager.openDevice(device);
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) { //Set Serial Connection Parameters.
setUiEnabled(true);
serialPort.setBaudRate(9600);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
tvAppend(textView,"Serial Connection Opened!\n");
} else {
tvAppend(textView,"Port not opened\n");
Log.d("SERIAL", "PORT NOT OPEN");
}
} else {
tvAppend(textView,"Port null\n");
Log.d("SERIAL", "PORT IS NULL");
}
} else {
tvAppend(textView,"Perm not granted\n");
Log.d("SERIAL", "PERM NOT GRANTED");
}
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
onClickStart(startButton);
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
onClickStop(stopButton);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usbManager = (UsbManager) getSystemService(this.USB_SERVICE);
startButton = (Button) findViewById(R.id.buttonStart);
clearButton = (Button) findViewById(R.id.buttonClear);
stopButton = (Button) findViewById(R.id.buttonStop);
textView = (TextView) findViewById(R.id.textView);
setUiEnabled(false);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(broadcastReceiver, filter);
list = new LinkedList<Box>();
}
public void setUiEnabled(boolean bool) {
startButton.setEnabled(!bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public void onClickStart(View view) {
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
tvAppend(textView, "Device VID : "+Integer.toString(deviceVID)+"\n");
if (deviceVID == 10755 || deviceVID == 9025)//Arduino Vendor ID
{
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
tvAppend(textView,"Arduino detected. Waiting for user authorization...\n");
usbManager.requestPermission(device, pi);
keep = false;
} else {
connection = null;
device = null;
tvAppend(textView,"This device is not an Arduino.\n");
}
if (!keep)
break;
}
}
else{
tvAppend(textView,"No USB device detected.\n");
}
}
public void onClickStop(View view) {
setUiEnabled(false);
serialPort.close();
tvAppend(textView, "\nUSB device unplugged.\nSerial Connection Closed !\n");
}
public void onClickClear(View view) {
textView.setText(" ");
showDialog();
}
private void tvAppend(TextView tv, CharSequence text) {
final TextView ftv = tv;
final CharSequence ftext = text;
runOnUiThread(new Runnable() {
@Override
public void run() {
ftv.append(ftext);
}
});
}
public void interpreter(String text){
String table[] = text.split("&");
String def = Integer.toString(list.size() + 1);
if (table.length == 2) {
if (list.isEmpty()) {
//showDialog();
Box b = new Box(table[0], table[1], def);
list.add(b);
//tvAppend(textView2, b.execute());
} else {
boolean isInList = false;
for (Box b : list) {
if (b.getAddr().compareTo(table[0]) == 0) {
isInList = true;
b.setState(table[1]);
//tvAppend(textView2, b.execute());
}
}
if (!isInList) {
//showDialog();
Box b = new Box(table[0], table[1], def);
list.add(b);
//tvAppend(textView2, b.execute());
}
}
}
}
public void buildString(String data){
int len = data.length();
char c;
for (int i = 0; i<len; i++){
c = data.charAt(i);
switch (c){
case '#':
text = "";
break;
case '!':
interpreter(text);
break;
default:
text+=c;
break;
}
}
}
private void showDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
final EditText input = new EditText(MainActivity.this);
builder.setTitle("Title");
builder.setMessage("Message");
builder.setView(input);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
name = input.getText().toString();
Log.d("MyTag", "name in onClick()" + name);
showToast(name);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
showToast(name);
}
private void showToast(String str) {
if (str != null) {
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Null String", Toast.LENGTH_SHORT).show();
}
}
}
ので、毎回私は、文字列を構築し、シリアル回線上のデータを受信し、文字列が完了している場合私は通訳を呼びます。文字列に新しいBoxが記述されている場合は、showDialogメソッドを呼び出して、ユーザーに名前を付けるように要求します。
編集編集 - ソリューション
以下の答え、および関連するコメントを参照してください。私が問題を理解する限り、UiThread以外のスレッド内のUIを変更することはできません(これは明らかですが...)。
「MainActivityの変数に入力されたテキストを取得したいのですか?実際に何を達成する必要がありますか? – darwin
ご意見ありがとうございます。私はEditTextコンポーネントでユーザーが書いたテキストを取得し、それを他の関数で使用するためにname変数に書きたいと思います。 –
テキストを取得する編集テキストはどれですか? – darwin