31

我的应用程序中有一个简单的计时器,它每 3 秒运行一次。如果它不在片段类中,它可以完美地工作。但是在片段中我总是遇到错误:只有创建视图层次结构的原始线程才能触及它的视图。

timer = new Timer();

timer.schedule(new TimerTask() {

    @Override
    public void run() {
        String timeStamp = new SimpleDateFormat(
                "yyyy.MM.dd HH:mm:ss").format(Calendar
                .getInstance().getTime());
        System.out.println("TimeStamp: " + timeStamp);
        // Read And Write Register Sample
        port = Integer.parseInt(gConstants.port);
        String refe = "0";// HEX Address
        ref = Integer.parseInt(refe, 16);// Hex to int
        count = 10; // the number Address to read
        SlaveAddr = 1;
        astr = gConstants.ip; // Modbus Device

        InetAddress addr;
        try {
            addr = InetAddress.getByName(astr);
            con = new TCPMasterConnection(addr); // the
            // connection
        } catch (UnknownHostException e2) {
            e2.printStackTrace();
        }

        // 1.Prepare the request
        /************************************/
        Rreq = new ReadMultipleRegistersRequest(ref, count);
        Rres = new ReadMultipleRegistersResponse();

        Rreq.setUnitID(SlaveAddr); // set Slave Address
        Rres.setUnitID(SlaveAddr); // set Slave Address

        // 2. Open the connection
        con.setPort(port);
        try {
            con.connect();
            System.out.println("Kapcsolódva!");
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        con.setTimeout(2500);
        // 3. Start Transaction
        trans = new ModbusTCPTransaction(con);
        trans.setRetries(5);
        trans.setReconnecting(true);
        trans.setRequest(Rreq);

        try {
            trans.execute();
        } catch (ModbusIOException e) {
            e.printStackTrace();
        } catch (ModbusSlaveException e) {
            e.printStackTrace();
        } catch (ModbusException e) {
            e.printStackTrace();
        }
        /* Print Response */
        Rres = (ReadMultipleRegistersResponse) trans
                .getResponse();

        System.out.println("Connected to=  " + astr
                + con.isConnected() + " / Start Register "
                + Integer.toHexString(ref));

        count = 10;
        for (int k = 0; k < count; k++) {
            System.out.println("The value READ: "
                    + Rres.getRegisterValue(k) + " "
                    + Rres.getUnitID());
            ki_adat = ki_adat + Rres.getRegisterValue(k) + "\n";


            // Adatbázisba írás
            ContentValues modbusData = new ContentValues();
            modbusData.put("Value", Rres.getRegisterValue(k)); // tábla
                                                                // +
                                                                // érték
            modbusData.put("timeStamp", timeStamp);
            try {
                gConstants.db.beginTransaction();
                gConstants.db
                        .insert("Modbus", null, modbusData);
                gConstants.db.setTransactionSuccessful();
            } finally {
                gConstants.db.endTransaction();
            }

        }
        kiir.setText(ki_adat);
        ki_adat = "";
    }//run vége

}, 0, 3000);
4

7 回答 7

99

尝试从不是 UI 线程的任何线程访问 UI 元素时会发生此错误。

要从非 UI 线程访问/修改元素,请使用runOnUIThread.

但是,由于您需要从 a 中更改 UI 元素fragmentrunOnUIThread因此应将其调用到拥有 Activity 的片段上。您可以通过getActivity().runOnUIThread().

例如:

timer.schedule(new TimerTask() {
    @Override
    public void run() {
        // Your logic here...

        // When you need to modify a UI element, do so on the UI thread. 
        // 'getActivity()' is required as this is being ran from a Fragment.
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // This code will always run on the UI thread, therefore is safe to modify UI elements.
                myTextBox.setText("my text");
            }
        });
    }
}, 0, 3000); // End of your timer code.

有关详细信息,请参阅以下文档:

  1. Android 片段(特别是getActivity())。
  2. 定时器任务
  3. 在 UI 线程上调用 Runnable。
于 2013-09-06T11:38:30.240 回答
8

你需要使用这个runOnUIThread()函数我有一个例子,当我找到它时我会发布。

你需要给你的计时器一个 MainActivity 的实例,或者看到这个问题我问了Android 图像计时问题,听起来与你试图做的事情相似

