Android, threads, AsyncTask, HTTP, Gson
ANR
"Has stopped"
LOGG & si fra til bruker!
new Thread(new Runnable() {
public void run() {
// code to run in background
}
}).start();
// inside other thread
Activity.runOnUiThread(new Runnable() {
public void run() {
// code to run on UI thread
}
});new AsyncTask<Params, Progress, Result>() {
@Override
protected void onPreExecute() {
// Stuff to do on UI thread before starting
}
@Override
protected <Result> doInBackground(
<Params>... params
) {
// Perform a long task, like an HTTP request
return <Result>;
}
@Override
protected void onPostExecute(
<Result> result
) {
// Stuff to do on UI thread after finishing
}
}Veldig vanlig case for apps:
HttpURLConnection connection = (HttpURLConnection)
new URL("http://a.page.xyz/whatever").openConnection();
InputStream in = connection.getInputStream();
Scanner scanner = new Scanner(in);
String body = "";
while (scanner.hasNextLine()) {
body += scanner.nextLine();
}
// body = data from server as Stringjava.net.*
(Quick demo)
<uses-permission
android:name="android.permission.INTERNET"/>
public class JustGetSomethingActivity extends Activity {
private TextView resultTextView;
// onCreate sets ^^^, calls vvv
private void downloadAndDisplayData() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(final Void... params) {
try {
HttpURLConnection connection =
(HttpURLConnection) new URL("https://google.com").openConnection();
return inputStreamToString(connection.getInputStream()); // made up method
} catch (IOException e) {
throw new RuntimeException(e); // I'm lazy
}
}
@Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
resultTextView.setText(result); // update the TextView
}
}.execute();
}
}
(les: AsyncTask)
// Arrays
[0, 1, 2]
["Hello", "world"]
// Objects
{
"key": "value",
"anotherKey", "anotherValue"
}
// Object with array
{
"name": "Liam",
"modules": [
"Physics",
"Maths"
]
}
// Array of objects
[
{ "name": "Liam" },
{ "name": "Martin" }
]"Fun"facts:
// build.gradle
dependencies {
// ...
compile 'com.google.code.gson:gson:2.6.2'
}// Serialization
Gson gson = new Gson();
gson.toJson(1); // ==> 1
gson.toJson("abcd"); // ==> "abcd"
// Deserialization
int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);// Deserialization
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);