简体   繁体   中英

How can i get final string into function for use to another function?

How can I get final string 'data' into this function beginListenForData () for use to another function upload ()? BeginListen get data from bluetooth...

  void beginListenForData()
  {
  final Handler handler = new Handler(); 

  workerThread = new Thread(new Runnable()
  {
      public void run()
      {              
              try {        
                        final String data = new String(encodedBytes, "US-ASCII");
                        readBufferPosition = 0;
                        //data2=data;
                              handler.post(new Runnable()
                              {
                                  public void run()
                                  {
                                      myLabel.setText(data);    

Make data as field instead of local variable.

 String data;

 void beginListenForData()
  {
  final Handler handler = new Handler(); 

  workerThread = new Thread(new Runnable()
  {
      public void run()
      {              
              try {        
                        data = new String(encodedBytes, "US-ASCII");
                        readBufferPosition = 0;
                        //data2=data;
                              handler.post(new Runnable()
                              {
                                  public void run()
                                  {
                                      myLabel.setText(data);    

I took a look at your code on google and I had this to ask:

Why are you re-declaring "data" again inside ListenBt() instead of manipulating the global final data variable?

And you cannot manipulate a final variable by reassigning aliases, you'll get an exception. 并且您不能通过重新分配别名来操纵最终变量,您将获得异常。
...Well maybe with reflection, but that's cheating!

You could achieve what you are looking for by calling "this.data" while data is a public global variable and setting it equal to what's desired.

If you are currently getting "0" when calling the upload function, it means it's referencing the global final variable data instead of what was done inside ListenBt().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM