简体   繁体   中英

Unable to access current value of Global Variable in Java

Below is my code, lat_val and long_val is not getting updated with received value from JSON response in btnShowLoc() , it is referencing to the default value which is 0,0. I want the global variable to keep updating when ever referenced and updated with JSON response.

public class MainActivity extends Activity {


    public static String lat_val = "0";
    public static String long_val = "0";

    public String readJSONFeed(String urlStr) {
        StringBuilder stringBuilder = new StringBuilder();

        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestProperty("SisApiKey", "4572c3c9-73cb-4958-9649-26c1e8df27e8");
            urlConnection.setRequestProperty("SisSmartKey", "d1aebd25-774c-4e8a-b3a5-ee5a603cc603");

            InputStream ins = urlConnection.getInputStream();
            urlConnection.connect();
            int statusCode = urlConnection.getResponseCode();

            if (statusCode == 200) {
                BufferedReader br = new BufferedReader(new InputStreamReader(ins));

                String line;
                while ((line = br.readLine()) != null) {
                    stringBuilder.append(line);
                }
                ins.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (java.net.MalformedURLException e) {
            e.printStackTrace();
        } catch (java.io.IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }

    public class ReadJSONFeedTask extends AsyncTask
            <String, Void, String> {
        protected String doInBackground(String... url) {
            return readJSONFeed(url[0]);
        }

        protected void onPostExecute(String result) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                //JSONObject flags = new JSONObject(jsonObject.getString("flag"));
                JSONObject locationItems = new JSONObject(jsonObject.getString("response"));
                //Log.v("Location Details :", locationItems.toString());
                String []dev_loc = locationItems.toString().split("[\\s*,\\s*]");
                MainActivity.lat_val = dev_loc[0]; //"12.9934136";
                MainActivity.long_val = dev_loc[1]; //"80.2464206";

            } catch (Exception e) {
                Log.d("ReadJSONFeedTask", e.getLocalizedMessage());
            }
        }
    }

    public void btnGetDevLoc(View view) {

        String sp_val = String.valueOf(spinner1.getSelectedItem());

        new ReadJSONFeedTask().execute(
                "http://15.153.133.160:21743/sis/sie/api/v1/applications/bb9f05fb-a796-4b75-9db7-c999360ad185/virtualobjects/d77d3905-aa77-41b9-9034-b0052bfde405?secondString=HWE_ASSET_ANDROID"); // + sp_val);
    }


    public void btnShowLoc(View view) {

        //lat_val = "12.9934136";
        //long_val = "80.2464206";

        Intent in = new Intent(MainActivity.this, MapActivity.class);
        Bundle bundle = new Bundle();

        bundle.putString("latitude", MainActivity.lat_val);
        bundle.putString("longitude", MainActivity.long_val);
        in.putExtras(bundle);
        startActivity(in);
    }

With the few information you have shared, and given that

btnGetDevLoc() and btnShowLoc() are the functions executed when clicked on buttons in the application defined in activity_main.xml

and that

First btnGetDevLoc() is called then btnShowLoc()

the first thing that pops out in my mind is that the AsyncTask has not yet finished updating the String values, when you call btnShowLoc() .

So, if btnGetDevLoc() and btnShowLoc() are called sequentially, like

... onClick() {
   btnGetDevLoc();
   btnShowLoc();
}

then it's most likely due to what I said above. Remember that AsyncTask runs asynchronously (as the name says...).


You can test this really small program.

public static double var1 = 0.0;

public static void main(String[] args) {
    new Thread(() -> {
        var1 = 1.0;
    }).start();

    System.out.println(var1);
}

It will almost always print 0.0 , because the value of var1 is not updated yet when the main thread prints it.


What you should do is place your btnShowLoc() call at the end of onPostExecute(String) . This guarantees that your method is called only after you have updated the new values.

I can't Understand, when the btnGetDevLoc() and btnShowLoc() called? Can you post your whole MainActivity?

Edit :

It's seems like you call btnShowLoc() before your AsyncTask finish its proccess. You can change your code this way to make sure your btnShowLoc() called after your AsyncTask :

public class ReadJSONFeedTask extends AsyncTask
        <String, Void, String> {
    protected String doInBackground(String... url) {
        return readJSONFeed(url[0]);
    }

    protected void onPostExecute(String result) {
        try {
            JSONObject jsonObject = new JSONObject(result);
            //JSONObject flags = new JSONObject(jsonObject.getString("flag"));
            JSONObject locationItems = new JSONObject(jsonObject.getString("response"));
            //Log.v("Location Details :", locationItems.toString());
            String []dev_loc = locationItems.toString().split("[\\s*,\\s*]");
            MainActivity.lat_val = dev_loc[0]; //"12.9934136";
            MainActivity.long_val = dev_loc[1]; //"80.2464206";

            btnShowLoc(dev_loc[0], dev_loc[1]);

        } catch (Exception e) {
            Log.d("ReadJSONFeedTask", e.getLocalizedMessage());
        }
    }
}

public void btnShowLoc(String latitude, String longitude) {

    //lat_val = "12.9934136";
    //long_val = "80.2464206";

    Intent in = new Intent(MainActivity.this, MapActivity.class);
    Bundle bundle = new Bundle();

    bundle.putString("latitude", latitude);
    bundle.putString("longitude", longitude);
    in.putExtras(bundle);
    startActivity(in);
} 

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