1

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();
    }

}

}

この質問が非常に基本的なものである場合は申し訳ありませんが、私が言ったように、私は学ぼうとしており、それがこのサイトのすべてです?

このトピックに関するフィードバックやヘルプをいただければ幸いです。どうもありがとう!

4

1 に答える 1

1

parsing spec- コンストラクターに渡す文字列を解析することを意味します。URL API の作成者は、この文字列 (url/uri) をより一般的な方法 (仕様) で命名しました。おそらく、接続先のリソースを指定しているためです。string が有効な URL を表していない場合は、 がスローされMalformedURLExceptionます。解析後、HTTP 要求の作成に使用するホスト、ポート、パスなどを認識します。

インスタンスを作成してURLも、ネットワークが発生するわけではありません。FileこれはAPIに似てFileいます。インスタンスを作成しても何も開いたり、読み書きしたりしません。

url.openConnection().getInputStream()- ここでネットワークが発生します (HTTP 要求が発生します)。

ULRのソース コードは次のとおりです。

于 2013-04-08T18:37:32.157 に答える