简体   繁体   中英

How to call the value of variables from one class to another in Java (Android)

This is my code. I want to call the value of lat , log variable from JSONTask to onMapReady .

public class JSONTask extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();

            String line ="";
            while ((line = reader.readLine()) != null){
                buffer.append(line);
            }

            String finalJson = buffer.toString();

            JSONObject parentObject = new JSONObject(finalJson);

            // JSONObject finalObject = parentObject.getJSONObject();

            String latitude = parentObject.getString("geo");
            String[] coordinate = latitude.split(",");

            double lat = Double.parseDouble(coordinate[0]);

            double log = Double.parseDouble(coordinate[1]);

            return lat + " - " + log ;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if(connection != null) {
                connection.disconnect();
            }
            try {
                if(reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        tvData.setText(result);
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(lat,log);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}

对于此类任务,我使用共享首选项,这是一种hack。

First of all, AsyncTask could be not finished yet when you onMapReady() method is called.
You should check this, for example if (lat != 0 && lon !=) .

Then, what's the problem is?
Announce variable lat, lon in your class.
And, in onPostExecute() parse your String with split(" - ") - it will give you String array of two items, then make lat = Double.parseDouble(yourArray[0]) and lon = Double.parseDouble(yourArray[1]) to get lat and lon.

尝试将lat和long变量定义为全局变量。

You can create a listener interface as code below

It is better to wait for map to get ready before you fetch your lat and long. so on onMapReady you can execute your AsyncTask and once you get result you can call addLatLng to add the marker

public class JSONTask extends AsyncTask<String, Void, LatLng> {

    interface OnLatLngReceivedListener {
        void onLatLngReceived(LatLng latLng);
    }

    private OnLatLngReceivedListener listener;

    public JsonTask(OnLatLngReceivedListener listener) {
        this.listener = listener;
    }

    @Override
    protected LatLng doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            JSONObject parentObject = new JSONObject(buffer.toString());
            String latitude = parentObject.getString("geo");
            String[] coordinate = latitude.split(",");

            double lat = Double.parseDouble(coordinate[0]);
            double log = Double.parseDouble(coordinate[1]);
            return new LatLng(lat, log);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(LatLng latLng) {
        if (latLng != null && listener != null) {
            listener.onLatLngReceived(latLng);
        } else {
            // SOME FAILING REPORT MECHANISM
        }
    }
}

In your activity/fragment

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    new JsonTask(new JsonTask.OnLatLngReceivedListener() {
        @Override
        public void onLatLngReceived(LatLng latLng) {
            addLatLng(latLng);
        }
    }).execute("YOUR_JSON_URL");
}

private void addLatLng(LatLng latLng) {
    // Add a marker in Sydney and move the camera
    mMap.addMarker(new MarkerOptions().position(latLng).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}

Note: you might have to write some logic to avoid adding same marker multiple time.

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