我正在開發一個連接到Web服務器並從服務器上的XML
讀取數據的大學的應用程序。 該應用程序正在工作,但我目前正試圖真正分解代碼並準確瞭解發生了什麼。從Web服務器下載XML文件Android
我的問題是,我有一個擴展AsyncTask
類的內部類。在這個內部類中,我創建一個新的URL
對象並獲得一個InputStream
。我明白,因爲我這樣做,我可以從後臺線程成功連接到Web服務器,併發出我喜歡的任何請求。
在過去,我總是使用DefaultHttpClient
來執行HTTP
請求。然而,在這段代碼中,我不會在任何地方創建這個類的實例。相反,我只是得到一個輸入流來讀取字節序列。
有人可以在下面的代碼解釋什麼是解析規範的意思,並且如果在幕後的某個地方HTTP
請求實際上正在作出? Android開發
URL url = new URL("http://feeds.pcworld.com/pcworld/latestnews");
文件說:
通過解析規範創建一個新的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();
}
}
}
我很抱歉,如果這個問題是非常基本的,但就像我說的,我努力學習,這是這個網站是什麼都差不多?
我很感謝任何反饋或幫助人們有關於這個話題。 非常感謝!