尝试从USGS网站获取地震数据时无法显示数据

时间:2017-11-02 09:07:10

标签: android listview

我需要帮助,我试图从USGS网站获取世界上不同位置的地震数据并将它们显示在listView上,但是在JSON链接上创建HttpRequest并从JSON链接获取数据后,我的应用程序无法提取数据并使屏幕空白,运行时没有任何崩溃消息。 这是JSON链接< http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&orderby=time&minmag=5&limit=10>

请参阅我的代码以连接和获取数据

package com.example.android.quakereport;

import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class QueryUtils {
    //create tag for the log messages
    public static final String LOG_TAG = EarthquakeActivity.class.getName();

     //Create a private constructor because no one should ever create a {@link QueryUtils} object.

    private QueryUtils() {
    }

    //Query the USGS data set to return an Earthquake object
    public static List<Earthquake> fetchEarthquakeData(String requestUrl){
        //create a url from the string url provided
        URL url = createUrl(requestUrl);

        //make Http request on the url created and receive json response back
        String jsonResponse = null;
        try{
            jsonResponse = makeHttpRequest(url);
            Log.e(LOG_TAG, "return Data " + jsonResponse );
        }
        catch (IOException e){
            Log.e(LOG_TAG, "Error Closing input Stream");
        }

        return extractFeatureFromJSON(jsonResponse);
    }


    //create a url fro the given url string
    private static URL createUrl(String StringUrl){
        URL url = null;
        try {
            url = new URL(StringUrl);
        }
        catch (MalformedURLException e){
            Log.e(LOG_TAG, "Malformed Url", e);
        }
        return url;
    }

    //make http request from the url created to return as a json string
    private static String makeHttpRequest(URL url) throws IOException{
        String jsonResponse = "";

        //if the url is null, then return early
        if (url == null){
            return jsonResponse;
        }

        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try{
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000 /* im milliseconds*/);
            urlConnection.setConnectTimeout(15000 /*in milliseconds*/);
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            //if the connection was successful i.e response code = 200
            //then read the input stream and pass the response
            if(urlConnection.getResponseCode() == 200){
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            }
            else{
                Log.e(LOG_TAG, "Response Error Code: " + urlConnection.getResponseCode());
            }
        }
        catch (IOException e){
            Log.e(LOG_TAG, "Problem Retrieving the earthquake Json results");
        }
        finally {
            if (urlConnection != null){
                urlConnection.disconnect();
            }
            if (inputStream != null){
                inputStream.close();
            }
        }
        return jsonResponse;
    }

    //convert the input stream into a String which has the whole json response
    private static String readFromStream(InputStream inputStream) throws IOException{
        StringBuilder output = new StringBuilder();
        if(inputStream != null){
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            if(line != null){
                line = reader.readLine();
                output.append(line);
            }
        }
        return output.toString();
    }

    //Return a list of {@link Earthquake} objects that has been built up from
    private static List<Earthquake> extractFeatureFromJSON(String eartquakeJSON) {
        //if the json string is empty or null, then return early
        if (TextUtils.isEmpty(eartquakeJSON)){
            return null;
        }

        // 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 {
            //create the JSON object of the SAMPLE_JSON_RESPONSE
            JSONObject EarthquakeObject = new JSONObject(eartquakeJSON);
            //get the features JSON array
            JSONArray featuresArray = EarthquakeObject.getJSONArray("features");

            //loop through the features array
            for (int i = 0; i < featuresArray.length(); i++) {
                //get the JSON object at position i
                JSONObject currentEarthquakeDetails = featuresArray.getJSONObject(i);

                //get the JSON properties of the current object
                JSONObject properties = currentEarthquakeDetails.getJSONObject("properties");

                //get the magnitude of the current earthquate details
                double magnitude = properties.getDouble("mag");

                //get the location of the current earthquake details
                String location = properties.getString("place");

                //get the time of the current earthquake details
                long time = properties.getLong("time");
                Date dateObject = new Date(time);
                SimpleDateFormat dateFormater = new SimpleDateFormat("MMM DD, yyyy HH:mm:ss");
                String dateToDisplay = dateFormater.format(dateObject);

                String url = properties.getString("url");

                earthquakes.add(new Earthquake(magnitude, location, dateToDisplay, url));
            }
            // TODO: Parse the response given by the SAMPLE_JSON_RESPONSE string and
            // build up a list of Earthquake objects with the corresponding data.

        } 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;

    }
}

