I am building a collector application that continuously scans the Bluetooth and writes the RSSI results in a file, I used this code but it scans and records the data every 5-second.
I want to make it scan and collect the RSSI data every 100 mill second.Please help me to modify this.
private ScanCallback leScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, final ScanResult result) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
// Tried new Handler(Looper.myLopper()) also
#Override
public void run() {
peripheralTextView.append("MAC: " + result.getDevice().getAddress() +","
+ result.getDevice().getName() +","
+ " RSSI: " + result.getRssi() + "\n");
}
});
try {
long TimeStampMillSec = TimeStampMillSec();
String DateTimeToIso8601Datetimehhmmss = DateTimeToIso8601Datetimehhmmss();
JSONObject jsonMsg =new JSONObject();
//Edited by Mansour
jsonMsg.put("BLue",
"6"+","+phoneIMEI+","+DateTimeToIso8601Datetimehhmmss+
","+TimeStampMillSec+","+result.getDevice().getName()
+ "," + result.getRssi());
WriteMessageLog(0, jsonMsg +"\n");
// auto scroll for text view
final int scrollAmount =
peripheralTextView.getLayout().getLineTop(peripheralTextView.getLineCount())
- peripheralTextView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
peripheralTextView.scrollTo(0, scrollAmount);
}
catch (Exception e)
{
e.printStackTrace();
}
}
};`
Related
I am working on a fitness app using Google fit API.
Step data from the API is passed to a method stepDisplayer with e.g. params (3300, "steps").
I am trying to update the progress bar once value == daily1 so that the max of bar is then pbStepBar.setMax(daily2) and again to pbStepBar.setMax(daily3) when value == daily2, while the progress of the bar is always set to value e.g. 3500/4000 then 4102/8000 and 8900/12000.
I tried to use a switch statement comparing the goals to value with a method called setNextGoal(value) with getter and setter methods getCurrentGoal() and setCurrentGoal() as seen below, but that did not work. Max value does not change from daily1 when I run the application and it looks something like this 5050/4000.
What am I doing wrong? Can I replace pbStepBar with another progress bar and and switching visibility?
Layout
<ProgressBar
android:id="#+id/pbStepBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="300dp"
android:layout_height="15dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="5dp"
android:layout_marginTop="25dp"
android:indeterminate="false"
android:scaleY="3"
/>
public class MainActivity {
//these are goals
int daily1 = 4000
int daily2 = 8000
int daily3 = 12000
//set to this onCreate
pbStepBar.setMax = daily1
private void stepDisplayer(final int value, final String field) {
tvHomeSteps = (TextView) findViewById(R.id.tvHomeSteps);
pbStepBar = (ProgressBar) findViewById(R.id.pbStepBar);
setNextGoal(value);
runOnUiThread(new Runnable() {
#Override
public void run() {
tvHomeSteps.setText("today's " + field + " " + value + "/" + dailyStepGoal);
}
});
new Thread(new Runnable() {
#Override
public void run() {
while (value <= getCurrentGoal()) {
handler.post(new Runnable() {
#Override
public void run() {
pbStepBar.setProgress(value);
}
});
try {
Thread.sleep(25);
}
catch (InterruptedException e) {
e.printStackTrace();
}
if (getCurrentGoal() == value) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Well done you reached your daily goal of " + getCurrentGoal() + " " + field,
Toast.LENGTH_LONG).show();
}
});
}
setNextGoal(value);
}
}
}).start();
}
private void setNextGoal (final int value) {
switch (value) {
case dailyStepGoal:
setCurrentGoal(dailyStepGoal + stepGoalIncrement);
pbStepBar.setMax(dailyStepGoal + stepGoalIncrement);
break;
case dailyStepGoal + stepGoalIncrement:
setCurrentGoal(dailyStepGoal + (stepGoalIncrement*2));
pbStepBar.setMax(dailyStepGoal + (stepGoalIncrement*2));
break;
case dailyStepGoal + (stepGoalIncrement*2):
setCurrentGoal(dailyStepGoal + (stepGoalIncrement*3));
pbStepBar.setMax(dailyStepGoal + (stepGoalIncrement*3));
break;
case dailyStepGoal + (stepGoalIncrement*3):
setCurrentGoal(dailyStepGoal + (stepGoalIncrement*4));
pbStepBar.setMax(dailyStepGoal + (stepGoalIncrement*4));
break;
case dailyStepGoal + (stepGoalIncrement*4):
setCurrentGoal(dailyStepGoal + (stepGoalIncrement*5));
pbStepBar.setMax(dailyStepGoal + (stepGoalIncrement*5));
break;
}
}
I found the solution.
I used an int variable currentGoal as seen below to keep track of the current goal. I think the problem was that I was trying to call methods in the activity from the UI thread. I used a simple if statement, don't know why I didn't think of this earlier.
I also tested the solution it works well.
private void stepDisplayer(final int value, final String field) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (value >= currentGoal) {
Toast.makeText(getApplicationContext(), "Well done you reached your daily goal of " + currentGoal + " " + field,
Toast.LENGTH_LONG).show();
currentGoal += stepGoalIncrement;
tvHomeSteps.setText("today's " + field + " " + value + "/" + currentGoal);
}
else {
tvHomeSteps.setText("today's " + field + " " + value + "/" + currentGoal);
}
}
});
new Thread(new Runnable() {
#Override
public void run() {
while (value <= currentGoal) {
handler.post(new Runnable() {
#Override
public void run() {
pbStepBar.setProgress(value);
if (value >= pbStepBar.getMax()) {
pbStepBar.setMax(currentGoal);
pbStepBar.setProgress(value);
}
else {
pbStepBar.setProgress(value);
}
}
});
try {
Thread.sleep(25);
}
catch (InterruptedException e) {
e.printStackTrace();
}
//setNextGoal(pbStepBar, value);
}
}
}).start();
}
I am trying to implement an animation of Markers on a Google Map. The issue I am running into is an Animation being started while another Animation is still happening for a specific Marker.
Is there a way to stop the iteration of a loop, and continue only when
a certain criteria is met?
Get LatLng - Start Animation - Callback Fires (Animation Finished) - Get LatLng.. Etc.
public void animateMarker(final String key, final List<LatLng> latlngList) {
Log.e(TAG, "------------- MARKER " + key + "-------------");
Handler mHandler = new Handler();
mHandler.post(new Runnable() {
final AnimateCarObj animateCarObj = animateCarObjMap.get(key);
final Marker marker = markersHashMap.get(key);
Boolean isAnimationRunning = false;
#Override
public void run() {
final Iterator<LatLng> iterator = latlngList.iterator();
while (iterator.hasNext()) {
if (!(isAnimationRunning)) {
Log.e(TAG, "START -- " + key + ": " + iterator.next().toString());
try {
isAnimationRunning = true;
LatLngInterpolator latlonInter = new LinearFixed();
latlonInter.interpolate(1, marker.getPosition(), iterator.next());
MarkerAnimation.animateMarker(new RunningCallback() {
#Override
public void onFinish() {
Log.e(TAG, "FINISH -- " + key + ": " + iterator.next().toString());
isAnimationRunning = false;
}
}, latlngList.size(), marker, iterator.next(), latlonInter);
} catch (Exception e) {
Log.e(TAG, "EXCEPTION: " + e.getMessage());
e.printStackTrace();
}
}
}
}
});
}
Just use a while loop to stop your iterator logic.
while (iterator.hasNext()) {
// wait
while (!someBooleanConditionToWaitFor) { }
// do your other stuff
// when you're done your other stuff, set it back to false.
someBooleanConditionToWaitFor = false;
}
When your animation has finished, set the condition to true so that it continues. When you're at the end of that iteration, set it back to false so it waits again.
Create a global static boolean flag
public static boolean criteriaMet=false;
After your criteria is met set it to true. Continue the iteration of the loop only if the flag is true.
in my application the user will input a channel they want to subscribe to in an editable text field. Upon clicking the subscribe button, the variable that is placed in my method to subscribe the user should be updated to that of the users choice and then a toast will appear notifying the user that they are subscribed to this channel.
At the bottom, I get the string value that the user inputs in the EditText field, but I don't think I'm putting it in the right place. Can someone take a look at it and let me know what I'm doing wrong? Let me know if I wasn't clear or am missing something and I can try to explain better. Thanks!
public class MainActivity extends ActionBarActivity {
private Button channelSubscribeButton;
private EditText subscribeChannelEditText;
//Declare variable
String subscribeChannel = null;
//-------------------------Access PubNub API-------------------------//
Pubnub pubnub = new Pubnub("pub-c-940c4776-36ff-425f-9677-f1c904a9d57b", "sub-c-cf42b292-a8bf-11e4-85d5-0619f8945a4f");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
channelSubscribeButton = (Button) findViewById(R.id.subscribe_button);
subscribeChannelEditText = (EditText) findViewById(R.id.channel_name);
//-------------------------Subscribe to a Channel to Receive Messages-------------------------//
try {
//THIS IS WHERE I AM INPUTTING THE VARIABLE THAT CONTAINS THE USER INPUTTED TEXT//
//I AM GETTING ERROR THAT SAYS IT CAN'T RESOLVE THE SYMBOL 'subscribeChannel'//
pubnub.subscribe(subscribeChannel, new Callback() {
#Override
public void connectCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : CONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
#Override
public void disconnectCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : DISCONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
public void reconnectCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : RECONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
#Override
public void successCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : " + channel + " : "
+ message.getClass() + " : " + message.toString());
}
#Override
public void errorCallback(String channel, PubnubError error) {
Log.d("PUBNUB", "SUBSCRIBE : ERROR on channel " + channel
+ " : " + error.toString());
}
}
);
} catch (PubnubException e) {
Log.d("PUBNUB", e.toString());
}
public void onChannelButtonClick(View view) {
subscribeChannel = String.valueOf(subscribeChannelEditText.getText());
String yourSubscribeChannel = "Subscribed to the " + subscribeChannel + " Channel";
Toast.makeText(this, yourSubscribeChannel, Toast.LENGTH_LONG).show();
return subscribeChannel;
}
Your subscribeChannel variable is only visible within the scope of your onChannelButtonClick method. Declare it outside along with your instance variables.
public void onChannelButtonClick(View view) {
//here you set it and then it's lost.
String subscribeChannel = String.valueOf(subscribeChannelEditText.getText());
String yourSubscribeChannel = "Subscribed to the " + subscribeChannel + " Channel";
Toast.makeText(this, yourSubscribeChannel, Toast.LENGTH_LONG).show();
}
Instead do:
//declare it.
String subscribeChannel = null;
And then on your method assign the value.
public void onChannelButtonClick(View view) {
//assign it.
subscribeChannel = String.valueOf(subscribeChannelEditText.getText());
String yourSubscribeChannel = "Subscribed to the " + subscribeChannel + " Channel";
Toast.makeText(this, yourSubscribeChannel, Toast.LENGTH_LONG).show();
}
in my project i received error:
02-20 23:32:45.433: E/Receiver(19076): Read: Error
02-20 23:32:45.433: E/Receiver(19076): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
02-20 23:32:45.433: E/Receiver(19076): at android.os.Handler.<init>(Handler.java:200)
02-20 23:32:45.433: E/Receiver(19076): at android.os.Handler.<init>(Handler.java:114)
02-20 23:32:45.433: E/Receiver(19076): at android.app.Activity.<init>(Activity.java:793)
02-20 23:32:45.433: E/Receiver(19076): at stas.tcp.client.SensorsActivity.<init>(SensorsActivity.java:29)
02-20 23:32:45.433: E/Receiver(19076): at stas.tcp.client.SPN_API.invoke_command(SPN_API.java:208)
02-20 23:32:45.433: E/Receiver(19076): at stas.tcp.client.SPN_engine.doInvokeCommand(SPN_engine.java:164)
02-20 23:32:45.433: E/Receiver(19076): at stas.tcp.client.SPN_engine.processPoUART(SPN_engine.java:127)
02-20 23:32:45.433: E/Receiver(19076): at stas.tcp.client.PoUARTSupport.checkPacket(PoUARTSupport.java:65)
02-20 23:32:45.433: E/Receiver(19076): at stas.tcp.client.Receiver.run(Receiver.java:46)
02-20 23:32:45.433: E/Receiver(19076): at java.lang.Thread.run(Thread.java:841)
and i don't know what does it mean for me. I have few threads in my project, and i don't know which made error. When i commented out one and only thred in SensorsActivity.class - error still occured.
--EDIT---
public class SensorsActivity extends Activity implements EventListener, StepCounterListener, LinearAccListener, StepDetectorListener, LightSensorListener, PressureSensorListener, GravitySensorListener, RotationVectorListener, RelativeHumidityListener, ProximitySensorListener, TempSensorListener, AccelerometerSensorListener, GyroSensorListener, MagSensorListener {
public static final long axisssx = 0;
private TextView lightText, pressureText, signText, noiseText, humidityText, linearAccText, proximityText, tempText, accelText, gyroText, magText, rotationText, gravityText, stepDetectorText, stepCounterText;
private LightSensor mLightSensor;
private PressureSensor mPressureSensor;
private RelativeHumiditySensor mRelativeHumidity;
private ProximitySensor mProximitySensor;
private TemperatureSensor mTempSensor;
private AccelerometerSensor mAccelSensor;
private GyroscopeSensor mGyroSensor;
private MagnetometerSensor mMagSensor;
private RotationSensor mRotSensor;
private GravitySensor mGravitySensor;
private StepCounterSensor mStepCounter;
private StepDetectorSensor mStepDetector;
private LinearAccelerometer mLinearAcc;
private NoiseLevel mNoise;
public double amp;
private Handler handler1;
public long accelx, accely, accelz;
private SPN_native spnNative;
private SPN_API spnApi;
private int argsImageLength;
private int actualNrOfArgs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sensors);
lightText = (TextView)findViewById(R.id.rLight);
pressureText = (TextView)findViewById(R.id.rPressure);
humidityText = (TextView)findViewById(R.id.rHumidity);
proximityText = (TextView)findViewById(R.id.rProximity);
tempText = (TextView)findViewById(R.id.rTemp);
accelText = (TextView)findViewById(R.id.rAccel);
gyroText = (TextView)findViewById(R.id.rGyro);
magText = (TextView)findViewById(R.id.rMag);
rotationText = (TextView)findViewById(R.id.rRotation);
gravityText = (TextView)findViewById(R.id.rGravity);
stepCounterText = (TextView)findViewById(R.id.rSCounter);
stepDetectorText = (TextView)findViewById(R.id.rSDetector);
linearAccText = (TextView)findViewById(R.id.rLinearAcc);
signText = (TextView)findViewById(R.id.rSignMotion);
noiseText = (TextView)findViewById(R.id.rNoise);
//SOUND LEVEL CODE:
mNoise = new NoiseLevel();
try {
mNoise.starter();
//Toast.makeText(getBaseContext(), "Sound sensor initiated.", Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler1 = new Handler();
final Runnable r = new Runnable() {
//this.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getBaseContext(), "Working!", Toast.LENGTH_LONG).show();
runOnUiThread(new Runnable() {
#Override
public void run() {
// Get the volume from 0 to 255 in 'int'
//double volume = 10 * mNoise.getTheAmplitude() / 32768;
double volume = mNoise.getTheAmplitude();
int volumeToSend = (int) volume;
noiseText.setText("Volume: " + String.valueOf(volumeToSend));
handler1.postDelayed(this, 250); // amount of delay between every cycle of volume level detection + sending the data out
}
});
}
};
handler1.postDelayed(r, 250);
mLightSensor = new LightSensor(getBaseContext());
mLightSensor.setListener(this);
Log.e("Sensor Activity:" , "LIGHT SENSOR LISTENER ACTIVE");
mPressureSensor = new PressureSensor(getBaseContext());
mPressureSensor.setListener(this);
Log.e("Sensor Activity:" , "PRESSURE SENSOR LISTENER ACTIVE");
mRelativeHumidity = new RelativeHumiditySensor(getBaseContext());
mRelativeHumidity.setListener(this);
mProximitySensor = new ProximitySensor(getBaseContext());
mProximitySensor.setListener(this);
Log.e("Sensor Activity:" , "PROXIMITY SENSOR LISTENER ACTIVE");
mTempSensor = new TemperatureSensor(getBaseContext());
mTempSensor.setListener((TempSensorListener) this);
mAccelSensor = new AccelerometerSensor(getBaseContext());
mAccelSensor.setListener(this);
mGyroSensor = new GyroscopeSensor(getBaseContext());
mGyroSensor.setListener(this);
mMagSensor = new MagnetometerSensor(getBaseContext());
mMagSensor.setListener(this);
mRotSensor = new RotationSensor(getBaseContext());
mRotSensor.setListener(this);
mGravitySensor = new GravitySensor(getBaseContext());
mGravitySensor.setListener(this);
mStepCounter = new StepCounterSensor(getBaseContext());
mStepCounter.setListener(this);
mStepDetector = new StepDetectorSensor(getBaseContext());
mStepDetector.setListener(this);
mLinearAcc = new LinearAccelerometer(getBaseContext());
mLinearAcc.setListener(this);
spnNative = new SPN_native();
spnApi = new SPN_API();
}
public void onLightSensorChanged(int lux){
lightText.setText("LIGHT level: " + lux + " lx");
}
public void onPressureSensorChanged(long pressure){
pressureText.setText("\nPRESSURE: " + pressure + " mPa ");
}
public void onRelativeHumidityChanged(String humidity) {
humidityText.setText("\nRELATIVE HUMIDITY: " + humidity);
}
public void onProximitySensorChanged(int proximity) {
proximityText.setText("\nPROXIMITY: " + proximity);
}
public void onTempSensorChanged(String temperature) {
tempText.setText("\nAMBIENT TEMPERATURE :" + temperature + " celcius degree");
}
public void onAccelSensorChanged(long axisX, long axisY, long axisZ) {
accelText.setText("\nACCELEROMETER: \nX: " + axisX + "nm/s^2 || Y: " + axisY + "nm/s^2 || Z: " + axisZ +"nm/s^2");
}
public void onGyroSensorChanged(long axisX, long axisY, long axisZ) {
gyroText.setText("\nGYROSCOPE: \nX: " + axisX + "nrad/s || Y: " + axisY + "nrad/s || Z: " + axisZ + "nrad/s");
}
public void onMagSensorChanged(long axisX, long axisY, long axisZ) {
magText.setText("\nMAGNETOMETER: \nX: " + axisX + " piko Tesla || Y: " + axisY + " piko Tesla || Z: " + axisZ + " piko Tesla");
}
public void onRotationVectorChanged(long rot1, long rot2, long rot3) {
rotationText.setText("\nROTATION VECTOR: \nYaw: " + rot1 + " nrad || Pitch: " + rot2 + " nrad || Roll: " + rot3 + " nrad");
}
public void onGravitySensorChanged(long gravity1, long gravity2, long gravity3) {
gravityText.setText("\nGRAVITY: \nX: " + gravity1 + "nm/s^2 || Y: " + gravity2 + "nm/s^2 || Z: " + gravity3 + "nm/s^2");
}
public void onStepCounterChanged(int step) {
stepCounterText.setText("\nSTEP CONTER: " + step + " steps");
}
public void onStepDetectorChanged(String step) {
stepDetectorText.setText("\nSTEP DETECTOR: " + step);
}
public void onLinearAccChanged(long axisX, long axisY, long axisZ) {
linearAccText.setText("\nLINEAR ACCELERATION: \nX: " + axisX + "nm/s^2 || Y: " + axisY + "nm/s^2 || Z: " + axisZ + "nm/s^2");
}
#Override
protected void onResume() {
super.onStart();
// Sound based code
// try {
// mNoise = new NoiseLevel();
// mNoise.starter();
// Toast.makeText(getBaseContext(), "Sound sensor initiated.", Toast.LENGTH_SHORT).show();
// } catch (IllegalStateException e) {
// // TODO Auto-generated catch block
// Toast.makeText(getBaseContext(), "On resume, sound sensor messed up...", Toast.LENGTH_LONG).show();
// e.printStackTrace();
// }
if(!mLightSensor.register()){
lightText.setText("\nLight sensor not supported!");
// Toast.makeText(this, "Light sensor not supported!", Toast.LENGTH_SHORT).show();
}
if(!mPressureSensor.register()){
pressureText.setText("\nPressure sensor not supported!");
}
if(!mRelativeHumidity.register()){
humidityText.setText("\nRelative humidity sensor not supported!");
}
if(!mProximitySensor.register()){
proximityText.setText("\nProximity sensor not supported!");
}
if(!mTempSensor.register()){
tempText.setText("\nAmbient temperature sensor not supported!");
}
if(!mAccelSensor.register()){
accelText.setText("\nAccelerometer sensor not supported!");
}
if(!mGyroSensor.register()){
gyroText.setText("\nGyroscope sensor not supported!");
}
if(!mMagSensor.register()){
magText.setText("\nMagnetometer sensor not supported!");
}
if(!mRotSensor.register()){
rotationText.setText("\nRotation Vector sensor not supported!");
}
if(!mGravitySensor.register()){
gravityText.setText("\nGravity sensor not supported!");
}
if(!mStepCounter.register()){
stepCounterText.setText("\nStep counter sensor not supported!");
}
if(!mStepDetector.register()){
stepDetectorText.setText("\nStep detector sensor not supported!");
}
if(!mLinearAcc.register()) {
linearAccText.setText("\nLinear accelerometer not supported!");
}
}
#Override
protected void onPause() {
super.onStop();
}
private void start() throws IllegalStateException, IOException {
mNoise.starter();
}
private void stop() {
// mNoise.stop();
}
private void sleep() {
// mNoise.stop();
}
private static byte[] longToByteArray(long data, int arrayLength) {
byte[] array = new byte[arrayLength];
int n = 0;
for(int i = arrayLength - 1; 0 <= i; --i) {
array[n] = (byte)(data >> i*8);
n++;
}
Log.e("SensorActivity", "longToByteArray array= " + Arrays.toString(array));
return array;
}
}
This question already has answers here:
Android "Only the original thread that created a view hierarchy can touch its views."
(33 answers)
Closed 5 years ago.
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);
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:
Android Fragments (specifically, getActivity()).
TimerTask.
Invoking a Runnable on the UI thread.
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);
}
});
}
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);
}
2 solutions :
Use the View.post(Runnable) method
Use the Activity.post(Runnable) method
And put the myTextView.setText(str) call in the run() method of the Runnable object.
Try this:
textView.post(new Runnable() {
#Override
public void run() {
textView.setText("Hello!"); }
});
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();
}
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();