Android“只有创build一个视图层次结构的原始线程可以触及其视图。”Fragment中的错误

我在每3秒运行一次的应用程序中就有了这个简单的计时器。 如果它不在片段类中,它会很好地工作。 但是在片段中,我总是得到错误:只有创build视图层次结构的原始线程才能触及其视图。

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); 

Solutions Collecting From Web of "Android“只有创build一个视图层次结构的原始线程可以触及其视图。”Fragment中的错误"

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

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

但是,由于您需要从fragment更改UI元素, runOnUIThread应该在片段拥有活动上调用runOnUIThread 。 你可以通过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. TimerTask 。
  3. 在UI线程上调用一个Runnable。

你需要使用runOnUIThread()函数我有一个例子somwhere,我会发现,当我find它。

你需要给你的计时器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); } }); } 

你正在从另一个线程做UI操作。 我build议你使用以下。

 runOnUiThread(new Runnable() { @Override public void run() { kiir.setText(ki_adat); } 

2解决scheme:

  • 使用View.post(Runnable)方法
  • 使用Activity.post(Runnable)方法

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

试一试:将这部分代码放在某处,但不要放在activity的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(); } 

尝试这个:

 textView.post(new Runnable() { @Override public void run() { textView.setText("Hello!"); } }); 

尝试这个

 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();