[英]how to import a variable in Main class to a another class
我有一個 class 通過套接字發送消息,我想要該消息,它是用戶輸入應該發送的純文本的文本。 因此,我嘗試在 class 中捕獲純文本的消息,但如果有人知道如何將主 class 的變量導入另一個 class,它就不起作用。
這是我執行 class 的代碼
class client extends AsyncTask<String, Void, Void> {
Handler handler = new Handler( );
protected Void doInBackground(String... h) {
TextView t3;
final EditText send;
send = (EditText) findViewById( R.id.editText );
t3 = (TextView) findViewById( R.id.textView );
try {
handler.post( new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),"start client", Toast.LENGTH_LONG).show();
}
} );
WifiManager manager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
ip = Formatter.formatIpAddress(manager.getConnectionInfo().getIpAddress());
String[] mess = h;
String messag_send=(mess+"<ip>"+ip);
sock = new Socket( "192.168.5.178", 5000 );
printWriter = new PrintWriter( sock.getOutputStream() );
printWriter.write(messag_send);
String line = "no";
printWriter.flush();
printWriter.close();
sock.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
and to import
client client = new client();
client.execute(h);
如您所見,您收到變量h
作為vararg 。 所以h
實際上是一個字符串數組。
protected Void doInBackground(String... h)
但是,您並沒有真正訪問它的內容,而是您編寫
String[] mess = h;
String messag_send=(mess+"<ip>"+ip);
由於mess
是一個數組,因此您將其toString()
值嵌入到您的消息中。
相反,您需要做的是檢索數組的第一個值(無論如何它可能只包含一個元素),就像這樣
String mess = h[0];
String messag_send=(mess+"<ip>"+ip);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.