Java 了解存储和检索字符串ArrayList的时间安排

Java 了解存储和检索字符串ArrayList的时间安排,java,timing,Java,Timing,我很难理解在类中存储和检索私有成员的时机。我只是尝试从XML文件中收集RSS标题,并在文本视图中显示它们 我记录了这个流,这让我很困惑,为什么在fetchXML()方法完成之前调用getTitleList()方法 MainActivity.java package com.digitalalias.dndandroid.rss; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import a

我很难理解在类中存储和检索私有成员的时机。我只是尝试从XML文件中收集RSS标题,并在文本视图中显示它们

我记录了这个流,这让我很困惑,为什么在fetchXML()方法完成之前调用getTitleList()方法

MainActivity.java

package com.digitalalias.dndandroid.rss;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {

    private String finalUri = "http://dndandroid.com/feed/";
    private HandleXML obj;
    private TextView tv, link, description;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void fetch(View view) {
        tv = (TextView) findViewById(R.id.textView2);
        tv.setMovementMethod(new ScrollingMovementMethod());
        tv.setText("");  // prep textview for use

        obj = new HandleXML(finalUri);
        obj.fetchXML();

        tv.setText(obj.getTitleList());  // display rss titles
    }

    public void play(View view) {
        TextView textView = (TextView) findViewById(R.id.textView2);
        textView.setText(textView.getText() + " Marc is cool " + finalUri);
        fetch(view);
    }
}
package com.digitalalias.dndandroid.rss;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.os.*;
import android.util.Log;

/**
 * Created by mfferguson on 5/2/2014.
 */
public class HandleXML {

    private String title = "title";
    private String link = "link";
    private String description = "description";
    private List<String> titleList = new ArrayList<String>();
    private boolean isEndTag = false;
    String linesep = System.getProperty("line.separator");

    private String urlString = null;
    private XmlPullParserFactory xmlFactoryObject;
    public volatile boolean parsingComplete = true;

    public HandleXML(String url) {
        this.urlString = url;
    }

    public String getTitle() {
        return title;
    }
    public String getLink(){
        return link;
    }
    public String getDescription(){
        return description;
    }
    public boolean getEndTagState() { return isEndTag; }
    public String getTitleList() {
        Log.i("Rss","The array in the getTitleList method. "+this.titleList.size());
        String ret = null;

        for (String temp : this.titleList) {
            ret = ret + temp + this.linesep;
        }

        return ret;
    }



    /**
     * fextXML
     */
    public void fetchXML() {
        Log.i("Rss","beginning of fetchXML");
        Thread thread = new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    Log.i("Rss","in the try");
                    URL url = new URL(urlString);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(10000 /* milliseconds */);
                    conn.setConnectTimeout(15000 /* milliseconds */);
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);

                    // Starts the query
                    conn.connect();
                    InputStream stream = conn.getInputStream();

                    xmlFactoryObject = XmlPullParserFactory.newInstance();
                    XmlPullParser myparser = xmlFactoryObject.newPullParser();
                    myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                    myparser.setInput(stream, null);

                    Log.i("Rss","before parseXMLAndStoreIt from fetchXML.");
                    parseXMLAndStoreIt(myparser);
                    Log.i("Rss","after parseXMLAndStoreIt from fetchXML.");
                    stream.close();
                } catch (Exception e) {
                }
            }
        });
        thread.start();
        Log.i("Rss","end of fetchXML.");
    }

    /**
     * parseXMLAndStoreIt
     * @param myParser
     */
    public void parseXMLAndStoreIt(XmlPullParser myParser) {
        Log.i("Rss","beginning of parseXMLAndStoreIt.");
        int event;
        String text=null;
        try {
            event = myParser.getEventType();

            System.out.println("before the while loop");

            while (event != XmlPullParser.END_DOCUMENT) {
                String name=myParser.getName();
                switch (event){
                    case XmlPullParser.START_TAG:
                        break;
                    case XmlPullParser.TEXT:
                        text = myParser.getText();
                        break;
                    case XmlPullParser.END_TAG:
                        if(name.equals("title")){
                            this.titleList.add(text);
                        }
                        else if(name.equals("link")){
                            link = text;
                        }
                        else if(name.equals("description")){
                            description = text;
                        }
                        else{
                        }
                        break;
                }

                event = myParser.next();
            }

            System.out.println("after the while loop");
            parsingComplete = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i("Rss","The array after at the end of the method. "+this.titleList.size());
    }
}
HandleXML.java

