【问题标题】:how to import a variable in Main class to a another class如何将主类中的变量导入另一个类
【发布时间】:2019-10-22 14:10:32
【问题描述】:

我有一个通过套接字发送消息的类,我想要该消息,它是用户输入应该发送的纯文本的文本。所以我尝试在类中捕捉纯文本的消息,但它不起作用如果有人知道如何将主类的变量导入另一个类。

这是我执行类的代码



    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);



【问题讨论】:

  • 谢谢,但是当我要求发送消息时,它会发送 [Ljava.lang.String;@7bab97d 我如何将其更改为字符串文本
  • 这可能是由几个原因造成的。您提供给printer.write() 的参数真正 包含此值,或者您已将变量声明为Object 而不是String。在后一种情况下,您应该确保您正在处理String 变量。在前一种情况下,您需要对为什么会发生这种情况进行一些调查(您可能会在不希望这样做的地方调用toString()
  • 谢谢,我会尝试找出错误并通知您。
  • 我没有找到错误我编辑代码如果你想找到错误。我你不想要,因为我需要问另一个我会理解的问题。感谢您尝试找出他的错误。

标签: java android plaintext


【解决方案1】:

如您所见,您收到变量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);

【讨论】:

  • 很高兴我能帮上忙 ;)。不要忘记接受这个答案。这将对有相同问题的其他用户有所帮助。
  • 对不起,我今天才知道这个函数
猜你喜欢
  • 2019-08-23
  • 2021-12-01
  • 2021-08-09
  • 1970-01-01
  • 2018-01-10
  • 2021-06-15
  • 2013-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多