Android 未更新TextView
我面临一个问题,我已经实现了一个代码,它在日志中正确地向我显示消息,但它没有更新TextView的文本。在这里,我尝试了这个版本。我如何更新它?我也尝试过使用线程,但没有成功。 我在这个StackOverflow平台上看到了很多解决方案,但我找不到任何解决方案Android 未更新TextView,android,multithreading,textview,android-runonuithread,Android,Multithreading,Textview,Android Runonuithread,我面临一个问题,我已经实现了一个代码,它在日志中正确地向我显示消息,但它没有更新TextView的文本。在这里,我尝试了这个版本。我如何更新它?我也尝试过使用线程,但没有成功。 我在这个StackOverflow平台上看到了很多解决方案,但我找不到任何解决方案 package com.example.yousafmoh.seizuredetection; import android.os.Build; import android.os.Bundle; import android.os.
package com.example.yousafmoh.seizuredetection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class ledControl extends AppCompatActivity {
// Button btnOn, btnOff, btnDis;
ImageButton On, Off, Discnt, Abt;
TextView txtMessage;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS); //receive the address of the bluetooth device
//view of the ledControl
setContentView(R.layout.activity_led_control);
//call the widgets
On = (ImageButton)findViewById(R.id.on);
Off = (ImageButton)findViewById(R.id.off);
Discnt = (ImageButton)findViewById(R.id.discnt);
Abt = (ImageButton)findViewById(R.id.abt);
txtMessage = (TextView) findViewById(R.id.txtMessage);
new ConnectBT().execute(); //Call the class to connect
//myBluetoothThread();
//commands to be sent to bluetooth
On.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
turnOnLed(); //method to turn on
}
});
Off.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
turnOffLed(); //method to turn off
}
});
Discnt.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
}
private void myBluetoothThread() {
while(true)
{
if (btSocket!=null)
{
try
{
if(isBtConnected) {
InputStream inputStream = btSocket.getInputStream();
for (int i = 0; i <= inputStream.available(); i++) {
//Log.d("data", inputStream.read() + " "+"ok");
int val = inputStream.read();
if (val == 49) // seizure detected
{
this.runOnUiThread(new Runnable() {
@Override
public void run() {
txtMessage.setText("Seizure Detected!!!");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
Log.d("Message", " Detected");
}
});
Log.d("Message", " Detected");
} else if (val == 48) // no detection
{
this.runOnUiThread(new Runnable() {
@Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
Log.d("Message", "not Detected");
}
});
Log.d("Message", "not Detected");
//, Toast.LENGTH_SHORT).show();
}
}
}
}
catch (IOException e)
{
msg("Error");
}
}
}
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
InputStream inputStream = btSocket.getInputStream();
for(int i = 0 ; i <= inputStream.available();i++)
{
Log.d("data",inputStream.read()+" ");
}
Log.d("Bytes available off",String.valueOf(inputStream.available()));
Log.d("Message off",String.valueOf(inputStream.read()));
//btSocket.getOutputStream().write("0".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
InputStream inputStream = btSocket.getInputStream();
Log.d("Bytes available on",String.valueOf(inputStream.available()));
Log.d("Message on",String.valueOf(inputStream.read()));
Log.d("Message on",inputStream.toString());
btSocket.getOutputStream().write("1".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
// fast way to call Toast
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
public void about(View v)
{
if(v.getId() == R.id.abt)
{
Intent i = new Intent(this, AboutActivity.class);
startActivity(i);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_led_control, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
@Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ledControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
@Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
progress.dismiss();
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
@Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
if(progress!=null)
progress.dismiss();
if(isBtConnected)
{
myBluetoothThread();
}
}
}
}
package com.example.yousafmoh.seasuredetection;
导入android.os.Build;
导入android.os.Bundle;
导入android.os.Handler;
导入android.provider.contacts合同;
导入android.support.v7.app.AppActivity;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.bluetooth.BluetoothSocket;
导入android.content.Intent;
导入android.view.view;
导入android.widget.ImageButton;
导入android.widget.ImageView;
导入android.widget.TextView;
导入android.widget.Toast;
导入android.app.ProgressDialog;
导入android.bluetooth.BluetoothAdapter;
导入android.bluetooth.bluetooth设备;
导入android.os.AsyncTask;
导入java.io.IOException;
导入java.io.InputStream;
导入java.util.UUID;
公共类ledControl扩展了AppCompative活动{
//按钮btnOn、btnOff、btnDis;
图像按钮On、Off、Discnt、Abt;
TextView-txtMessage;
字符串地址=空;
私人进展对话进展;
蓝牙适配器myBluetooth=null;
BluetoothSocket btSocket=null;
私有布尔值isBtConnected=false;
//SPP UUID,找它
静态最终UUID myUUID=UUID.fromString(“00001101-0000-1000-8000-00805F9B34FB”);
@凌驾
创建时受保护的void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent newint=getIntent();
address=newint.getStringExtra(DeviceList.EXTRA_address);//接收蓝牙设备的地址
//LED控制的视图
setContentView(R.layout.activity\u led\u控件);
//调用小部件
On=(ImageButton)findViewById(R.id.On);
Off=(ImageButton)findViewById(R.id.Off);
Discnt=(ImageButton)findViewById(R.id.Discnt);
Abt=(ImageButton)findViewById(R.id.Abt);
txtMessage=(TextView)findViewById(R.id.txtMessage);
new ConnectBT().execute();//调用类进行连接
//myBluetoothThread();
//要发送到蓝牙的命令
On.setOnClickListener(新视图.OnClickListener()
{
@凌驾
公共void onClick(视图v)
{
turnOnLed();//要启用的方法
}
});
Off.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v)
{
turnOffLed();//要关闭的方法
}
});
Discnt.setOnClickListener(新视图.OnClickListener()
{
@凌驾
公共void onClick(视图v)
{
Disconnect();//关闭连接
}
});
}
私有void myBluetoothThread(){
while(true)
{
if(btSocket!=null)
{
尝试
{
如果(isBtConnected){
InputStream InputStream=btSocket.getInputStream();
对于(inti=0;i如果它是一个片段类,请尝试使用它
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
}
});
这是一项活动
this.runOnUiThread(new Runnable() {
@Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
}
});
你可以尝试的另一个解决方案是
您可以使用处理程序
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
txtMessage.setText("Seizure Detected!!!");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
}
});
我在某个地方读过一些文章,认为不应该直接在可运行线程内更新textview。因此,我创建了一个更新textview的函数,然后Runnable run方法调用该函数。看起来是这样的
public class SampleActivity extends AppCompatActivity {
TextView sample;
int counter = 0;
Handler handler;
Runnable runnable;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
sample = findViewById(R.id.sample);
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
counter++;
updateTextView("Counter: " + counter);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
public void updateTextView(String message) {
sample.setText(message);
}
但我尝试在可运行线程中调用sample.setText(“Counter:+Counter”),但它仍然有效。
顺便说一句,这是我的sample.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/sample"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="SAWSAW"
android:textColor="#000"
android:textSize="32dp" />
</LinearLayout>
显示您的xml文件。或者val既不是49也不是48。这就是为什么文本不更新,也在此处显示您的日志消息。显示此类的完整代码并显示xml。@ManishGupta我选中了值它是49和48,它也在if-else语句中显示我的日志。但不更新TextView的文本。是的,我认为会发生这种情况ed也给了我,然后我传递了上下文,它工作了如果上下文有错误,那么它将显示语法错误。它不工作,没有显示任何错误,你明白吗?试着在片段中编写runOnUiThread并检查你会看到。我在活动中使用了它,但在片段中它不工作,我没有检查确切的原因,我使用了postrunnable而不是它,我这次会检查它。如果只更新runnable线程中的TextView,那么这就行了。我已经测试过了。它每秒钟更新一次。输出是计数器:1,每秒钟递增一次。@Meowk你能看一下我给出的有问题的代码吗??