AsyncTask and HttpUrlConnection Sample in Android

The sample code below shows you how to use AsyncTask for network tasks (downloading weather data). To make this sample code running on android, you just have to create two files, an activity class MainActivity.java and a layout file for this activity. In the layout, there will be only two views, a TextView and a Button. In the main activity, there will be some initialization in in the onCreate method for the TextView and Button, plus the AsyncTask inner class for downloading the weather data through HttoURLConnection.

activity_main.xml, replace the code with the following if it’s already created for you when you created the project in Android Studio, otherwise just create this file in the layout folder uner res.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.peng.httpurlconnection.MainActivity">
    <Button
        android:id="@+id/btn_fetch_weather"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Fetch Weather"/>
    <TextView
        android:id="@+id/tv_weather_json"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn_fetch_weather"
        android:maxLines = "100"
        android:scrollbars = "vertical"/>
</RelativeLayout>

MainActivity.java, replace the code with the following if it’s already created for you when you created the project in Android Studio, otherwise just create this file your java package.

public class MainActivity extends AppCompatActivity {

    TextView tvWeatherJson;
    Button  btnFetchWeather;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvWeatherJson = (TextView) findViewById(R.id.tv_weather_json);
        btnFetchWeather = (Button) findViewById(R.id.btn_fetch_weather);
        btnFetchWeather.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new FetchWeatherData().execute();
            }
        });
    }


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

        @Override
        protected String doInBackground(Void... params) {
            // These two need to be declared outside the try/catch
            // so that they can be closed in the finally block.
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string.
            String forecastJsonStr = null;

            try {
                // Construct the URL for the OpenWeatherMap query
                // Possible parameters are avaiable at OWM's forecast API page, at
                // http://openweathermap.org/API#forecast
                URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7&appid=2de143494c0b295cca9337e1e96b00e0");

                // Create the request to OpenWeatherMap, and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                // Read the input stream into a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                    // But it does make debugging a *lot* easier if you print out the completed
                    // buffer for debugging.
                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    // Stream was empty.  No point in parsing.
                    return null;
                }
                forecastJsonStr = buffer.toString();
                return forecastJsonStr;
            } catch (IOException e) {
                Log.e("PlaceholderFragment", "Error ", e);
                // If the code didn't successfully get the weather data, there's no point in attemping
                // to parse it.
                return null;
            } finally{
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e("PlaceholderFragment", "Error closing stream", e);
                    }
                }
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            tvWeatherJson.setText(s);
            Log.i("json", s);
        }
    }
}

Make sure to import the classes when you see Cannot Resove Symbol Errors.

Reference:

Search within Codexpedia

Custom Search

Search the entire web

Custom Search