Java 如何使用依赖注入实现加载程序
我在我的代码中使用依赖项注入来创建一个可维护的代码,我开始用字符串中包含的虚拟数据填充ArrayList,然后我们开始使用数据库填充它,然后使用JSON和AsyncTask的WEB APIJava 如何使用依赖注入实现加载程序,java,android,dependency-injection,Java,Android,Dependency Injection,我在我的代码中使用依赖项注入来创建一个可维护的代码,我开始用字符串中包含的虚拟数据填充ArrayList,然后我们开始使用数据库填充它,然后使用JSON和AsyncTask的WEB API final ArrayList<Earthquake> earthquake = (ArrayList<Earthquake>) QueryUtils.extractEarthquakes(); final ArrayList<Earthquake> earthqua
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();
final ArrayList地震=(ArrayList)QueryUtils.extract地震();
最终ArrayList地震=(ArrayList)新地震控制器(新地震数据库()).GetListofEarth地震();
最终ArrayList地震=(ArrayList)新地震控制器(新地震JSON()).GetListofEarth地震();
为了在实现的方法中使用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();
}
..........................
......................
.......................
}
公共接口地震接口{
列出getEarthqueakes();
}
下面是实现该接口的类
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();
}
..........................
......................
.......................
}
公共类EarthquakesJson扩展AsyncTask实现EarthquakeInterface{
私有静态字符串URL_TOP_10_MOST_RECENT_EARTHQUEAKE_over_6=”http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10";
@凌驾
公共列表getEarthqueakes(){
返回这个。执行(URL_TOP_10_MOST_RECENT_EARTHQUEAKE_ABOVE_6)。get();
}
..........................
......................
.......................
}
现在我读到使用加载程序比使用AsyncTask更有效,但我不知道如何像使用AsyncTask那样使用独立注入的加载程序
我就是这样做的,但是没有使用依赖注入,尽管我尝试了
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;
}
公共类EarthquakeLoaderJson扩展AsyncTaskLoader实现EarthquakeInterface{
私有静态字符串URL_TOP_10_MOST_RECENT_EARTHQUEAKE_over_6=”http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10";
公共EarthquakeLoaderJson(上下文){
超级(上下文);
}
@凌驾
公共列表加载背景(){
网址;
HttpURLConnection HttpURLConnection=null;
StringBuilder json=新的StringBuilder();
字符串行=”;
试一试{
url=新url(url\u顶部\u 10\u最近\u最近\u地球探索\u 6以上);
httpURLConnection=(httpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod(“GET”);
InputStream InputStream=httpURLConnection.getInputStream();
InputStreamReader InputStreamReader=新的InputStreamReader(inputStream);
BufferedReader BufferedReader=新的BufferedReader(inputStreamReader);
而((line=bufferedReader.readLine())!=null){
json.append(行);
}
}捕获(格式错误){
e、 printStackTrace();
}
捕获(IOE异常){
e、 printStackTrace();
}最后{
if(httpURLConnection!=null){
httpURLConnection.disconnect();
}
}
//创建一个空的ArrayList,我们可以开始向其中添加地震
列表地震=新的ArrayList();
//尝试解析示例_JSON_响应。如果JSON响应的方式有问题
//如果已格式化,将抛出JSONException异常对象。
//捕获异常以便应用程序不会崩溃,并将错误消息打印到日志中。
试一试{
JSONObject root=新的JSONObject(json.toString());
JSONArray features=root.getJSONArray(“features”);
对于(int i=0;i
下面是需要列表的片段。注释的代码是我在更改加载程序的AsyncTask后无法使用的代码
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) {
}}
公共类ListMainFragment扩展片段实现LoaderManager.LoaderCallbacks{
公共ListMainFragment(){
//必需的空公共构造函数
}
列表视图列表视图;
@凌驾
创建视图(最终布局)上的公共视图充气机、视图组容器、,
Bundle savedInstanceState){
View viewRoot=充气机。充气(R.layout.fragment\u主列表,容器,false);
//最终ArrayList地震=(ArrayList)QueryUtils.extractSequences();
//最终ArrayList地震=(ArrayList)新地震控制器(new Earth震动fromDB()).GetListofEarth震动();
//最终ArrayList地震=(ArrayList)新地震控制器(新地震JSON()).GetListofEarth地震();
//我尝试使用依赖注入
//最终ArrayList地震=null;//(ArrayList)新地震控制器(新地震加载程序JSON(getContext())。getListOfEarthquakes();
listView=(listView)viewRoot.findViewById(R.id.list\u视图);
/*地震适配器noteAdapter=新的地震适配器(getActivity(),地震);
setAdapter(noteAdapter);
setOnItemClickListener(新的AdapterView.OnItemClickListener(){
//最后一个字符串mensaje=notas.get(position.getMag();
@凌驾
public void onItemClick(AdapterView父级、视图、整型位置)