33

I've got this simple timer in my app which is runs in every 3 seconds. It works perfectly if it's not in a fragment class. But here in fragment I always got the error: Only the original thread that created a view hierarchy can touch its views.

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);
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
David
  • 2,331
  • 4
  • 29
  • 42

7 Answers7

101

This error occurs when trying to access UI elements from any thread that is not the UI thread.

To access/modify elements from a non-UI-thread, use runOnUIThread.

However as you need to change a UI element from within a fragment, runOnUIThread should be invoked onto the fragments owning activity. You can do this through getActivity().runOnUIThread().

EG:

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.

For further information see the following documentation:

  1. Android Fragments (specifically, getActivity()).
  2. TimerTask.
  3. Invoking a Runnable on the UI thread.
matthewrdev
  • 11,930
  • 5
  • 52
  • 64
8

you need to use the runOnUIThread() function I have an example somwhere that I will post when I find it.

you need to give your timer an instance of MainActivity alternatively see this question I asked Android image timing issues with what sounds like a similar thing to what you were trying to do

public static void updateText(Activity act, resID)
{

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

                     }

                });
}
Community
  • 1
  • 1
Cob50nm
  • 911
  • 2
  • 9
  • 27
3

You are doing UI operation from another thread. I suggest you to use following.

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

                    kiir.setText(ki_adat);
                }                   
Ritesh Gune
  • 16,629
  • 6
  • 44
  • 72
  • The method runOnUiThread(new Runnable(){}) is undefined for the type new TimerTask(){} – David Sep 06 '13 at 12:27
  • use your_activity_name.runOnUiThread.. – Ritesh Gune Sep 06 '13 at 12:38
  • Fragment1.this.runOnUiThread(new Runnable() { @Override public void run() { // This code will always run on the UI thread, // therefore is safe to modify UI elements. System.out.println("FAszom"); kiir.setText("my text"); } }); same error, and it stops wirking – David Sep 06 '13 at 12:42
  • If you are using it in Fragment, then plz use getActivity().runOnUiThread for further information on runOnUiThread I suggest you to read [this](http://developer.android.com/reference/android/app/Activity.html) – Ritesh Gune Sep 06 '13 at 12:59
2

2 solutions :

And put the myTextView.setText(str) call in the run() method of the Runnable object.

Mickäel A.
  • 9,012
  • 5
  • 54
  • 71
2

Try this:

textView.post(new Runnable() {
    @Override
    public void run() {
    textView.setText("Hello!"); }
});
frapeti
  • 1,090
  • 13
  • 18
0

TRY THIS: put this part of code somewhere but not in activity onCreate method

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();
}
Jevgenij Kononov
  • 1,210
  • 16
  • 11
-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();
Girish Nair
  • 5,148
  • 5
  • 40
  • 61
  • 3
    Oh cool, a riddle. Lets see how much time it takes to find the difference between your answer and the original code in the question. Irony off: -1 for code only answer without explanation what was changed and why. – WarrenFaith Sep 06 '13 at 11:50