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();
}
}
}
この質問が非常に基本的なものである場合は申し訳ありませんが、私が言ったように、私は学ぼうとしており、それがこのサイトのすべてです?
このトピックに関するフィードバックやヘルプをいただければ幸いです。どうもありがとう!