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.
--A person who can write Java reasonably well. --A person who can do so in Android development.
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.
Create a class that inherits * Asynuc Task. * → It is convenient to create it as a private member class of the activity class.
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( ... );
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.
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 ().
src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Use the ** HttpURLConnection ** object.
URL url = new URL("URL string");
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.
Use ** setRequestMethod () **.
con.setRequestMethod("GET")
Use ** URLConnection # connect () **.
con.connect();
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()
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.
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
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