繁体   English   中英

使用带有变量的aSyncTask

[英]using aSyncTask with variables

我正在制作一个简单的天气应用程序,我在通过aSyncTask读取变量时遇到问题。 我是Andorid编程的初学者,所以我需要了解。 因此,我想将从位置选择器中选择的变量“纬度”和“经度”放入asyncTask.execute(“ Latitude”,“ Longitude”)并刷新屏幕以显示新位置的天气。 现在它可以正常工作了,但是我注意到,当我将坐标而不是变量中的代码放入代码中时(例如asyncTask.execute(“ 52.2296756”,“ 38,3435546”),然后在使用Place Picker之后出现了该位置的天气。还添加了外包以检查此变量,它们看起来还可以。

  public class MainActivity extends AppCompatActivity {


        TextView cityField, detailsField, currentTemperatureField, 
        humidity_field, pressure_field, weatherIcon, updatedField;
        ImageView mPlacePicker;
        Typeface weatherFont;
        int PLACE_PICKER_REQUEST = 1;
        String latitude;
        String longitude;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            getSupportActionBar().hide();
            setContentView(R.layout.activity_main);
            mPlacePicker = (ImageView) findViewById(R.id.place_picker);
            mPlacePicker.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    PlacePicker.IntentBuilder builder = new 
                    PlacePicker.IntentBuilder();
                    Intent intent;
                    try {
                        intent = builder.build(MainActivity.this);
                        startActivityForResult(intent, PLACE_PICKER_REQUEST);
                    } catch (GooglePlayServicesRepairableException e) {
                        e.printStackTrace();
                    } catch (GooglePlayServicesNotAvailableException e) {
                        e.printStackTrace();
                    }
                }
            });

        }

        public void onActivityResult(int requestCode, int resultCode, Intent 
        data) {
            if (requestCode == PLACE_PICKER_REQUEST) {
                if (resultCode == RESULT_OK) {
                    Place place = PlacePicker.getPlace(this, data);
                    String address = String.format("Place %s", place.getAddress());
                    Toast.makeText(this, address, Toast.LENGTH_LONG).show();
                    LatLng latLng = place.getLatLng();
                    latitude = String.valueOf(latLng.latitude);
                    longitude = String.valueOf(latLng.longitude);
                    //System.out.println(latitude);
                    //System.out.println(longitude);
                }
            }
            weatherFont = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/weathericons-regular-webfont.ttf");

            cityField = (TextView) findViewById(R.id.city_field);
            updatedField = (TextView) findViewById(R.id.updated_field);
            detailsField = (TextView) findViewById(R.id.details_field);
            currentTemperatureField = (TextView) findViewById(R.id.current_temperature_field);
            humidity_field = (TextView) findViewById(R.id.humidity_field);
            pressure_field = (TextView) findViewById(R.id.pressure_field);
            weatherIcon = (TextView) findViewById(R.id.weather_icon);
            weatherIcon.setTypeface(weatherFont);
            mPlacePicker = (ImageView) findViewById(place_picker);


            Function.placeIdTask asyncTask = new Function.placeIdTask(new Function.AsyncResponse() {
                public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {

                    cityField.setText(weather_city);
                    updatedField.setText(weather_updatedOn);
                    detailsField.setText(weather_description);
                    currentTemperatureField.setText(weather_temperature);
                    humidity_field.setText("Humidity: " + weather_humidity);
                    pressure_field.setText("Pressure: " + weather_pressure);
                    weatherIcon.setText(Html.fromHtml(weather_iconText));

                }
            });
            System.out.println('"' + latitude + '"');
            System.out.println('"' + longitude + '"');
            asyncTask.execute('"' + latitude + '"', '"' + longitude + '"'); //  asyncTask.execute("Latitude", "Longitude")
        }


    }