package com.digitalalias.dndandroid.rss;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {

    private String finalUri = "http://dndandroid.com/feed/";
    private HandleXML obj;
    private TextView tv, link, description;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void fetch(View view) {
        tv = (TextView) findViewById(R.id.textView2);
        tv.setMovementMethod(new ScrollingMovementMethod());
        tv.setText("");  // prep textview for use

        obj = new HandleXML(finalUri);
        obj.fetchXML();

        tv.setText(obj.getTitleList());  // display rss titles
    }

    public void play(View view) {
        TextView textView = (TextView) findViewById(R.id.textView2);
        textView.setText(textView.getText() + " Marc is cool " + finalUri);
        fetch(view);
    }
}
package com.digitalalias.dndandroid.rss;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.os.*;
import android.util.Log;

/**
 * Created by mfferguson on 5/2/2014.
 */
public class HandleXML {

    private String title = "title";
    private String link = "link";
    private String description = "description";
    private List<String> titleList = new ArrayList<String>();
    private boolean isEndTag = false;
    String linesep = System.getProperty("line.separator");

    private String urlString = null;
    private XmlPullParserFactory xmlFactoryObject;
    public volatile boolean parsingComplete = true;

    public HandleXML(String url) {
        this.urlString = url;
    }

    public String getTitle() {
        return title;
    }
    public String getLink(){
        return link;
    }
    public String getDescription(){
        return description;
    }
    public boolean getEndTagState() { return isEndTag; }
    public String getTitleList() {
        Log.i("Rss","The array in the getTitleList method. "+this.titleList.size());
        String ret = null;

        for (String temp : this.titleList) {
            ret = ret + temp + this.linesep;
        }

        return ret;
    }



    /**
     * fextXML
     */
    public void fetchXML() {
        Log.i("Rss","beginning of fetchXML");
        Thread thread = new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    Log.i("Rss","in the try");
                    URL url = new URL(urlString);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(10000 /* milliseconds */);
                    conn.setConnectTimeout(15000 /* milliseconds */);
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);

                    // Starts the query
                    conn.connect();
                    InputStream stream = conn.getInputStream();

                    xmlFactoryObject = XmlPullParserFactory.newInstance();
                    XmlPullParser myparser = xmlFactoryObject.newPullParser();
                    myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                    myparser.setInput(stream, null);

