我正在开发一个连接到 Web 服务器并从服务器XML
上读取数据的大学应用程序。该应用程序正在运行,但我目前正在尝试真正分解代码并准确了解正在发生的事情。
我的问题是我有一个扩展类的内部AsyncTask
类。在这个内部类中,我创建一个新URL
对象并获得一个InputStream
. 我知道因为我这样做了,所以我可以从后台线程成功连接到 Web 服务器并发出我喜欢的任何请求。
过去我总是使用DefaultHttpClient
来执行HTTP
请求。但是,在这段代码中,我没有在任何地方创建此类的实例。相反,我只是得到一个输入流来读取字节序列。
有人可以在下面的代码中解释解析规范的含义,以及是否在幕后某个地方HTTP
实际发出请求?
URL url = new URL("http://feeds.pcworld.com/pcworld/latestnews");
Android Dev 上的文档说:
通过解析规范创建一个新的 URL 实例。
这是我的全部MainActivity
public class MainActivity extends ListActivity {
List<Item>items;//Holds item objects containing info relating to element pulled from XML file.
Item item; //Instance of Item - contains all data relating to a specific Item.
ArticleListAdapter adapter;//Generates the Views and links the data source (ArrayList) to the ListView.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set the layout
setContentView(R.layout.activity_main);
//initialize variables
items = new ArrayList<Item>();
//Perform a http request for the file on the background thread.
new PostTask().execute();
//Create instance of the adapter and pass the list of items to it.
adapter = new ArticleListAdapter(this, items);
//Attach adapter to the ListView.
setListAdapter(adapter);
}
private InputStream getInputStream(URL url) {
try{
return url.openConnection().getInputStream();
}catch(IOException e){
return null;
}
}
/**
* Executed when an Item in the List is clicked. Will display the article being clicked in a browser.
*/
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
//Get the link from the item object stored in the array list
Uri uri = items.get(position).getLink();
//Create new intent to open browser
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
//ASYNC CLASS
private class PostTask extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... arg0) {
try{
//link to data source
URL url = new URL("http://feeds.pcworld.com/pcworld/latestnews");
//Set up parser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
//get XML from input stream
InputStream in = getInputStream(url);
if (in == null) {
throw new Exception("Empty inputstream");
}
xpp.setInput(in, "UTF_8");
//Keep track of which tag inside of XML
boolean insideItem = false;
//Loop through the XML file and extract data required
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
Log.v("ENTER", String.valueOf(xpp.getEventType()));
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
//Create new item object
item = new Item();
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem){
item.setTitle(xpp.nextText());
Log.i("title", item.getTitle());
}
}
else if (xpp.getName().equalsIgnoreCase("description")) {
if (insideItem){
item.setDescription(xpp.nextText());
}
}
else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem){
item.setLink(Uri.parse(xpp.nextText()));
}
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
//If no longer inside item tag then we know we are finished parsing data relating to one specific item.
insideItem=false;
//add item to list
items.add(item);
}
eventType = xpp.next(); //move to next element
publishProgress(); //update progress on UI thread.
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return "COMPLETED";
}
/*
* Update the List as each item is parsed from the XML file.
* @see android.os.AsyncTask#onProgressUpdate(Progress[])
*/
@Override
protected void onProgressUpdate(Integer... values) {
adapter.notifyDataSetChanged();
}
/*
* Runs on UI thread after doInBackground is finished executing.
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
public void onPostExecute(String s) {
//Toast message to inform user of how many articles have been downloaded.
Toast.makeText(getApplicationContext(), s + " Items: " + items.size(), Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
}
}
如果这个问题非常基本,我很抱歉,但就像我说的我正在努力学习,这就是这个网站的全部内容,对吗?
我很感激人们对此主题的任何反馈或帮助。非常感谢!