Android pri (25)

Android Basics: Networking

Lesson 1: JSON Parsing

API

JSON

  • JSON格式的数据是以大括号来开头的,然后中间是以键值对的方式来进行的。
  • Markdown
  • “size”这个对应的键值对是JSON primitive(也就是JSON的基本数据,什么整数啊,double啊之类的),然后”wide”这个对应的是boolean。”country-of-origin”对应的也是primitive的类型。然后”style”对应的是一个JSON Object的类型,因为里面还可以嵌套很多东西,然后”categories”对应的是一个数组,里面可以放很多值。

Traversing JSON Data

  • 这一部分讲的是怎样遍历JSON数据类型并从中取出我们需要的数据。其实就是相当于遍历JSON树,一点一点走下去就好了。
  • Markdown

Parsing JSON In Android

日期转化

  • 用什么DecimalFormat,和java差不多的。

Switch

  • 这个比较好懂,但是我这里想提一点就是:
  • Markdown
  • 如果case 3中没有break的话,那么它会直接进入到case 4中去,所以当spiceLevel是3时,flavor是”very hot”。
  • switch语句无法接受双精度值。

设置背景颜色

  • 这里的背景颜色是colors.xml文件中的颜色,这里有一点不同,就是当我们找到了对应颜色资源的id之后,我们仍需进行下一步,就是将其转化为实际的颜色值。
  • 切记:颜色资源 ID 仅指向我们定义的资源,而非颜色的 值。
  • 可以调用 ContextCompat getColor() 以将颜色资源 ID 转换为 实际整数颜色值,并将结果作为 getMagnitudeColor() 辅助方法的返回值返回。
  • 代码如下: ContextCompat.getColor(getContext(), magnitudeColorResourceId);

layout_gravity=”end”

  • 这个代表的意思是将当前的对象放到该容器的末尾的位置,比如说一个LinearLayout是wrap content的,那么就将该TextView放到紧贴这个LinearLayout边缘的位置。
  • 就像这样:Markdown

隐藏列表项间的分隔线

  • 只需要在ListView XML文件中添加两个属性就可以了。
  • android:divider=”@null” ,android:dividerHeight=”0dp”

效果

  • 最后效果应该如下图所示:
  • Markdown

添加ListView的监听器

  • 为了当我们点击列表中的每一项都能够跳出对应的uri网站时,我们给ListView创建了一个监听器,然后又获取到了JSON Response中每个Item所对应的uri,然后我们使用隐式Intent来打开对应的网站就好了。

