码迷,mamicode.com
首页 > Web开发 > 详细

联网demo:在线解析JSON+ AsyncTaskLoader

时间:2019-04-06 19:14:12      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:ryu   mil   final   vat   原因   utf-8   except   androi   long   

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

标签:ryu   mil   final   vat   原因   utf-8   except   androi   long   

原文地址:https://www.cnblogs.com/neowu/p/10662452.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!