我在我的代码中使用依赖注入来创建使我的代码可维护,我开始使用String中包含的虚拟数据填充我的ArrayList,然后我们开始使用数据库填充它,然后我使用使用JSON的WEB API并使用一个AsyncTask。
final ArrayList<Earthquake> earthquake = (ArrayList<Earthquake>) QueryUtils.extractEarthquakes();
final ArrayList<Earthquake> earthquake = (ArrayList<Earthquake>) new EarthquakeController(new EarthquakesDB()).getListOfEarthquakes();
final ArrayList<Earthquake> earthquake = (ArrayList<Earthquake>) new EarthquakeController(new EarthquakesJson()).getListOfEarthquakes();
为了使它与AsynkTask和实现方法中的独立注入一起使用,我调用了execute.get()方法。
这是我的界面
public interface EarthquakeInterface {
List<Earthquake> getEarthqueakes();
}
这是我实现该接口的类
public class EarthquakesJson extends AsyncTask<String,Void,List<Earthquake>>implements EarthquakeInterface {
private static String URL_TOP_10_MOST_RECENT_EARTHQUEAKE_ABOVE_6 = "http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10";
@Override
public List<Earthquake> getEarthqueakes() {
return this.execute(URL_TOP_10_MOST_RECENT_EARTHQUEAKE_ABOVE_6).get();
}
..........................
......................
.......................
}
现在我正在阅读使用Loaders比使用AsyncTask更有效,但我无法像使用Asynctask一样使用具有独立注入的Loaders。
这就是我这样做的方式,但是我没有尝试使用依赖注入。
public class EarthquakeLoaderJson extends AsyncTaskLoader<List<Earthquake>> implements EarthquakeInterface {
private static String URL_TOP_10_MOST_RECENT_EARTHQUEAKE_ABOVE_6 = "http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10";
public EarthquakeLoaderJson(Context context){
super(context);
}
@Override
public List<Earthquake> loadInBackground() {
URL url;
HttpURLConnection httpURLConnection = null;
StringBuilder json = new StringBuilder();
String line="";
try {
url = new URL(URL_TOP_10_MOST_RECENT_EARTHQUEAKE_ABOVE_6);
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("GET");
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
while ((line=bufferedReader.readLine())!= null){
json.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
} finally {
if(httpURLConnection!=null){
httpURLConnection.disconnect();
}
}
// Create an empty ArrayList that we can start adding earthquakes to
List<Earthquake> earthquakes = new ArrayList<>();
// Try to parse the SAMPLE_JSON_RESPONSE. If there's a problem with the way the JSON
// is formatted, a JSONException exception object will be thrown.
// Catch the exception so the app doesn't crash, and print the error message to the logs.
try {
JSONObject root = new JSONObject(json.toString());
JSONArray features = root.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
JSONObject earthquake = features.getJSONObject(i);
JSONObject properties = earthquake.getJSONObject("properties");
double mag = properties.getDouble("mag");
String place = properties.getString("place");
long time = properties.getLong("time");
String mapURL = properties.getString("url");
earthquakes.add(new Earthquake(mag, place, time, mapURL));
}
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
}
// Return the list of earthquakes
return earthquakes;
}
//this is my method that I implement from the interface
@Override
public List<Earthquake> getEarthqueakes() {
return null;
}
这是需要列表的片段。注释的代码是我更改了AsadersTask for Loaders后我无法使用的代码。
public class ListMainFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Earthquake>> {
public ListMainFragment() {
// Required empty public constructor
}
ListView listView;
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View viewRoot = inflater.inflate(R.layout.fragment_mainlist, container, false);
//final ArrayList<Earthquake> earthquake = (ArrayList<Earthquake>) QueryUtils.extractEarthquakes();
//final ArrayList<Earthquake> earthquake = (ArrayList<Earthquake>) new EarthquakeController(new EarthquakeFromDB()).getListOfEarthquakes();
//final ArrayList<Earthquake> earthquake = (ArrayList<Earthquake>) new EarthquakeController(new EarthquakesJson()).getListOfEarthquakes();
//I tried to use dependency injection
// final ArrayList<Earthquake> earthquake = null;// (ArrayList<Earthquake>) new EarthquakeController(new EarthquakeLoaderJson(getContext())).getListOfEarthquakes();
listView = (ListView)viewRoot.findViewById(R.id.list_view);
/* EarthquakeAdapter noteAdapter = new EarthquakeAdapter(getActivity(), earthquake);
listView.setAdapter(noteAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//final String mensaje = notas.get(position).getMag();
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(earthquake.get(0).getMapURL()));
Log.w("ListView", "Se despliega la siguente URL " + earthquake.get(0).getMapURL());
startActivity(intent);
}
});*/
getLoaderManager().initLoader(0,null,this).forceLoad();
return viewRoot;
}
@Override
public Loader<List<Earthquake>> onCreateLoader(int id, Bundle args) {
return new EarthquakeLoaderJson(getContext());
}
@Override
public void onLoadFinished(Loader<List<Earthquake>> loader, List<Earthquake> data) {
final ArrayList<Earthquake> earthquakeArrayList = (ArrayList<Earthquake>)data;
EarthquakeAdapter earthquakeAdapter = new EarthquakeAdapter(getActivity(),earthquakeArrayList);
listView.setAdapter(earthquakeAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//final String mensaje = notas.get(position).getMag();
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(earthquakeArrayList.get(0).getMapURL()));
startActivity(intent);
}
});
}
@Override
public void onLoaderReset(Loader<List<Earthquake>> loader) {
}}