                    Log.i("Rss","before parseXMLAndStoreIt from fetchXML.");
                    parseXMLAndStoreIt(myparser);
                    Log.i("Rss","after parseXMLAndStoreIt from fetchXML.");
                    stream.close();
                } catch (Exception e) {
                }
            }
        });
        thread.start();
        Log.i("Rss","end of fetchXML.");
    }

    /**
     * parseXMLAndStoreIt
     * @param myParser
     */
    public void parseXMLAndStoreIt(XmlPullParser myParser) {
        Log.i("Rss","beginning of parseXMLAndStoreIt.");
        int event;
        String text=null;
        try {
            event = myParser.getEventType();

            System.out.println("before the while loop");

            while (event != XmlPullParser.END_DOCUMENT) {
                String name=myParser.getName();
                switch (event){
                    case XmlPullParser.START_TAG:
                        break;
                    case XmlPullParser.TEXT:
                        text = myParser.getText();
                        break;
                    case XmlPullParser.END_TAG:
                        if(name.equals("title")){
                            this.titleList.add(text);
                        }
                        else if(name.equals("link")){
                            link = text;
                        }
                        else if(name.equals("description")){
                            description = text;
                        }
                        else{
                        }
                        break;
                }

                event = myParser.next();
            }

            System.out.println("after the while loop");
            parsingComplete = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i("Rss","The array after at the end of the method. "+this.titleList.size());
    }
}
package com.digitalalias.dndandroid.rss;
导入java.io.InputStream;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.util.ArrayList;
导入java.util.List;
导入org.xmlpull.v1.XmlPullParser;
导入org.xmlpull.v1.XmlPullParserFactory;
导入android.os.*;
导入android.util.Log;
/**
*由mfferguson于2014年5月2日创建。
*/
公共类HandleXML{
私有字符串title=“title”;
私有字符串link=“link”;
私有字符串description=“description”;
私有列表标题列表=新的ArrayList();
私有布尔值isEndTag=false;
字符串linesep=System.getProperty(“line.separator”);
私有字符串urlString=null;
私有XmlPullParserFactoryXmlFactoryObject;
public volatile boolean parsingplete=true;
公共HandleXML(字符串url){
this.urlString=url;
}
公共字符串getTitle(){
返回标题;
}
公共字符串getLink(){
返回链接;
}
公共字符串getDescription(){
返回说明;
}
公共布尔getEndTagState(){return isEndTag;}
公共字符串getTitleList(){
Log.i(“Rss”,“getTitleList方法中的数组”。+this.titleList.size());
字符串ret=null;
for(字符串温度:此标题列表){
ret=ret+temp+this.linesep;
}
返回ret;
}
/**
*fextXML
*/
public void fetchXML(){
Log.i(“Rss”,“fetchXML的开头”);
Thread Thread=新线程(new Runnable(){
@凌驾
公开募捐{
试一试{
Log.i(“Rss”,“在尝试中”);
URL=新URL(URL字符串);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setReadTimeout(10000/*毫秒*/);
conn.setConnectTimeout(15000/*毫秒*/);
conn.setRequestMethod(“GET”);
conn.setDoInput(真);
//启动查询
连接();
InputStream=conn.getInputStream();
xmlFactoryObject=XmlPullParserFactory.newInstance();
XmlPullParser myparser=xmlFactoryObject.newPullParser();
setFeature(XmlPullParser.FEATURE_进程_名称空间,false);
setInput(流,空);
i(“Rss”,“在ParseXmlandStorefromFetchXML之前”);
parseXMLAndStoreIt(myparser);
i(“Rss”,“在ParseXmlandStoreItfromFetchXML之后”);
stream.close();
}捕获(例外e){
}
}
});
thread.start();
i(“Rss”,“fetchXML的结尾”);
}
/**
*parseXMLAndStoreIt
*@param myParser
*/
public void parseXMLAndStoreIt(XmlPullParser myParser){
Log.i(“Rss”,“parseXMLAndStoreIt的开始”);
int事件;
字符串文本=空;
试一试{
event=myParser.getEventType();
System.out.println(“while循环之前”);
while(event!=XmlPullParser.END_文档){
String name=myParser.getName();
开关(事件){
case XmlPullParser.START_标记:
打破
case XmlPullParser.TEXT:
text=myParser.getText();
打破
case XmlPullParser.END_标记:
如果(名称等于(“头衔”)){
此.titleList.add(文本);
}
else if(name.equals(“link”)){
链接=文本;
}
else if(name.equals(“description”)){
描述=文本;
}
否则{
}
打破
}
event=myParser.next();
}
System.out.println(“while循环之后”);
parsingComplete=false;
}捕获(例外e){
e、 printStackTrace();
}
Log.i(“Rss”,“方法末尾后面的数组”。+this.titleList.size());
}
}

在HandleXML类中,fetchXML方法创建一个新线程,并对其调用start()方法。因此,它产生了一个获取XML的新线程。主线程没有“等待新创建的线程完成执行”。因此,主线程继续执行并调用getTitleList()方法


如果希望fetchXML方法是异步的并生成新线程,那么应该在getTitleList()方法中使用一些阻塞逻辑,以查看线程是否仍在运行,并等待它完成执行。

感谢您为我选择了正确的路径。我最终学会了如何正确使用AsyncTask。