Android 学习笔记Android开发Android技术知识

Json File

2017-08-17  本文已影响25人  mlya

Json file

Project address: QuakeReport-github

About this course

Build a earthquake app.

  1. Where to find the earthquake data.
  2. API: application programming interface.
  3. Earthquake data from the USGS

How to describe earthquake

magnitude, epicenter, depth, date, and so on.

Json: packaged data

USGS website

GEOJson Summary Format

API documentation

URL format

In the API Documentation we can see that the URL format: https://earthquake.usgs.gov/fdsnws/event/1/[METHOD[?PARAMETERS]]. There are many Methods we can use. For example, we use query method to submit a data request. query method has many parameters to indicate the query time and other search condition.

This will return a GEOJson file.

Json format

GEOJson Summary Format

Display Earthquake information

After import the code from github, we do some changes. The app will looks like below.

Add Earthquake class

We need a class to store the information of an earthquake, including magnitude, Location and date.

// a float number to store the magnitude.
    private float mMagnitude;
    // a String value to store the location
    private String mLocation;
    // a String value to store the date in the format "Feb 2, 2016"
    private String mDate;

In this class, There should be a constructor to set the value of the three variables.

/**
     *
     * @param magnitude the magnitude of the earthquake
     * @param location the location of the earthquake, maybe a city name
     * @param date the date of the earthquake in the format "Feb 2, 2016"
     */
    public Earthquake(float magnitude, String location, String date) {
        mMagnitude = magnitude;
        mLocation = location;
        mDate = date;
    }

Then, We have the getter method to get the value.

 /**
     *
     * @return return magnitude
     */
    public float getmMagnitude() {
        return mMagnitude;
    }

    /**
     *
     * @return return date
     */
    public String getmDate() {
        return mDate;
    }

    /**
     *
     * @return return location
     */
    public String getmLocation() {
        return mLocation;
    }

Add EarthquakeAdapter

Then, we need the Adapter to show the information on the screen.

create the file EarthquakeAdapter.java.

Constructor

We use our custom constructor because we use our list_item view.

/**
     * This is our custom constructor,
     * The context is used to inflate the layout file,
     * and the list is the data we want to populate into the lists.
     * @param context The current context. Used to inflate the layout file.
     * @param earthquakes A List of Earthquake objects to display in a list
     */
    public EarthquakeAdapter(Activity context, ArrayList<Earthquake> earthquakes){
        // the second parameter is 0 to indicate we will use our custom list item view to show.
        super(context, 0, earthquakes);
    }

getView()

  1. Inflate the view
  2. get data using getItem(position)
  3. set data

Json

GEOJson is a special flavor of JSON.

Json: JavaScript Object Notation

Brace, Key Value pairing

Parsing Json in Android

Class JSONObject

Example:
Json file:

{
    "candies":[
        {
            "name":"Jelly Beans",
            "count":10
        }
    ]
}

Android code:

String candyJson = "{\"candies\":[{\"name\":\"Jelly Beans\",\"count\":10}]}";

JSONObject root = new JSONObject(candyJson);

JSONArray candiesArray = root.getJSONArray("candies");

JSONObject firstCandy = candiesArray.getJSONObject(0);

String name = firstCandy.getString("name");
int count = firstCandy.getInt("count");

Android provides four different classes to manipulate JSON data. JSONArray, JSONObject, JSONStringer and JSONTokenizer.

JSON Elements

Str.No Component & description
1 Array: [] <p>In a JSON file, square bracket [] represents a JSON array
2 Objects: {} <p>In a JSON file, curly bracket {} represents a JSON object
3 Key <p>A JSON object contains a key that is just a string. Pairs of key/value make up JSON object.
4 Value <p>Each key has a value that could be string, integer or double, etc.

JSON Parsing

For parsing a JSON object, we will create an object of class JSONObject and specify a string containing JSON data to it.

String in;
JSONObject reader = new JSONObject(in);
Str.No Method & description
1 get(String name) <p>This method just Returns the value but in the format of Object type.
2 getBoolean(String name) <p>This method returns the boolean value specified by the key.
3 getDouble(String name) <p>This method returns the double value specified by the key.
4 getInt(String name) <p>This method returns the integer value specified by the key
5 getLong(String name) <p>This method returns the long value specified by the key
6 length() <p>This method returns the number of name/value mappings in this object.
7 names() <p>This method returns an array containing the string names in this object.

