Android错误:只有创建视图层次结构的原始线程才能触及其视图

时间:2012-04-18 06:56:18

标签: android views

我读了其他帖子,但没有解决我的问题。我是Android上的新手。我必须连接到MSSQL,但我得到原始线程错误。我怎么解决这个问题?感谢。

这是我的代码:

private class MyThread implements Runnable {
    public void run() {

        durumKontrol();
        if (isConnected) {

            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub

                    kuyrukKontrol();
                }

            }).start();

        } else {
            Toast toast = Toast
                    .makeText(
                            getApplicationContext(),
                            "Ağa erişilemiyor. Lütfen kablosuz ağın açık olduğundan emin olunuz",
                            Toast.LENGTH_LONG);
            toast.show();
        }

        tick_Handler.postDelayed(tick_thread, firstDelay);
        firstDelay = 10000;
    }

}private void kuyrukKontrol() {
    // TODO Auto-generated method stub

    // Hücrenin sipariş ettiği ve henüz getirilmemiş malzemelerin listesi
    // çekiliyor
    TextView tvIP = (TextView) findViewById(R.id.tvIP);
    tvIP.setText(HatAdi + "-" + HucreNo);


    try {
        Class.forName("net.sourceforge.jtds.jdbc.Driver");
        Connection conn = DriverManager
                .getConnection("jdbc:jtds:sqlserver://x.x.x.x:1433",
                        "xx", "xxxxx");

        Statement query = conn.createStatement();

        // İlk olarak bu forklifte ait teslim edilmeyen bir talep var mı
        ResultSet rs = query
                .executeQuery("select * from MOBILE.dbo.fos_SS where hucreNo = '" + HucreNo + "' and sonDurum != 'T'");
        while (rs.next()) {

            KuyrugaEkle(rs.getString("malzemeNo"),rs.getString("sonDurum"),rs.getString("sonIslemZamani"));

        }

        rs.close();
        conn.close();

    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

并且在KuyrugaEkle函数中我动态地改变了布局,我在该函数中遇到错误。

感谢。

2 个答案:

答案 0 :(得分:1)

您不能从main以外的线程修改UI,并且您可以在函数kuyrukKontrol中执行此操作。使用HandlerrunOnUiThread在主线程上执行此操作。

答案 1 :(得分:1)

创建MyThread的Object并在runOnUiThread方法中使用它

MyThread mt = new MyThread();

获取活动的上下文并使用以下代码

Activity a=(Activity)context;
            a.runOnUiThread(mt);

将Applications上下文传递给MyThread类的构造函数,并按照上面的描述使用它。