Download Android-Chapter14-JSON Encoding

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CIS 470
Quick Notes: Android & JSON encoding
GOALS: Encode/Decode locally. Access a server to read a file holding JSON encoded data, decode, show results.
package csu.matos;
import
import
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.os.Handler;
android.os.Message;
android.view.View;
android.widget.ProgressBar;
android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import
import
import
import
java.lang.reflect.Type;
java.net.URL;
java.util.ArrayList;
java.util.Scanner;
public class MainActivity extends Activity {
ProgressBar progressBar;
TextView txtMsg;
Gson gson;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
txtMsg.append("\n" + (String) msg.obj);
progressBar.setVisibility(View.INVISIBLE);
}
};
Thread slowWorkerThread = new Thread() {
@Override
public void run() {
super.run();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
//a little delay here (dramatic effect)...
}
String text;
//PART2: JSON Encoding
Person person0 = new Person("Daenerys", 20);
// convert Person (Java object) to JSON format
// display it as a JSON formatted string
Gson gson = new Gson();
String json = gson.toJson(person0);
text = "\n(LOCAL)Json serialized object:\n" + json;
handler.sendMessage(handler.obtainMessage(1, text));
// create a few more Person objects
Person person1 = new Person("Arya", 12);
Person person2 = new Person("Cersei", 35);
// place all Person objects in an ArrayList
ArrayList<Person> lstPerson = new ArrayList<>();
lstPerson.add(person0);
lstPerson.add(person1);
lstPerson.add(person2);
// convert Java ArrayList to JSON string
String jsonList = gson.toJson(lstPerson);
text = "\n(LOCAL)Json serialized list:\n" + jsonList;
handler.sendMessage(handler.obtainMessage(1, text));
// use Java reflection to find the list's type
Type arrayPersonType = new TypeToken<ArrayList<Person>>(){}.getType();
// deserialize JSON string representing the list of objects
ArrayList<Person> lst2 = gson.fromJson(jsonList, arrayPersonType);
// explore the Java ArrayList
for(int i=0; i<lst2.size(); i++){
Person p = lst2.get(i);
text = "\n" + i + "-(LOCAL) Person From Deserialized List:\n" + p.toString()
+ "\n
name:" + p.getName()
+ "\n
age: " + p.getAge();
handler.sendMessage(handler.obtainMessage(1, text));
}
try {
//URL url = new URL("http://informatos.org/westeros_ladies.txt");
//URL url = new URL("http://192.168.1.70/westeros/westeros_ladies.txt");
//URL url = new URL("http://informatos.org/westeros_ladies.txt");
//URL url = new URL("http://192.168.1.70/westeros/westeros_ladies.txt");
//--------------------------------------------------------------------------------URL url = new URL("http://grail.csuohio.edu/~matos/gameofthrones/westeros_ladies.txt");
//URL url = new URL("http://grail.cba.csuohio.edu/~matos/gameofthrones/getPersonNoSql.php");
URL url = new
URL("http://grail.cba.csuohio.edu/~matos/gameofthrones/getPersonNoSql.php?castle=winterfell");
//URL url = new
URL("http://grail.cba.csuohio.edu/~matos/gameofthrones/getPersonNoSql.php?castle=dragonstone");
//URL url = new
URL("http://grail.cba.csuohio.edu/~matos/gameofthrones/getPersonNoSql.php?castle=kings_landing");
// -------------------------------------------------------------------------------// next statement reads the ENTIRE file (delimiter \A matches All input)
// String text = new Scanner( url.openStream() ).useDelimiter("\\A").next();
// ------------------------------------------------------------------------// scanning a remote file one line at the time
text ="";
Scanner scanner = new Scanner(url.openStream());
while (scanner.hasNext()) {
text += scanner.nextLine() + "\n";
}
handler.sendMessage(handler.obtainMessage(1, "\nFROM REMOTE SERVER\n" + url.toString()));
handler.sendMessage(handler.obtainMessage(1, "\nREMOTE JSON STR\n" + text));
// use Java reflection to find the list's type
Type arrayPersonType3 = new TypeToken<ArrayList<Person>>(){}.getType();
// deserialize JSON string representing the list of objects
ArrayList<Person> lst3 = gson.fromJson(jsonList, arrayPersonType3);
// explore the Java ArrayList
for(int i=0; i<lst3.size(); i++){
Person p = lst3.get(i);
text = "\n" + i + "-(REMOTE)Person From Deserialized List:\n" + p.toString()
+ "\n
name:" + p.getName()
+ "\n
age: " + p.getAge();
handler.sendMessage(handler.obtainMessage(1, text));
}
} catch (java.io.IOException e) {
handler.sendMessage(handler.obtainMessage(1, "ERROR: " + e.getMessage()));
}
}//run
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtMsg = (TextView) findViewById(R.id.txtMsg);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
slowWorkerThread.start();
}//onCreate
}
Person class
package csu.matos;
public class Person {
private String name;
private Integer age;
public Person (String name, Integer age) {
this.name = name; this.age = age;
}
public Person() {
this.name = "n.a.";
this.age=0;
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String toString() {
return "PERSON(POJO)[ name:" + name + " age:" + age + "]";
}
}
Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/scrollView">
<TextView
android:id="@+id/txtMsg"
android:text="Hello World!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</ScrollView>
</LinearLayout>
Manifest
Remember to add permission clause
<uses-permission android:name="android.permission.INTERNET" />
GSON API
Use Windows-Explorer. Place a copy of the latest gson jar in the application’s app/libs
Your Gradle Scripts/build.gradle(Module:app) file needs to be modified to include references to the GSON API. In our example we have:
...
dependencies {
compile 'com.android.support:support-v4:19.1.0'
compile files('libs/gson-2.2.4.jar')
}
PHP Code to create “westerosLadies.txt” file
<?php
//make disk file holding a
$person0 = array('name' =>
$person1 = array('name' =>
$person2 = array('name' =>
JSON encoded list
'Daenerys', 'age'
'Arya',
'age'
'Cersei',
'age'
of
=>
=>
=>
Person objects
20);
12);
35);
$people = array($person0, $person1, $person2);
$jsondata = json_encode($people);
echo "<p>JSON Encoded Data <br>" . $jsondata;
$myfile = fopen("westerosLadiesJson.txt", "w") or die("Unable to open file!");
fwrite($myfile, $jsondata);
fclose($myfile);
echo '<br>' . 'Done writing file...';
?>
PHP code: getPersonNoSql.php (return a JSON string with heroes listed by castle)
<?php
// METHOD: getPeopleNoSql.php
// retrieves people by castle location (eg.?castle=winterfell)
// data comes from comes from associative arrays (noSql)
// --------------------------------------------------------------// create anonymous Person-like objects
$person0 = array('name' => 'Cersei Lannister', 'age' => 40);
$person1 = array('name' => 'Tiryion Lannister', 'age' => 30);
$person2 = array('name' => 'Arya Stark', 'age' => 11);
$person3 = array('name' => 'Jon Snow', 'age' => 20);
$person4 = array('name' => 'Hodor', 'age' => 40);
$person5 = array('name' => 'Daenerys Targaryen', 'age' => 18);
// create lists of people-by-HomeCastle
$winterfelPeople = array($person2, $person3,$person4);
$kingsLandingPeople = array($person0, $person1);
$dragonstonePeople = array($person5);
$people = array($person0, $person1, $person2, $person3,$person4, $person5);
// select what list to return (only winterfel in this example)
if( strtolower($_REQUEST['castle']) == 'winterfell' )
$people = $winterfelPeople;
else if ( strtolower($_REQUEST['castle']) == 'kings_landing' )
$people = $kingsLandingPeople;
else if ( strtolower($_REQUEST['castle']) == 'dragonstone' )
$people = $dragonstonePeople;
// respond with JSON-encoded list
echo json_encode($people);
?>
Related documents