QuakeUtil.java

We create a java class QuakeUtil.java to do something for quake data.

Constructor

This util class is only directly accessed from the class name, so we need the private constructor. There will be no object.

/**
     * Create a private constructor because no one should ever create a {@link QueryUtils} object.
     * This class is only meant to hold static variables and methods, which can be accessed
     * directly from the class name QueryUtils (and an object instance of QueryUtils is not needed).
     */
    private QueryUtils() {
    }
extractEarthquakes()

This method will Get the information from JSON and add the item to an ArrayList<Earthquake>.

/**
     * Return a list of {@link Earthquake} objects that has been built up from
     * parsing a JSON response.
     */
    public static ArrayList<Earthquake> extractEarthquakes() {

        // Create an empty ArrayList that we can start adding earthquakes to
        ArrayList<Earthquake> earthquakes = new ArrayList<>();

        // Try to parse the SAMPLE_JSON_RESPONSE. If there's a problem with the way the JSON
        // is formatted, a JSONException exception object will be thrown.
        // Catch the exception so the app doesn't crash, and print the error message to the logs.
        try {

            // Parse the response given by the SAMPLE_JSON_RESPONSE string and
            // build up a list of Earthquake objects with the corresponding data.
            JSONObject root = new JSONObject(SAMPLE_JSON_RESPONSE);
            JSONArray features = root.getJSONArray("features");

            for (int i = 0; i < features.length(); i++) {
                JSONObject earthquake = features.getJSONObject(i);
                JSONObject properties = earthquake.getJSONObject("properties");
                double mag = properties.getDouble("mag");
                String place = properties.getString("place");
                long time = properties.getLong("time");
                earthquakes.add(new Earthquake(Double.toString(mag), place, Long.toString(time)));
            }

        } catch (JSONException e) {
            // If an error is thrown when executing any of the above statements in the "try" block,
            // catch the exception here, so the app doesn't crash. Print a log message
            // with the message from the exception.
            Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
        }

        // Return the list of earthquakes
        return earthquakes;
    }
Show Earthquake date and time

In our app now, it shows the Unix time. We can use class SimpleDateFormat and Date to convert the time from Unix time to what we need.

Time format: yyyy-MM-dd HH:mm:ss:
y means year. yyyy: 2016
M means mounth. MM: 03
d means day. dd: 10
H hour
m minute
s second

  1. Create a Date class.
  2. Use class SimpleDateFormat to create a date formatter.
  3. Use this date formatter to format the Date object and output a String.
// time in ms format
long timeInMilliseconds = 1454124312220L;
// create Date object
Date dateObject = new Date(timeInMilliseconds);
// create the SimpleDateFormat object dateFormatter
SimpleDateFormat dateFormatter = new SimpleDateFormat("MMM DD, yyyy");
// Format the time
String dateToDisplay = dateFormatter.format(dateObject);
split the location and offset

The location we can get from JSON file is like "64km NNE of Tomatlan, Mexico" or "Pacific-AntarcticRidge"

We need to split the String to two part. "64km NNE of" and "Tomatlan, Mexico"

we use the method split of String.

private static final String LOCATION_SEPARATOR = "of";

...

String[] split_location = location.split("(?<=" + LOCATION_SEPARATOR + ")");

We can judge if the String contains LOCATION_SEPARATOR to decide whether the String can be split.

if (location.contains(LOCATION_SEPARATOR)) {
            String[] split_location = location.split("(?<=" + LOCATION_SEPARATOR + ")");
            locationOffsetToDisplay = split_location[0];
            locationToDisplay = split_location[1];
        } else {
            locationOffsetToDisplay = getContext().getString(R.string.near_the);
            locationToDisplay = location;
        }
Format the mag number

DecimalFormat

0 表示数字的占位符、# 也表示 数字,但是不显示前导零

上一篇下一篇

猜你喜欢

热点阅读