我是android的初学者,我只学过asynctaskloader作为后台线程,所以我不知道其他的方法,你能告诉我怎么解决吗。
public class MainActivity extends AppCompatActivity {
public static final String LOG_TAG = MainActivity.class.getSimpleName();
private static final String USGS_REQUEST_URL =
"https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2014-01-01&endtime=2014-12-01&minmagnitude=7";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void updateUi(Event earthquakes) {
// Display the earthquake title in the UI
TextView titleTextView = (TextView) findViewById(R.id.title);
titleTextView.setText(earthquakes.title);
// Display the earthquake date in the UI
TextView dateTextView = (TextView) findViewById(R.id.date);
dateTextView.setText(getDateString(earthquakes.time));
// Display whether or not there was a tsunami alert in the UI
TextView tsunamiTextView = (TextView) findViewById(R.id.tsunami_alert);
tsunamiTextView.setText(getTsunamiAlertString(earthquakes.tsunamiAlert));
}
/**
* Returns a formatted date and time string for when the earthquake happened.
*/
private String getDateString(long timeInMilliseconds) {
SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy 'at' HH:mm:ss z");
return formatter.format(timeInMilliseconds);
}
/**
* Return the display string for whether or not there was a tsunami alert for an earthquake.
*/
private String getTsunamiAlertString(int tsunamiAlert) {
switch (tsunamiAlert) {
case 0:
return getString(R.string.alert_no);
case 1:
return getString(R.string.alert_yes);
default:
return getString(R.string.alert_not_available);
}
}
public List<Event> extractearthquakesfromurl(String requesturl) {
URL url = createUrl(requesturl);
String jsonresponse = null;
try {
jsonresponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Error closing input stream", e);
}
// Extract relevant fields from the JSON response and create an {@link Event} object
List<Event>earthquake= (List<Event>) extractFeatureFromJson(jsonresponse);
// Return the {@link Event}
return earthquake;
}
/**
* Returns new URL object from the given string URL.
*/
private URL createUrl(String requestUrl) {
URL url = null;
try {
url = new URL(requestUrl);
} catch (MalformedURLException exception) {
Log.e(LOG_TAG, "Error with creating URL", exception);
return null;
}
return url;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
// TODO: Handle the exception
Log.e(LOG_TAG, "Problem with HTTP request", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {@link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private 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();
}
/**
* Return an {@link Event} object by parsing out information
* about the first earthquake from the input earthquakeJSON string.
*/
private Event extractFeatureFromJson(String earthquakeJSON) {
try {
JSONObject baseJsonResponse = new JSONObject(earthquakeJSON);
JSONArray featureArray = baseJsonResponse.getJSONArray("features");
// If there are results in the features array
if (featureArray.length() > 0) {
// Extract out the first feature (which is an earthquake)
JSONObject firstFeature = featureArray.getJSONObject(0);
JSONObject properties = firstFeature.getJSONObject("properties");
// Extract out the title, time, and tsunami values
String title = properties.getString("title");
long time = properties.getLong("time");
int tsunamiAlert = properties.getInt("tsunami");
// Create a new {@link Event} object
return new Event(title, time, tsunamiAlert);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
}
return null;
}
}
对于网络请求有什么方法吗?喜欢asynctaskloader在后台运行和加载吗?试着用java回答这个问题我不知道kotlin。。谢谢您
暂无答案!
目前还没有任何答案,快来回答吧!