在线解析JSON+ AsyncTaskLoader

在线解析JSON+ AsyncTaskLoader,第1张

在线解析JSON+ AsyncTaskLoader

效果图

获取并解析Json


package com.example.admin.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.util.ArrayList;import java.util.List;

public class QueryUtils {

    private static final String LOG_TAG = QueryUtils.class.getSimpleName();

    public static List<Earthquake> fetchEarthquakeData(String requestUrl){        URL url = createUrl(requestUrl);        String jsonResponse = null;        try        { jsonResponse = makehttpRequest(url);        }catch (IOException e){            Log.e(LOG_TAG,"Error in making http request",e); }        List<Earthquake> result = extractEarthquakes(jsonResponse);        return result;    }

    private static URL createUrl(String mUrl) {        URL url = null;        try {            url = new URL(mUrl);        } catch (MalformedURLException e) {            Log.e(LOG_TAG, "Problem building the URL ", e);        }        return url;    }

    private static String makehttpRequest(URL url)throws IOException {        String jsonResponse = "";        if (url == null) {            return jsonResponse;        }

        HttpURLConnection urlConnection = null;        InputStream inputStream = null;

        try {            urlConnection = (HttpURLConnection) url.openConnection();            urlConnection.setReadTimeout(10000);            urlConnection.setConnectTimeout(15000);            urlConnection.setRequestMethod("GET");            urlConnection.connect();

            if (urlConnection.getResponseCode() == 200) {                inputStream = urlConnection.getInputStream();                jsonResponse = readFromStream(inputStream);            } else {                Log.e(LOG_TAG, "Error in connection!! Bad Response ");            }

        } catch (IOException e) {            Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);        } finally {            {                if (urlConnection != null) {                    urlConnection.disconnect();                }                if (inputStream != null) {                    inputStream.close();                }            }        }        return jsonResponse;    }

    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();

            while (line != null) {                output.append(line);                line = reader.readLine();            }        }

       return output.toString();}

    private static List<Earthquake> extractEarthquakes(String earthquakeJSON){         final String getJsonArray="features",jsObject="properties",double_magnituede="mag",String_location="place"                 ,String_time="time",String_url="url";

        if (TextUtils.isEmpty(earthquakeJSON)) {            return null;        }        List<Earthquake> earthquakes = new ArrayList<>();

        try {            JSONObject baseJsonResponse = new JSONObject(earthquakeJSON);            JSONArray featureArray = baseJsonResponse.getJSONArray(getJsonArray);

            for (int i = 0; i < featureArray.length(); i++) {                JSONObject currentEarthquake = featureArray.getJSONObject(i);                JSONObject properties = currentEarthquake.getJSONObject(jsObject);                double magnitude = properties.getDouble(double_magnituede);                String location = properties.getString(String_location);                long time = properties.getLong(String_time);                String Url = properties.getString(String_url);                Earthquake earthquake = new Earthquake(magnitude, location, time,Url);                earthquakes.add(earthquake);            }

        }catch (JSONException e){            Log.e(LOG_TAG,"Error in fetching data",e);        }        return earthquakes;    }

}
android 网络连接必须放在子线程中,不推荐用AsyncTask的原因:横屏时AsyncTask不会被回收到内存。


package com.example.admin.quakereport;

import android.content.AsyncTaskLoader;import android.content.Context;import android.support.annotation.NonNull;import android.support.annotation.Nullable;

import java.util.List;

public class EarthquakeLoader extends AsyncTaskLoader<List<Earthquake>> {    private String mUrl;    private List<Earthquake> itemlist;

    public EarthquakeLoader(@NonNull Context context,String mUrl) {        super(context);        this.mUrl=mUrl;    }

    @Override    protected void onStartLoading() {        if (itemlist!=null){            deliverResult(itemlist);        }else {            forceLoad();        }    }

    @Nullable    @Override

    public List<Earthquake> loadInBackground(){        if (mUrl == null) {            return null; }        List<Earthquake> earthquakes = QueryUtils.fetchEarthquakeData(mUrl);        return earthquakes;    }

    @Override    public void deliverResult(@Nullable List<Earthquake> data) {        itemlist=data;        super.deliverResult(data);    }}
github项目源码: https://github.com/NeoWu55/Android-QuakeReport

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/588099.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存