在其他方法中获取AsyncTask的结果

时间:2017-04-02 21:59:50

标签: java android servlets android-asynctask client-server

我正在尝试将servlet的响应作为文本,解析此文本并提取用于在Google地图上显示标记的坐标。我的问题是我不知道如何从onMapReady方法中的onPostExecute方法调用结果。就像我在我的代码中调用一样,输入String显然是空的。

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap map;
private static final String LOG_TAG = "ExampleApp";
TextView tvIsConnected;
TextView tvResult;
TextView textView2;
private static final String SERVICE_URL = "http://192.168.178.42:8080/TutorialApp/User/GetAll";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
    tvResult = (TextView) findViewById(R.id.tvResult);
    textView2 = (TextView) findViewById(R.id.textView2);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    if (checkNetworkConnection())
        // perform HTTP GET request
        new HTTPAsyncTask().execute("http://192.168.178.42:8080/TutorialApp/User/GetAll");
}


public boolean checkNetworkConnection() {
    ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    boolean isConnected = false;
    if (networkInfo != null && (isConnected = networkInfo.isConnected())) {
        // show "Connected" & type of network "WIFI or MOBILE"
        tvIsConnected.setText("Connected " + networkInfo.getTypeName());
        // change background color to red
        tvIsConnected.setBackgroundColor(0xFF7CCC26);


    } else {
        // show "Not Connected"
        tvIsConnected.setText("Not Connected");
        // change background color to green
        tvIsConnected.setBackgroundColor(0xFFFF0000);
    }

    return isConnected;
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while ((line = bufferedReader.readLine()) != null)
        result += line + "\n";

    inputStream.close();
    return result;

}
private String HttpGet(String myUrl) throws IOException {
    InputStream inputStream = null;
    String result = "";

    URL url = new URL(myUrl);

    // create HttpURLConnection
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // make GET request to the given URL
    conn.connect();

    // receive response as inputStream
    inputStream = conn.getInputStream();

    // convert inputstream to string
    if (inputStream != null)
        result = convertInputStreamToString(inputStream);
    else
        result = "Did not work!";

    return result;
}

private class HTTPAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {
            return HttpGet(urls[0]);
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }
    //onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        tvResult.setText(result);
    }

}
@Override
public void onMapReady(GoogleMap googleMap) {

    String input = tvResult.getText().toString();

    String[] lines = input.split( "\n" );
    List<Pair<Double, Double>> list = new ArrayList<>();
    String ss="i";
    for( int i =1; i < lines.length-1; i++ ) {
        int firstcomma = lines[i].indexOf(",");
        int secondcomma = lines[i].indexOf(",", firstcomma + 1);
        int thirdcomma = lines[i].indexOf(",", secondcomma + 1);
        Double lat = Double.parseDouble(lines[i].substring(secondcomma + 1, thirdcomma));
        Double longitude = Double.parseDouble(lines[i].substring(thirdcomma + 1, lines.length));
        list.add(new Pair(lat,longitude));
    }
    for(int j=1; j<list.size();j++) {

        map = googleMap;
        // Add a marker in Sydney and move the camera
        //LatLng sydney = new LatLng(-34, 151);
        LatLng sydney = new LatLng(list.get(j).first, list.get(j).second);
        map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

}

1 个答案:

答案 0 :(得分:0)

您无法在onPostExecute()中调用onMapReady()的结果的原因是因为它们都在后台运行。您在这里唯一可以做的就是从getMapAsync()拨打onPostExecute(),这将确保您onPostExecute()已完成;或者,将onMapReady()的功能移动到onPostExecute()。您基本上有2 asyncTasks正在运行,因此您需要将它们链接起来(这有点像hacky)或将逻辑从onMapReady()移到onPostExecute()