另见我的主要活动代码

package com.example.android.quakereport;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class EarthquakeActivity extends AppCompatActivity {
    /**
     * Sample JSON response for a USGS query
     */
    private static final String SAMPLE_JSON_RESPONSE = "http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&orderby=time&minmag=5&limit=10";

    private EarthquakeAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.earthquake_activity);

        // Find a reference to the {@link ListView} in the layout
        ListView earthquakeListView = (ListView) findViewById(R.id.list);
        final ArrayList<Earthquake> earthquakes = new ArrayList<>();
        // Create a new {@link ArrayAdapter} of earthquakes
        adapter = new EarthquakeAdapter(this, earthquakes);

        // Set the adapter on the {@link ListView}
        // so the list can be populated in the user interface
        earthquakeListView.setAdapter(adapter);

        //set onclick listener to each item on the listView
        earthquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l){
                //Get the current earthquake that was clicked
                Earthquake currentEarthquake = earthquakes.get(position);
                Intent browse = new Intent(Intent.ACTION_VIEW, Uri.parse(currentEarthquake.getUrl()));
                startActivity(browse);
            }
        });

        EarthquakeAsyncTask task = new EarthquakeAsyncTask();
        task.execute(SAMPLE_JSON_RESPONSE);
    }

    private class EarthquakeAsyncTask extends AsyncTask<String, Void, List<Earthquake>> {

        @Override
        protected List<Earthquake> doInBackground(String... urls) {
            //check if the url is empty
            if (urls.length < 0 || urls[0] == null){
                return null;
            }
            return QueryUtils.fetchEarthquakeData(urls[0]);
        }

        @Override
        protected void onPostExecute(List<Earthquake> data){
            //Clear the adapter of previous earthquake data
            adapter.clear();

            //if data is null then return empty
            if(data != null && !data.isEmpty()){
                adapter.addAll(data);
            }
        }
    }
}

还有我的Log Cat

  

11-02 08:41:15.049 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:41:15.055 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:41:15.075 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:41:15.089 1710-1838 /? E / UsimAccountType:AAS的[addDataKindEmail]。   11-02 08:41:15.089 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:41:15.092 1710-1838 /? E / CsimAccountType:AAS的[addDataKindEmail]。   11-02 08:41:24.008 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:41:24.021 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:41:24.027 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:41:24.029 1710-1838 /? E / UsimAccountType:AAS的[addDataKindEmail]。   11-02 08:41:24.030 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:41:24.033 1710-1838 /? E / CsimAccountType:AAS的[addDataKindEmail]。   11-02 08:41:32.988 1665-1665 /? E / InputEventModelImpl:onStartInput事件中止:com.touchtype.keyboard.c.ag:无法获取提取的文本(类com.touchtype.keyboard.c.ag)   11-02 08:41:33.977 898-898 /? E / WifiTrafficPoller:ENABLE_TRAFFIC_STATS_POLL false令牌847   11-02 08:41:33.980 30524-30524 /? E / hostapd:第0行:未知配置项'pno'   11-02 08:41:33.980 898-945 /? E / WifiStateMachine:无法设置pno,现在想要假false   11-02 08:41:34.309 898-945 /? E / WifiStateMachine:错误!未处理的消息{when = -2ms what = 131156 target = com.android.internal.util.StateMachine $ SmHandler}   11-02 08:42:26.243 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:42:26.249 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:42:26.253 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:42:26.256 1710-1838 /? E / UsimAccountType:AAS的[addDataKindEmail]。   11-02 08:42:26.256 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:42:26.259 1710-1838 /? E / CsimAccountType:AAS的[addDataKindEmail]。   11-02 08:42:26.346 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:42:26.349 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:42:26.353 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:42:26.357 1710-1838 /? E / UsimAccountType:AAS的[addDataKindEmail]。   11-02 08:42:26.357 1710-1838 /? E / MPlugin:不支持的类:com.mediatek.common.telephony.IOnlyOwnerSimSupport   11-02 08:42:26.360 1710-1838 /? E / CsimAccountType:AAS的[addDataKindEmail]。   11-02 08:42:26.363 898-1757 /? E / Sensors:handleToDriver句柄(0)   11-02 08:42:26.369 898-1757 /? E / Sensors:handleToDriver句柄(0)   11-02 08:42:26.382 898-1757 /? E / Sensors:新的setDelay句柄(0),ns(200000000)m,错误(0),索引(2)

0 个答案:

没有答案