这是doInBackground的第二类

    public class Function {



    private static final String OPEN_WEATHER_MAP_URL =
            "http://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&units=metric";

    private static final String OPEN_WEATHER_MAP_API = "3b30fbc239f6a1ed664220635330aa46";

    public static String setWeatherIcon(int actualId, long sunrise, long sunset){
        int id = actualId / 100;
        String icon = "";
        if(actualId == 800){
            long currentTime = new Date().getTime();
            if(currentTime>=sunrise && currentTime<sunset) {
                icon = "&#xf00d;";
            } else {
                icon = "&#xf02e;";
            }
        } else {
            switch(id) {
                case 2 : icon = "&#xf01e;";
                    break;
                case 3 : icon = "&#xf01c;";
                    break;
                case 7 : icon = "&#xf014;";
                    break;
                case 8 : icon = "&#xf013;";
                    break;
                case 6 : icon = "&#xf01b;";
                    break;
                case 5 : icon = "&#xf019;";
                    break;
            }
        }
        return icon;
    }



    public interface AsyncResponse {

        void processFinish(String output1, String output2, String output3, String output4, String output5, String output6, String output7, String output8);
    }


    public static class placeIdTask extends AsyncTask<String, Void, JSONObject> {

        public AsyncResponse delegate = null;//Call back interface

        public placeIdTask(AsyncResponse asyncResponse) {
            delegate = asyncResponse;//Assigning call back interfacethrough constructor
        }

        @Override
        protected JSONObject doInBackground(String... params) {

            JSONObject jsonWeather = null;
            try {
                jsonWeather = getWeatherJSON(params[0], params[1]);
            } catch (Exception e) {
                Log.d("Error", "Cannot process JSON results", e);
            }


            return jsonWeather;
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            try {
                if(json != null){
                    JSONObject details = json.getJSONArray("weather").getJSONObject(0);
                    JSONObject main = json.getJSONObject("main");
                    DateFormat df = DateFormat.getDateTimeInstance();


                    String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country");
                    String description = details.getString("description").toUpperCase(Locale.US);
                    String temperature = String.format("%.2f", main.getDouble("temp"))+ "°";
                    String humidity = main.getString("humidity") + "%";
                    String pressure = main.getString("pressure") + " hPa";
                    String updatedOn = df.format(new Date(json.getLong("dt")*1000));
                    String iconText = setWeatherIcon(details.getInt("id"),
                            json.getJSONObject("sys").getLong("sunrise") * 1000,
                            json.getJSONObject("sys").getLong("sunset") * 1000);

                    delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn, iconText, ""+ (json.getJSONObject("sys").getLong("sunrise") * 1000));

                }
            } catch (JSONException e) {
                //Log.e(LOG_TAG, "Cannot process JSON results", e);
            }

        }

    }

    public static JSONObject getWeatherJSON(String lat, String lon){
        try {
            URL url = new URL(String.format(OPEN_WEATHER_MAP_URL, lat, lon));
            HttpURLConnection connection =
                    (HttpURLConnection)url.openConnection();

            connection.addRequestProperty("x-api-key", OPEN_WEATHER_MAP_API);

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

            StringBuffer json = new StringBuffer(1024);
            String tmp="";
            while((tmp=reader.readLine())!=null)
                json.append(tmp).append("\n");
            reader.close();

            JSONObject data = new JSONObject(json.toString());

            // This value will be 404 if the request was not
            // successful
            if(data.getInt("cod") != 200){
                return null;
            }

            return data;
        }catch(Exception e){
            return null;
        }
    }
}

您可以为类AsyncTask使用构造函数

像这样的东西:

class placeIdTask extends AsynckTask<Void,Void,Void>{
    Double latitude;
    Double longitude;
public placeIdTask(Double latitude, Double longitude){

this.latitude = latitude;
this.longitude=longitude;
}

...//implement doInbackground using latitude and longitude 

}

或者只是像这样更改通用CLass的类型

class placeIdTask extends AsynckTask<Double,Void,Void>{
   @Override
        protected Void doInBackground(Double... arg0) {
       Double latitude = arg0[0];
       Double longitude = arg0[1];
         ...   }
... }

我建议你使用Double而不是String

希望对你有帮助

    //Add async task

    private class SampleAsyncTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        // this might take a while ...
        // Do your task over here
        // Use parameterlike this
        latitude=params[0];
        longitude=params[1];

        return "Success";

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
    }
}
//Call asyc task
new SampleAsyncTask().execute(String.valueOf(latitude),String.valueOf(longitude));

希望这对您有所帮助。 快乐编码

删除多余的"" 你不需要那些

asyncTask.execute(latitude,longitude);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM