[英]How to refresh content using Swipe Refresh Layout?
我正在从 UDACITY 学习网络,在那里我遇到了一个名为 Quake Report 的应用程序,我想在应用程序中添加滑动刷新功能,但我无法获得我想要的结果。
package com.example.android.quakereport;
import android.app.LoaderManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class EarthquakeActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Earthquake>> {
/**
* Constant value for the earthquake loader ID. We can choose any integer.
* This really only comes into play if you're using multiple loaders.
*/
private static final int EARTHQUAKE_LOADER_ID = 1;
// TextView that is displayed when the list is empty
private TextView mEmptyStateTextView;
// progress bar
private ProgressBar progressBar;
public static final String LOG_TAG = EarthquakeActivity.class.getName();
// URL for earthquake data from the USGS dataset
private static final String USGS_REQUEST_URL =
"https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&orderby=time&minmag=5&limit=15";
/**
* Adapter for the list of earthquakes
*/
private EarthquakeAdapter mAdapter;
@Override
public Loader<List<Earthquake>> onCreateLoader(int id, Bundle args) {
Log.i(LOG_TAG, "Test: onCreateLoader() called...");
// Create a new loader for the given URL
return new EarthquakeLoader(this, USGS_REQUEST_URL);
}
@Override
public void onLoadFinished(Loader<List<Earthquake>> loader, List<Earthquake> data) {
Log.i(LOG_TAG, "Test: onLoadFinished() called...");
// Clear the adapter of previous earthquake data
mAdapter.clear();
// Hiding the progress bar as the results have been loaded
progressBar.setVisibility(View.GONE);
// Check if Internet Connection is present or not and show text accordingly
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
mEmptyStateTextView.setText(R.string.no_earthquakes);
} else {
mEmptyStateTextView.setText(R.string.no_internet_connection);
}
// If there is a valid list of {@link Earthquake}s, then add them to the adapter's
// data set. This will trigger the ListView to update.
if (data != null && !data.isEmpty()) {
mAdapter.addAll(data);
}
}
@Override
public void onLoaderReset(Loader<List<Earthquake>> loader) {
Log.i(LOG_TAG, "Test: onLoaderReset() called...");
// Loader reset, so we can clear out our existing data.
mAdapter.clear();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(LOG_TAG, "Test: Earthquake Activity onCreate() called.");
super.onCreate(savedInstanceState);
setContentView(R.layout.earthquake_activity);
// Creating a swipe to refresh feature
final SwipeRefreshLayout pullToRefresh = findViewById(R.id.swipe_refresh);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
pullToRefresh.setRefreshing(false);
}
});
// Find a reference to the {@link ListView} in the layout
ListView earthquakeListView = (ListView) findViewById(R.id.list);
// Get a reference to the ConnectivityManager to check state of network connectivity
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// Get details on the currently active default data network
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
// If there is a network connection, fetch data
if (networkInfo != null && networkInfo.isConnected()) {
// Get a reference to the LoaderManager, in order to interact with loaders.
LoaderManager loaderManager = getLoaderManager();
// Initialize the loader. Pass in the int ID constant defined above and pass in null for
// the bundle. Pass in this activity for the LoaderCallbacks parameter (which is valid
// because this activity implements the LoaderCallbacks interface).
// Create a new adapter that takes an empty list of earthquakes as input
Log.i(LOG_TAG, "Test: calling initLoader()...");
loaderManager.initLoader(EARTHQUAKE_LOADER_ID, null, this);
} else {
// Otherwise, display error
// First, hide loading indicator so error message will be visible
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setVisibility(View.GONE);
// Update empty state with no connection error message
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
mEmptyStateTextView.setText(R.string.no_internet_connection);
}
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
earthquakeListView.setEmptyView(mEmptyStateTextView);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
mAdapter = new EarthquakeAdapter(this, new ArrayList<Earthquake>());
// Set the adapter on the {@link ListView}
// so the list can be populated in the user interface
earthquakeListView.setAdapter(mAdapter);
// Set an item click listener on the ListView, which sends an intent to a web browser
// to open a website with more information about the selected earthquake.
earthquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// Find the current earthquake that was clicked on
Earthquake currentEarthquake = mAdapter.getItem(position);
// Convert the String URL into a URI object (to pass into the Intent constructor)
Uri earthquakeUri = Uri.parse(currentEarthquake.getUrl());
// Create a new intent to view the earthquake URI
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, earthquakeUri);
// Send the intent to launch a new activity
startActivity(websiteIntent);
}
});
// EarthquakeAsyncTask task = new EarthquakeAsyncTask();
// task.execute(USGS_REQUEST_URL);
}
/**
* {@link AsyncTask} to perform the network request on a background thread, and then
* update the UI with the list of earthquakes in the response.
* <p>
* AsyncTask has three generic parameters: the input type, a type used for progress updates, and
* an output type. Our task will take a String URL, and return an Earthquake. We won't do
* progress updates, so the second generic is just Void.
* <p>
* We'll only override two of the methods of AsyncTask: doInBackground() and onPostExecute().
* The doInBackground() method runs on a background thread, so it can run long-running code
* (like network activity), without interfering with the responsiveness of the app.
* Then onPostExecute() is passed the result of doInBackground() method, but runs on the
* UI thread, so it can use the produced data to update the UI.
*/
private class EarthquakeAsyncTask extends AsyncTask<String, Void, List<Earthquake>> {
/**
* This method runs on a background thread and performs the network request.
* We should not update the UI from a background thread, so we return a list of
* {@link Earthquake}s as the result.
*/
@Override
protected List<Earthquake> doInBackground(String... urls) {
// Don't perform the request if there are no URLs, or the first URL is null.
if (urls.length < 1 || urls[0] == null) {
return null;
}
List<Earthquake> result = QueryUtils.fetchEarthquakeData(urls[0]);
return result;
}
/**
* This method runs on the main UI thread after the background work has been
* completed. This method receives as input, the return value from the doInBackground()
* method. First we clear out the adapter, to get rid of earthquake data from a previous
* query to USGS. Then we update the adapter with the new list of earthquakes,
* which will trigger the ListView to re-populate its list items.
*/
@Override
protected void onPostExecute(List<Earthquake> data) {
// Clear the adapter of previous earthquake data
mAdapter.clear();
// If there is a valid list of {@link Earthquake}s, then add them to the adapter's
// data set. This will trigger the ListView to update.
if (data != null && !data.isEmpty()) {
mAdapter.addAll(data);
}
}
}
}
每当用户向下滑动时,我希望此应用程序从给定的 URL 获取数据,但我无法找到方法。 谁能帮我编写以下代码块中的代码:
final SwipeRefreshLayout pullToRefresh = findViewById(R.id.swipe_refresh);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
pullToRefresh.setRefreshing(false);
}
});
调用 doRefresh 方法中负责网络调用的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.