简体   繁体   中英

Cannot refer to the non-final local variable jSONString defined in an enclosing scope

I am trying to pass JSON string to the server after 60 seconds. At the moment I am facing problem when I try to execute MyAsyncTask from an thread; jSONString is not accessable at this line new MyAsyncTask().execute(jSONString); and I am getting this error Cannot refer to the non-final local variable jSONString defined in an enclosing scope

This part of code is being called from the onLocationChanged method in the inner class of the MainActivity :

String jSONString = convertToJSON(pLong, pLat, formatted);
PostData sender = new PostData();
sender.timer(jSONString);

PostData class:

public class PostData {
    String jSONString;
    Handler handler = new Handler();

    public PostData() {
        super();
    }

    public String getjSONString() {
        return jSONString;
    }

    public void setjSONString(String jSONString) {
        this.jSONString = jSONString;
    }

    public void timer(String jSONString) {
        this.jSONString = jSONString;

        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean run = true;
                while (run) {
                   handler.postDelayed(new Runnable() {
                       @Override
                       public void run() {
                           new MyAsyncTask().execute(jSONString); //How can I access this variable'jSONString' here?
                       }
                   }, 5000);
                }
            }
        }).start();
    }

    class MyAsyncTask extends AsyncTask<String, Integer, Void> {

        @Override
        protected Void doInBackground(String... params) {
            System.out.println("The output of : doInBackground " +params[0]);
            //the connection code.

            return null;
        }
    }
}

使用在jSONString中声明的PostData当前尝试访问不是final timer方法参数:

new MyAsyncTask().execute(PostData.this.jSONString);

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