如何设置文本或从android中的线程发送一个arraylist

时间:2015-05-13 21:38:48

标签: android arraylist

我正在尝试制作一个新闻板,我已经搜索了很多并尝试使用“处理程序”,但总是崩溃

这是原始代码:

public void onViewCreated(final View view, Bundle savedInstanceState) {
    final Handler handler = new Handler();
    final TextView t1 = (TextView) view.findViewById(R.id.txt1);
    final TextView t2 = (TextView) view.findViewById(R.id.txt2);
    final TextView t3 = (TextView) view.findViewById(R.id.txt3);
    new Thread(new Runnable() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        final ArrayList arrayList = XMLPullParser.parse("http://localhost/news.xml", "news", 1, 2, 3);
                        System.out.println(arrayList.size() + "return from arraylist");
                        t1.setText(arrayList.get(0).toString());
                        t2.setText(arrayList.get(1).toString());
                        t3.setText(arrayList.get(2).toString());
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }).start();
}

我这样编辑:

{{1}}

原始代码是suses显示arraylist细节和String,但问题是如何setText。

1 个答案:

答案 0 :(得分:2)

试试这个

   public void onViewCreated(final View view, Bundle savedInstanceState) {
       // main thread
        final Handler handler = new Handler();
        final TextView t1 = (TextView) view.findViewById(R.id.txt1);
        final TextView t2 = (TextView) view.findViewById(R.id.txt2);
        final TextView t3 = (TextView) view.findViewById(R.id.txt3);
        new Thread(new Runnable() {
            @Override
            public void run() {
                      // background thread
                final ArrayList arrayList = XMLPullParser.parse("http://localhost/news.xml", "news", 1, 2, 3);
                System.out.println(arrayList.size() + "return from arraylist");
                handler.post(new Runnable() {
                    public void run() {
                        try {
                          // main thread 
                            t1.setText(arrayList.get(0).toString());
                            t2.setText(arrayList.get(1).toString());
                            t3.setText(arrayList.get(2).toString());
                        } catch (URISyntaxException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }).start();
    }

为了解释发生了什么,你在主线程中创建了一个Handler对象,因为在那里调用onCreateView。

然后你创建了另一个网络线程,该线程进行XML解析,并使用Handler将Runnable传递给UI / Main线程。

处理程序接受按摩/ Runnable,并在主线程上调用它(允许触摸UI的唯一线程)。