现在的项目结构图 & 代码

  • Markdown
  • Earthquake.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    package com.example.android.quakereport;
    /**
    * Created by hclmaster on 2017/2/2.
    */
    public class Earthquake {
    private double magnitude;
    private String place;
    private long time;
    private String url;
    public Earthquake(double magnitude, String place, long time, String url) {
    this.magnitude = magnitude;
    this.place = place;
    this.time = time;
    this.url = url;
    }
    public double getMagnitude() {
    return magnitude;
    }
    public String getPlace() {
    return place;
    }
    public long getTime() {
    return time;
    }
    public String getUrl() {
    return url;
    }
    }
  • EarthquakeActivity.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    /*
    * Copyright (C) 2016 The Android Open Source Project
    *
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    *
    * http://www.apache.org/licenses/LICENSE-2.0
    *
    * Unless required by applicable law or agreed to in writing, software
    * distributed under the License is distributed on an "AS IS" BASIS,
    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    * See the License for the specific language governing permissions and
    * limitations under the License.
    */
    package com.example.android.quakereport;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ListView;
    import java.util.ArrayList;
    public class EarthquakeActivity extends AppCompatActivity {
    public static final String LOG_TAG = EarthquakeActivity.class.getName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.earthquake_activity);
    // Create a fake list of earthquake locations.
    ArrayList<Earthquake> earthquakes = QueryUtils.extractEarthquakes();
    // Find a reference to the {@link ListView} in the layout
    ListView earthquakeListView = (ListView) findViewById(R.id.list);
    earthquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    Earthquake currentearthquake = (Earthquake) adapterView.getItemAtPosition(i);
    // 将字符串转化为Uri对象
    Uri earthquakeUri = Uri.parse(currentearthquake.getUrl());
    Intent webIntent = new Intent(Intent.ACTION_VIEW, earthquakeUri);
    startActivity(webIntent);
    }
    });
    EarthquakeAdapter earthquakeAdapter = new EarthquakeAdapter(this, earthquakes);
    // Set the adapter on the {@link ListView}
    // so the list can be populated in the user interface
    earthquakeListView.setAdapter(earthquakeAdapter);
    }
    }
  • EarthquakeAdapter.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    package com.example.android.quakereport;
    import android.content.Context;
    import android.graphics.drawable.GradientDrawable;
    import android.support.annotation.NonNull;
    import android.support.v4.content.ContextCompat;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.TextView;
    import java.text.DecimalFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.List;
    /**
    * Created by hclmaster on 2017/2/2.
    */
    public class EarthquakeAdapter extends ArrayAdapter<Earthquake> {
    public EarthquakeAdapter(Context context, List<Earthquake> objects) {
    super(context, 0, objects);
    }
    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    Earthquake earthquake = getItem(position);
    if(convertView == null){
    convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
    }
    TextView tvMagnitude = (TextView)convertView.findViewById(R.id.tv_quake_magnitude);
    TextView tvLocOffset = (TextView)convertView.findViewById(R.id.tv_location_offset);
    TextView tvLocation = (TextView)convertView.findViewById(R.id.tv_quake_location);
    TextView tvDate = (TextView)convertView.findViewById(R.id.tv_date);
    double mag = earthquake.getMagnitude();
    DecimalFormat formatter = new DecimalFormat("0.0");
    String magnitude = formatter.format(mag);
    tvMagnitude.setText(magnitude);
    String place = earthquake.getPlace();
    String location_offset;
    String primary_location;
    if(place.contains("of")){
    String[] strplace = place.split("(?<=of)");
    location_offset = strplace[0];
    primary_location = strplace[1];
    } else{
    location_offset = "Near the";
    primary_location = place;
    }
    tvLocOffset.setText(location_offset);
    tvLocation.setText(primary_location);
    TextView tvTime = (TextView)convertView.findViewById(R.id.tv_time);
    Date date = new Date(earthquake.getTime());
    String formattedDate = formatDate(date);
    tvDate.setText(formattedDate);
    String formattedTime = formatTime(date);
    tvTime.setText(formattedTime);
    // 为震级圆圈设置正确的背景颜色。
    // 从 TextView 获取背景,该背景是一个 GradientDrawable。
    GradientDrawable magnitudeCircle = (GradientDrawable) tvMagnitude.getBackground();
    // 根据当前的地震震级获取相应的背景颜色
    int magnitudeColor = getMagnitudeColor(earthquake.getMagnitude());
    // 设置震级圆圈的颜色
    magnitudeCircle.setColor(magnitudeColor);
    return convertView;
    }
    /**
    * Return the formatted date string (i.e. "Mar 3, 1984") from a Date object.
    */
    private String formatDate(Date date){
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("LLL dd, yyyy");
    return simpleDateFormat.format(date);
    }
    /**
    * Return the formatted date string (i.e. "4:30 PM") from a Date object.
    */
    private String formatTime(Date date){
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
    return simpleDateFormat.format(date);
    }
    /**
    * Set background color due to the magnitude of the earthquake
    */
    private int getMagnitudeColor(double magnitude){
    int magnitudeResourceID;
    int magnitudeFloor = (int)Math.floor(magnitude);
    switch (magnitudeFloor){
    case 0:
    case 1:
    magnitudeResourceID = R.color.magnitude1;
    break;
    case 2:
    magnitudeResourceID = R.color.magnitude2;
    break;
    case 3:
    magnitudeResourceID = R.color.magnitude3;
    break;
    case 4:
    magnitudeResourceID = R.color.magnitude4;
    break;
    case 5:
    magnitudeResourceID = R.color.magnitude5;
    break;
    case 6:
    magnitudeResourceID = R.color.magnitude6;
    break;
    case 7:
    magnitudeResourceID = R.color.magnitude7;
    break;
    case 8:
    magnitudeResourceID = R.color.magnitude8;
    break;
    case 9:
    magnitudeResourceID = R.color.magnitude9;
    break;
    default:
    magnitudeResourceID = R.color.magnitude10plus;
    break;
    }
    return ContextCompat.getColor(getContext(), magnitudeResourceID);
    }
    }
  • QueryUtils.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    package com.example.android.quakereport;
    import android.util.Log;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    /**
    * Helper methods related to requesting and receiving earthquake data from USGS.
    */
    public final class QueryUtils {
    /** Sample JSON response for a USGS query */
    private static final String SAMPLE_JSON_RESPONSE = "{\"type\":\"FeatureCollection\",\"metadata\":{\"generated\":1462295443000,\"url\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-01-01&endtime=2016-01-31&minmag=6&limit=10\",\"title\":\"USGS Earthquakes\",\"status\":200,\"api\":\"1.5.2\",\"limit\":10,\"offset\":1,\"count\":10},\"features\":[{\"type\":\"Feature\",\"properties\":{\"mag\":7.2,\"place\":\"88km N of Yelizovo, Russia\",\"time\":1454124312220,\"updated\":1460674294040,\"tz\":720,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us20004vvx\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us20004vvx&format=geojson\",\"felt\":2,\"cdi\":3.4,\"mmi\":5.82,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":1,\"sig\":798,\"net\":\"us\",\"code\":\"20004vvx\",\"ids\":\",at00o1qxho,pt16030050,us20004vvx,gcmt20160130032510,\",\"sources\":\",at,pt,us,gcmt,\",\"types\":\",cap,dyfi,finite-fault,general-link,general-text,geoserve,impact-link,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,\",\"nst\":null,\"dmin\":0.958,\"rms\":1.19,\"gap\":17,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 7.2 - 88km N of Yelizovo, Russia\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[158.5463,53.9776,177]},\"id\":\"us20004vvx\"},\n" +
    "{\"type\":\"Feature\",\"properties\":{\"mag\":6.1,\"place\":\"94km SSE of Taron, Papua New Guinea\",\"time\":1453777820750,\"updated\":1460156775040,\"tz\":600,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us20004uks\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us20004uks&format=geojson\",\"felt\":null,\"cdi\":null,\"mmi\":4.1,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":1,\"sig\":572,\"net\":\"us\",\"code\":\"20004uks\",\"ids\":\",us20004uks,gcmt20160126031023,\",\"sources\":\",us,gcmt,\",\"types\":\",cap,geoserve,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,\",\"nst\":null,\"dmin\":1.537,\"rms\":0.74,\"gap\":25,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.1 - 94km SSE of Taron, Papua New Guinea\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[153.2454,-5.2952,26]},\"id\":\"us20004uks\"},\n" +
    "{\"type\":\"Feature\",\"properties\":{\"mag\":6.3,\"place\":\"50km NNE of Al Hoceima, Morocco\",\"time\":1453695722730,\"updated\":1460156773040,\"tz\":0,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004gy9\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004gy9&format=geojson\",\"felt\":117,\"cdi\":7.2,\"mmi\":5.28,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":0,\"sig\":695,\"net\":\"us\",\"code\":\"10004gy9\",\"ids\":\",us10004gy9,gcmt20160125042203,\",\"sources\":\",us,gcmt,\",\"types\":\",cap,dyfi,geoserve,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,\",\"nst\":null,\"dmin\":2.201,\"rms\":0.92,\"gap\":20,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.3 - 50km NNE of Al Hoceima, Morocco\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[-3.6818,35.6493,12]},\"id\":\"us10004gy9\"},\n" +
    "{\"type\":\"Feature\",\"properties\":{\"mag\":7.1,\"place\":\"86km E of Old Iliamna, Alaska\",\"time\":1453631430230,\"updated\":1460156770040,\"tz\":-540,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004gqp\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004gqp&format=geojson\",\"felt\":1816,\"cdi\":7.2,\"mmi\":6.6,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":1,\"sig\":1496,\"net\":\"us\",\"code\":\"10004gqp\",\"ids\":\",at00o1gd6r,us10004gqp,ak12496371,gcmt20160124103030,\",\"sources\":\",at,us,ak,gcmt,\",\"types\":\",cap,dyfi,finite-fault,general-link,general-text,geoserve,impact-link,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,trump-origin,\",\"nst\":null,\"dmin\":0.72,\"rms\":2.11,\"gap\":19,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 7.1 - 86km E of Old Iliamna, Alaska\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[-153.4051,59.6363,129]},\"id\":\"us10004gqp\"},\n" +
    "{\"type\":\"Feature\",\"properties\":{\"mag\":6.6,\"place\":\"215km SW of Tomatlan, Mexico\",\"time\":1453399617650,\"updated\":1459963829040,\"tz\":-420,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004g4l\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004g4l&format=geojson\",\"felt\":11,\"cdi\":2.7,\"mmi\":3.92,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":1,\"sig\":673,\"net\":\"us\",\"code\":\"10004g4l\",\"ids\":\",at00o1bebo,pt16021050,us10004g4l,gcmt20160121180659,\",\"sources\":\",at,pt,us,gcmt,\",\"types\":\",cap,dyfi,geoserve,impact-link,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,\",\"nst\":null,\"dmin\":2.413,\"rms\":0.98,\"gap\":74,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.6 - 215km SW of Tomatlan, Mexico\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[-106.9337,18.8239,10]},\"id\":\"us10004g4l\"},\n" +
    "{\"type\":\"Feature\",\"properties\":{\"mag\":6.7,\"place\":\"52km SE of Shizunai, Japan\",\"time\":1452741933640,\"updated\":1459304879040,\"tz\":540,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004ebx\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004ebx&format=geojson\",\"felt\":51,\"cdi\":5.8,\"mmi\":6.45,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":1,\"sig\":720,\"net\":\"us\",\"code\":\"10004ebx\",\"ids\":\",us10004ebx,pt16014050,at00o0xauk,gcmt20160114032534,\",\"sources\":\",us,pt,at,gcmt,\",\"types\":\",associate,cap,dyfi,geoserve,impact-link,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,\",\"nst\":null,\"dmin\":0.281,\"rms\":0.98,\"gap\":22,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.7 - 52km SE of Shizunai, Japan\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[142.781,41.9723,46]},\"id\":\"us10004ebx\"},\n" +
    "{\"type\":\"Feature\",\"properties\":{\"mag\":6.1,\"place\":\"12km WNW of Charagua, Bolivia\",\"time\":1452741928270,\"updated\":1459304879040,\"tz\":-240,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004ebw\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004ebw&format=geojson\",\"felt\":3,\"cdi\":2.2,\"mmi\":2.21,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":0,\"sig\":573,\"net\":\"us\",\"code\":\"10004ebw\",\"ids\":\",us10004ebw,gcmt20160114032528,\",\"sources\":\",us,gcmt,\",\"types\":\",cap,dyfi,geoserve,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,\",\"nst\":null,\"dmin\":5.492,\"rms\":1.04,\"gap\":16,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.1 - 12km WNW of Charagua, Bolivia\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[-63.3288,-19.7597,582.56]},\"id\":\"us10004ebw\"},\n" +
    "{\"type\":\"Feature\",\"properties\":{\"mag\":6.2,\"place\":\"74km NW of Rumoi, Japan\",\"time\":1452532083920,\"updated\":1459304875040,\"tz\":540,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004djn\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004djn&format=geojson\",\"felt\":8,\"cdi\":3.4,\"mmi\":3.74,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":0,\"sig\":594,\"net\":\"us\",\"code\":\"10004djn\",\"ids\":\",us10004djn,gcmt20160111170803,\",\"sources\":\",us,gcmt,\",\"types\":\",cap,dyfi,geoserve,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,\",\"nst\":null,\"dmin\":1.139,\"rms\":0.96,\"gap\":33,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.2 - 74km NW of Rumoi, Japan\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[141.0867,44.4761,238.81]},\"id\":\"us10004djn\"},\n" +
    "{\"type\":\"Feature\",\"properties\":{\"mag\":6.5,\"place\":\"227km SE of Sarangani, Philippines\",\"time\":1452530285900,\"updated\":1459304874040,\"tz\":480,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004dj5\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004dj5&format=geojson\",\"felt\":1,\"cdi\":2.7,\"mmi\":7.5,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":1,\"sig\":650,\"net\":\"us\",\"code\":\"10004dj5\",\"ids\":\",at00o0srjp,pt16011050,us10004dj5,gcmt20160111163807,\",\"sources\":\",at,pt,us,gcmt,\",\"types\":\",cap,dyfi,geoserve,impact-link,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,\",\"nst\":null,\"dmin\":3.144,\"rms\":0.72,\"gap\":22,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.5 - 227km SE of Sarangani, Philippines\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[126.8621,3.8965,13]},\"id\":\"us10004dj5\"},\n" +
    "{\"type\":\"Feature\",\"properties\":{\"mag\":6,\"place\":\"Pacific-Antarctic Ridge\",\"time\":1451986454620,\"updated\":1459202978040,\"tz\":-540,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004bgk\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004bgk&format=geojson\",\"felt\":0,\"cdi\":1,\"mmi\":0,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":0,\"sig\":554,\"net\":\"us\",\"code\":\"10004bgk\",\"ids\":\",us10004bgk,gcmt20160105093415,\",\"sources\":\",us,gcmt,\",\"types\":\",cap,dyfi,geoserve,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,\",\"nst\":null,\"dmin\":30.75,\"rms\":0.67,\"gap\":71,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.0 - Pacific-Antarctic Ridge\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[-136.2603,-54.2906,10]},\"id\":\"us10004bgk\"}],\"bbox\":[-153.4051,-54.2906,10,158.5463,59.6363,582.56]}";
    /**
    * 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() {
    }
    /**
    * 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 {
    // TODO: 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 featuresArray = root.getJSONArray("features");
    for(int i=0; i<featuresArray.length(); i++){
    JSONObject f = featuresArray.getJSONObject(i);
    JSONObject properties = f.getJSONObject("properties");
    double mag = properties.getDouble("mag");
    String place = properties.getString("place");
    String url = properties.getString("url");
    // 因为默认得到的是一个Unix Time,所以我们下面可以
    // 利用一个Date Object来进行时间格式的修改!
    Long time = properties.getLong("time");
    Date dateObject = new Date(time);
    SimpleDateFormat dateFormatter = new SimpleDateFormat("MMM DD, yyyy");
    String dateToDisplay = dateFormatter.format(dateObject);
    earthquakes.add(new Earthquake(mag, place, time, url));
    }
    } 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;
    }
    }
  • magnitude_circle.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <?xml version="1.0" encoding="utf-8"?>
    <!-- Background circle for the magnitude value -->
    <shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@color/magnitude1" />
    <size
    android:width="36dp"
    android:height="36dp" />
    <corners android:radius="18dp" />
    </shape>
  • earthquake_activity.xml

    1
    2
    3
    4
    5
    6
    7
    <ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@null"
    android:dividerHeight="0dp"/>
  • list_item.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    <?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="?android:attr/listPreferredItemHeight"
    android:orientation="horizontal"
    android:paddingEnd="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingStart="16dp">
    <TextView
    android:id="@+id/tv_quake_magnitude"
    android:layout_width="36dp"
    android:layout_height="36dp"
    android:layout_gravity="center_vertical"
    android:background="@drawable/magnitude_circle"
    android:fontFamily="sans-serif-medium"
    android:gravity="center"
    android:textColor="@android:color/white"
    android:textSize="16sp"
    tools:text="8.9" />
    <LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:layout_marginLeft="16dp"
    android:layout_marginStart="16dp"
    android:layout_weight="1"
    android:orientation="vertical">
    <TextView
    android:id="@+id/tv_location_offset"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:fontFamily="sans-serif-medium"
    android:maxLines="1"
    android:textAllCaps="true"
    android:textColor="@color/textColorEarthquakeDetails"
    android:textSize="12sp"
    tools:text="30km S of" />
    <TextView
    android:id="@+id/tv_quake_location"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:maxLines="2"
    android:textColor="@color/textColorEarthquakeLocation"
    android:textSize="16sp"
    tools:text="Long placeholder location that should wrap to more than 2 lines of text" />
    </LinearLayout>
    <LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:layout_marginLeft="16dp"
    android:layout_marginStart="16dp"
    android:orientation="vertical">
    <TextView
    android:id="@+id/tv_date"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end"
    android:textColor="@color/textColorEarthquakeDetails"
    android:textSize="12sp"
    tools:text="Mar 6, 2010" />
    <TextView
    android:id="@+id/tv_time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end"
    android:textColor="@color/textColorEarthquakeDetails"
    android:textSize="12sp"
    tools:text="3:00 PM" />
    </LinearLayout>
    </LinearLayout>

感悟,终于搞完了第一课,感觉好累= =。。
果然是越往后走越不容易啊~
但是更加深刻的了解了api的知识,以及人们是怎样通过request api来获取他们需要的内容的!
希望能够更有干劲↖(^ω^)↗

热评文章