[JAVA] Android development-WEB access (GET) Try to get data by communicating with the outside. ~

Introduction

Hello. I'm Wataku, a server-side programmer who is studying programming at a certain school. : relaxed: Let's develop Android this time as well. This time I would like to connect to an external network with Android and acquire data.

Target person

--A person who can write Java reasonably well. --A person who can do so in Android development.

Web access overview

  1. Write the source code for http access in the app. → Most of the response contents are JSON or XML.
  2. Use the screen component WebView in the screen. → The content of the response is HTML in principle.

Asynchronous processing

For things that take a long time to process, such as Web access, and for those that are likely to cause unexpected errors, processing (asynchronous processing) is performed in a thread different from the main processing. AsyncTask Of the asynchronous processing of Android, it is convenient to use the AsyucTask class when interacting with the UI thread.

1. How to use AsyncTask

  1. Create a class that inherits * Asynuc Task. * → It is convenient to create it as a private member class of the activity class.

    • Describe the process you want to perform asynchronously in the method doInBackground (). * → This method is an abstract method of Asyuc Task, so it must be overridden.
    • New this class in the activity and execute the execute () method *
private class class name extends AsyucTask< ... > {
  ...
  @Override
  public String doInBackground( String ... params ) {    
     //Describe asynchronous processing here
  }
}
afterwards
Class name Variable name=new class name(); 
Variable name.execute( ... );

2. Other methods

In addition to doInBackground (), AsyucTask has the following methods. Since these methods are executed on the UI thread, it is possible to operate screen parts.

-** onPostExecute () : Executed after the end of doInBackground (). - onPreExecute () : Executed before the start of doInBackground (). - onProgressUpdate () **: Executed when publishProgress () is called in doInBackground ().

In addition, when cancel () is called from the activity, onCancelled () is executed after doInBackground () is completed.

3. Generics

When creating a child class of AsyucTask, you need to write three types in the generics. → * Describe Void for those that do not require type specification. *

...Class name extends AsyucTask<①String, ②Void, ③String> {

①Params

execute (). The argument type of doInBackground (). → The argument of execute () is passed as it is as the argument of doInBackground ()

②Progress

publishProgress (). The argument type of onProgressUpdate (). → The argument of publishProgress () is passed as it is as the argument of onProgressUpdate ().

③Result

The return value of doInBackground () and the argument type of onPostExecute (). OnCanceled (). → The return value of doInBackground () is passed as it is as an argument of onPostExecute () and onCanceled ().

http access

Give internet connection permission

src/main/AndroidManifest.xml


<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Connect to the internet

Use the ** HttpURLConnection ** object.

Set the URL string.

URL url = new URL("URL string");

Get a connection

con = (HttpURLConnection) url.openConnection();

You can get the HttpURLConnection object (connection) by executing the ** URL # openConnection () ** method on the URL object that has the access destination URL information.

Access method settings

Use ** setRequestMethod () **.

con.setRequestMethod("GET")

Actual internet connection

Use ** URLConnection # connect () **.

con.connect();

Disconnection

Use ** disconnect () **. After the processing is completed, it is necessary to explicitly disconnect the connection so as not to leave an unnecessary connection.

con.disconnect()

Sample code for http request

private class class name extends AsyncTask<String, Void, String> {
        private static final String DEBUG_TAG = "tag";

        @Override
        public String doInBackground(String... params) {
            String urlStr = params[0];
            String id = params[1];

            HttpURLConnection con = null;
            InputStream is = null;
            String result = "";

            try {
                URL url = new URL(urlStr);
                con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.connect();
                is = con.getInputStream();

                result = is2String(is);
            }
            catch(MalformedURLException ex) {
                Log.e(DEBUG_TAG, "URL conversion failure", ex);
            }
            catch(IOException ex) {
                Log.e(DEBUG_TAG, "Communication failure", ex);
            }
            finally {
                if (con != null) {
                    con.disconnect();
                }
                if (is != null) {
                    try {
                        is.close();
                    }
                    catch (IOException ex) {
                        Log.e(DEBUG_TAG, "Input Stream release failure", ex);
                    }
                }
            }
            return result;
        }

        private String is2String(InputStream is) throws IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sb = new StringBuffer();
            char[] b = new char[1024];
            int line;
            while(0 <= (line = reader.read(b))) {
                sb.append(b, 0, line);
            }
            return sb.toString();
        }
}

*** InputStream ** is a class for reading bytes.

Handling of JSON

Use the ** JSONObject ** class. Specify "JSON character string" as an argument.

After that, while performing the following operations, get the target JSONObject and get the value with getString (...).

--GetJSONObject (...) to get the JSONObject directly below --GetJSONArray (...) to get the JSONArray (JSON array) directly below --GetJSONObject (...) to get the specified JSONObject of JSONArray

Sample code for JSON processing

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


 @Override
 public void onPostExecute(String result) {
            String title = "";
            String text = "";
            String dateLabel = "";
            String telop = "";
            try {
                JSONObject rootJSON = new JSONObject(result);
                title = rootJSON.getString("title");
                JSONObject descriptionJSON = rootJSON.getJSONObject("description");
                text = descriptionJSON.getString("text");
                JSONArray forecasts = rootJSON.getJSONArray("forecasts");
                JSONObject forecastNow = forecasts.getJSONObject(0);
                dateLabel = forecastNow.getString("dateLabel");
                telop = forecastNow.getString("telop");
            }
            catch(JSONException ex) {
                Log.e(DEBUG_TAG, "JSON parsing failed", ex);
            }

   }
}

that's all. If you have any suggestions such as something wrong, please contact us. Thank you for reading to the end.

Recommended Posts

Android development-WEB access (GET) Try to get data by communicating with the outside. ~
Android development-WEB access (POST) Try to communicate with the outside and send data. ~
Try to get redmine API key with ruby
Get data with api created by curl command
Try to summarize the common layout with rails
Try to save the data that can be read by JavaFX as PNG
Going back to the beginning and getting started with Java ① Data types and access modifiers
I tried to get started with Spring Data JPA
Communicate from the outside to the container launched by docker-compose
[Android] How to get the setting language of the terminal
Access Web API on Android with Get and process Json (Java for the time being)
How to take a screenshot with the Android Studio emulator
Get the URL issued by ngrok with the Docker expose plugin
[MT] Specify the article category from Android with Data API
How to get values in real time with TextWatcher (Android)
[MT] Specify the article category from Android with Data API
I want to distinct the duplicated data with has_many through
Now is the time to get started with the Stream API
Read the data of Shizuoka point cloud DB with Java and try to detect the tree height.
Try to imitate the idea of a two-dimensional array with a one-dimensional array
When requested access to the resource is denied when pushing with Docker
Run logstash with Docker and try uploading data to Elastic Cloud
[Android] I want to get the listener from the button in ListView