簡體   English   中英

AsyncTask完成后,全局變量返回0.0

[英]Global Variable returning to 0.0 after completion of an AsyncTask

這個問題的主要部分是,當我運行這段代碼時,TextViews的latitudeTextView和longitudeTextView得到正確的更新,因此全局變量被更改為正確的值。 但是當我嘗試執行asynctask后再次嘗試訪問它們時,它們設置為0.0、0.0? 在onPostExecute結束后,它們不應該保持相同的值嗎?

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Weather>{

    private static final String GOOGLE_CONVERTER = "https://maps.googleapis.com/maps/api/geocode/json";

    private static final String GOOGLE_KEY = "AIzaSyBtt8yaXoRvLTkJHUXrhl5pQaLxomReHIA";

    public static final int LOADER_ID = 0;

    String jsonResponse = "";
    private String address;

    private TextView latitudeTextView;
    private TextView longitudeTextView;
    private TextView summaryTextView;
    private TextView tempuratureTextView;
    private TextView timezoneTextView;
    private TextView textTextView;

    private double latitude = 0.0;
    private double longitude = 0.0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        latitudeTextView = (TextView) findViewById(R.id.latitude);
        longitudeTextView = (TextView) findViewById(R.id.longitude);
        summaryTextView = (TextView) findViewById(R.id.summaryTextView);
        tempuratureTextView = (TextView) findViewById(R.id.temperatureTextView);
        timezoneTextView = (TextView) findViewById(R.id.timezoneTextView);
        textTextView = (TextView) findViewById(R.id.test);

        final EditText addressEditText = (EditText) findViewById(R.id.edittext_address);
        Button submitButton = (Button) findViewById(R.id.submit_button);

        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                address = addressEditText.getText().toString().trim();
                address = "5121+Paddock+Court+Antioch+Ca+94531";
                String fullUrl = GOOGLE_CONVERTER + "?address=" + address + "&key=" + GOOGLE_KEY;
                new getlongAndLat().execute(fullUrl);
                textTextView.setText(latitude + "");
                //Log.e("TAG", latitude + " " + longitude);
              //  getLoaderManager().initLoader(LOADER_ID, null, MainActivity.this);
            }
        });
    }

    @Override
    public android.content.Loader<Weather> onCreateLoader(int id, Bundle args) {
        return new WeatherAsyncTaskLoader(this, latitude, longitude);
    }

    @Override
    public void onLoadFinished(android.content.Loader<Weather> loader, Weather data) {

    }

    @Override
    public void onLoaderReset(android.content.Loader<Weather> loader) {

    }


    public class getlongAndLat extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {
            HttpURLConnection connection = null;
            InputStream inputStream = null;
            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();
                Log.e("TAG", connection.getResponseCode() + "");

                if (connection.getResponseCode() == 200) {
                    inputStream = connection.getInputStream();
                    jsonResponse = readFromStream(inputStream);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        //trouble closing input stream
                        e.printStackTrace();
                    }
                }
            }
            extractJsonResponse(jsonResponse);
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            latitudeTextView.setText(latitude + "");
            longitudeTextView.setText(longitude + "");
            super.onPostExecute(s);
        }
    }

    private void extractJsonResponse(String jsonResponse) {
        try {
            JSONObject rootJsonObject = new JSONObject(jsonResponse);
            JSONArray nodeResultsArray = rootJsonObject.getJSONArray("results");
            JSONObject nodeFirstObject = nodeResultsArray.getJSONObject(0);
            JSONObject nodeGeometryObject = nodeFirstObject.getJSONObject("geometry");
            JSONObject nodeLocation = nodeGeometryObject.getJSONObject("location");

            latitude = nodeLocation.getDouble("lat");
            longitude = nodeLocation.getDouble("lng");

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private String readFromStream(InputStream inputStream) throws IOException{
        StringBuilder output = new StringBuilder();
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null) {
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();

    }

}

在代碼doInBackground()中,您要在return語句之前調用extractJsonResponse()方法。 在extractJsonResponse()中,您變得越來越長,並將其設置為代碼中提到的Global變量

JSONObject nodeLocation = nodeGeometryObject.getJSONObject("location");

    latitude = nodeLocation.getDouble("lat");
    longitude = nodeLocation.getDouble("lng");

我確定您是從Json對象獲取那些零值的。 您需要在最后驗證此內容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM