联网demo:在线解析JSON+ AsyncTaskLoader

Posted neowu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了联网demo:在线解析JSON+ AsyncTaskLoader相关的知识,希望对你有一定的参考价值。

demo效果:

技术图片

 

获取并解析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){
if (TextUtils.isEmpty(earthquakeJSON)) {
return null;
}
List<Earthquake> earthquakes = new ArrayList<>();

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

for (int i = 0; i < featureArray.length(); i++) {
JSONObject currentEarthquake = featureArray.getJSONObject(i);
JSONObject properties = currentEarthquake.getJSONObject("properties");
double magnitude = properties.getDouble("mag");
String location = properties.getString("place");
long time = properties.getLong("time");
String Url = properties.getString("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

以上是关于联网demo:在线解析JSON+ AsyncTaskLoader的主要内容,如果未能解决你的问题,请参考以下文章

JSON在线解析,新版本JSON在线解析

JSON相关 JSON在线解析 JSON压缩转义工具 JSON着色工具 JSON 在线格式化工具 在线XML/JSON互相转换工具 XMLJSON在线转换

在线Excel文件解析转换成JSON格式

json data 解析demo

Mapbox源码分析(2)url解析

JSON在线解析及格式化校验工具 jsonin.com