public static void updateText(Activity act, resID)
{

 loadingText = (TextView) activity.findViewById(R.id.loadingScreenTextView);
          act.runOnUiThread(new Runnable() 
                {
                     public void run() 
                     {
                       loadingText.setText(resID);

                     }

                });
}
于 2013-09-06T11:34:37.980 回答
3

您正在从另一个线程执行 UI 操作。我建议你使用以下。

runOnUiThread(new Runnable() {  
                @Override
                public void run() {

                    kiir.setText(ki_adat);
                }                   
于 2013-09-06T11:38:12.757 回答
2

2个解决方案:

并将myTextView.setText(str)调用放在对象的run()方法中Runnable

于 2013-09-06T13:13:05.597 回答
1

尝试这个:

textView.post(new Runnable() {
    @Override
    public void run() {
    textView.setText("Hello!"); }
});
于 2017-03-25T22:41:13.933 回答
0

试试这个:把这部分代码放在某个地方,但不要放在活动 onCreate 方法中

public void LoadTable(final String u, final String k) {

    //  runOnUiThread need to be used or error will appear 
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            try {

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                       //method which was problematic and was casing a problem
                       createTable(u, k);
                    }
                });
            } catch (Exception exception) {
                createAndShowDialog(exception, "Error");
            }
            return null;
        }
    }.execute();
}
于 2016-10-14T15:45:50.470 回答
-1

Try this

new CountDownTimer(365*24*60*60, 3000) {

 public void onTick(long millisUntilFinished) {
     String timeStamp = new SimpleDateFormat(
                        "yyyy.MM.dd HH:mm:ss").format(Calendar
                        .getInstance().getTime());
                System.out.println("TimeStamp: " + timeStamp);
                // Read And Write Register Sample
                port = Integer.parseInt(gConstants.port);
                String refe = "0";// HEX Address
                ref = Integer.parseInt(refe, 16);// Hex to int
                count = 10; // the number Address to read
                SlaveAddr = 1;
                astr = gConstants.ip; // Modbus Device

                InetAddress addr;
                try {
                    addr = InetAddress.getByName(astr);
                    con = new TCPMasterConnection(addr); // the
                    // connection
                } catch (UnknownHostException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }

                // 1.Prepare the request
                /************************************/
                Rreq = new ReadMultipleRegistersRequest(ref, count);
                Rres = new ReadMultipleRegistersResponse();

                Rreq.setUnitID(SlaveAddr); // set Slave Address
                Rres.setUnitID(SlaveAddr); // set Slave Address

                // 2. Open the connection
                con.setPort(port);
                try {
                    con.connect();
                    System.out.println("Kapcsolódva!");
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                con.setTimeout(2500);
                // 3. Start Transaction
                trans = new ModbusTCPTransaction(con);
                trans.setRetries(5);
                trans.setReconnecting(true);
                trans.setRequest(Rreq);

                try {
                    trans.execute();
                } catch (ModbusIOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ModbusSlaveException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ModbusException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                /* Print Response */
                Rres = (ReadMultipleRegistersResponse) trans
                        .getResponse();

                System.out.println("Connected to=  " + astr
                        + con.isConnected() + " / Start Register "
                        + Integer.toHexString(ref));

                count = 10;
                for (int k = 0; k < count; k++) {
                    System.out.println("The value READ: "
                            + Rres.getRegisterValue(k) + " "
                            + Rres.getUnitID());
                    ki_adat = ki_adat + Rres.getRegisterValue(k) + "\n";


                    // Adatbázisba írás
                    ContentValues modbusData = new ContentValues();
                    modbusData.put("Value", Rres.getRegisterValue(k)); // tábla
                                                                        // +
                                                                        // érték
                    modbusData.put("timeStamp", timeStamp);
                    try {
                        gConstants.db.beginTransaction();
                        gConstants.db
                                .insert("Modbus", null, modbusData);
                        gConstants.db.setTransactionSuccessful();
                    } finally {
                        gConstants.db.endTransaction();
                    }

                }
                kiir.setText(ki_adat);
                ki_adat = "";
 }

 public void onFinish() {}
}.start();
于 2013-09-06T11:48:31.753 回答