- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
所以我正在制作一个 OBDII 蓝牙应用程序,用户可以发送电压等命令(在本例中)并从 OBDII 获取数据。到目前为止,我已经成功将我的移动设备与 OBDII 适配器建立蓝牙连接,现在我需要发送一些基本命令并在 Logcat 中显示它们(暂时)。
我遇到的问题是它无法识别我的 onClick
方法?
Could not find method onClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'getValue'
我确信我在代码中遗漏了一些东西,但我不知道是什么。
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button b1;
BluetoothAdapter mAdapter;
FragmentHostCallback mHost;
BTHandler btHandler;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BTHandler.STATE_CONNECTED:
//setContentView(R.layout.activity_connected);
Intent intent = new Intent(MainActivity.this, Connected.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), R.string.title_connected_to, Toast.LENGTH_SHORT).show();
Log.v("Log", "Connected");
break;
case BTHandler.STATE_NONE:
Toast.makeText(getApplicationContext(), R.string.title_not_connected, Toast.LENGTH_SHORT).show();
break;
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btHandler = new BTHandler(MainActivity.this, mHandler);
b1 = (Button) findViewById(R.id.connect);
mAdapter = BluetoothAdapter.getDefaultAdapter();
//init();
if (mAdapter == null) {
Toast.makeText(getApplicationContext(), R.string.device_not_supported, Toast.LENGTH_LONG).show();
finish();
} else {
if (!mAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1);
}
}
//BTHandler btHandler = new BTHandler(MainActivity.this, mHandler);
//btHandler.connect("");
}
public void onClick(View v) {
int id = v.getId();
String sendMessage = ("AT RV");
switch (id) {
case R.id.connect:
onConnect(); //Operation
Log.v("Log", "Pressed onClick");
break;
case R.id.getValue:
btHandler.write(sendMessage);
Log.v("Log", "getValue" + sendMessage);
break;
}
}
BTHandler.java
public class BTHandler {
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
final ArrayList<String> devices = new ArrayList();
private final Handler mHandler;
private BluetoothAdapter mAdapter;
private BluetoothDevice device;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private BluetoothSocket socket;
private String status;
private int mState;
private boolean connectionStatus = false;
public BTHandler(Context context, Handler handler) { // Konstruktor
mAdapter = BluetoothAdapter.getDefaultAdapter();
mHandler = handler;
}
public void write(String s) {
mConnectedThread.sendRawCommand(s);
}
/*
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
}
}
*/
public void connect(String deviceAddress) {
mConnectThread = new ConnectThread(deviceAddress);
mConnectThread.start();
}
private void guiHandler(int what, int arg1, String obj) {
Message msg = mHandler.obtainMessage();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.sendToTarget();
}
private class ConnectThread extends Thread {
BluetoothSocket tmp = null;
private BluetoothSocket mmSocket;
public ConnectThread(String deviceAddress) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
device = mAdapter.getRemoteDevice(deviceAddress);
BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = mAdapter.getRemoteDevice(deviceAddress);
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
try {
tmp = device.createRfcommSocketToServiceRecord(uuid);
//socket.connect();
//Log.v("connect", "connect");
} catch (IOException e) {
//e.printStackTrace();
//Log.v("exception", "e");
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mAdapter.cancelDiscovery();
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes;
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Log.v("connect", "connect");
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
Log.v("close", "close");
} catch (IOException closeException) {
}
guiHandler(Constants.TOAST, Constants.SHORT, "Connection Failed");
return;
}
guiHandler(Constants.CONNECTION_STATUS, Constants.STATE_CONNECTED, "");
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private ObdMultiCommand multiCommand;
public ConnectedThread(BluetoothSocket socket) {
connectionStatus = true;
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
try {
RPMCommand engineRpmCommand = new RPMCommand();
SpeedCommand speedCommand = new SpeedCommand();
ModuleVoltageCommand voltageCommand = new ModuleVoltageCommand();
while (!Thread.currentThread().isInterrupted()) {
engineRpmCommand.run(mmInStream, mmOutStream); //(socket.getInputStream(), socket.getOutputStream());
speedCommand.run(mmInStream, mmOutStream); //(socket.getInputStream(), socket.getOutputStream());
voltageCommand.run(mmInStream, mmOutStream); //(socket.getInputStream(), socket.getOutputStream());
// TODO handle commands result
Log.d("Log", "RPM: " + engineRpmCommand.getFormattedResult());
Log.d("Log", "Speed: " + speedCommand.getFormattedResult());
Log.v("Log", "Voltage: " + speedCommand.getFormattedResult());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
OBDcmds();
// Keep listening to the InputStream until an exception occurs
while (connectionStatus) {
sendMultiCommand();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// CALL this to MainActivity
public void sendRawCommand(String s) {
try {
//new ObdRawCommand();
} catch (Exception e) {
}
}
private void OBDcmds() { // execute commands
try {
new EchoOffCommand().run(socket.getInputStream(), socket.getOutputStream());
new LineFeedOffCommand().run(socket.getInputStream(), socket.getOutputStream());
new TimeoutCommand(125).run(socket.getInputStream(), socket.getOutputStream());
new SelectProtocolCommand(ObdProtocols.AUTO).run(socket.getInputStream(), socket.getOutputStream()); //ISO_15765_4_CAN
} catch (Exception e) {
Log.v("Log", "e");
// handle errors
}
}
/*
// Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
}
}
*/
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
public void sendMultiCommand() {
try {
// RUN some code here
} catch (Exception e) {
}
}
}
}
编辑:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {...}
@Override
protected void onCreate(Bundle savedInstanceState) {
b1 = (Button) findViewById(R.id.connect);
b1.setOnClickListener(this);
}
Logcat:
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.asabanov.powersupplytool, PID: 26570 java.lang.IllegalStateException: Could not find method onClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'getValue' at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:307) at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:266) at android.view.View.performClick(View.java:5226) at android.view.View$PerformClick.run(View.java:21266) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:168) at android.app.ActivityThread.main(ActivityThread.java:5845) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
W/System.err: com.github.pires.obd.exceptions.UnableToConnectException: Error running 01 42, response: 0142...UNABLETOCONNECT W/System.err: at java.lang.Class.newInstance(Native Method) W/System.err: at com.github.pires.obd.commands.ObdCommand.checkForErrors(ObdCommand.java:203) W/System.err: at com.github.pires.obd.commands.ObdCommand.readResult(ObdCommand.java:123) W/System.err: at com.github.pires.obd.commands.ObdCommand.run(ObdCommand.java:77) W/System.err: at com.example.asabanov.powersupplytool.BTHandler$ConnectedThread.(BTHandler.java:151) W/System.err: at com.example.asabanov.powersupplytool.BTHandler$ConnectThread.run(BTHandler.java:117) V/Log: e
编辑:
private void onConnect() {
ArrayList deviceStrs = new ArrayList();
final ArrayList<String> devices = new ArrayList();
BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
Set pairedDevices = mAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (Object device : pairedDevices) {
BluetoothDevice bdevice = (BluetoothDevice) device;
deviceStrs.add(bdevice.getName() + "\n" + bdevice.getAddress());
devices.add(bdevice.getAddress());
}
}
// show list
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.select_dialog_singlechoice,
deviceStrs.toArray(new String[deviceStrs.size()]));
alertDialog.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
int position = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
String deviceAddress = devices.get(position);
btHandler.connect(deviceAddress);
//btHandler.write();
}
});
alertDialog.setTitle("Paired devices");
alertDialog.show();
}
最佳答案
您应该为您的按钮设置一个 onClickListener。
为此,您需要实现 OnClickListener 接口(interface):
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
创建按钮时,按如下方式设置其 OnClickListener:
b1 = (Button) findViewById(R.id.connect);
b1.setOnClickListener(this);
当单击按钮时,这应该会让您进入 onClick 方法。
编辑:我看到你有两个按钮。对另一个按钮执行相同的操作。不要忘记为 b2 声明一个成员,就像 b1 一样。
Button b2;
b2 = (Button)findViewById(R.id.getValue);
b2.setOnClickListener(this);
关于java - 如何通过蓝牙向 OBDII 适配器发送 ELM327 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36173194/
基本上我想在悬停时使文本带有删除线。这并不容易使用 el [ mouseOver [Font.strike] ] (text "some text") 就像这样 el [ mouseOver [Bac
基本上我想在悬停时使文本带有删除线。这并不容易使用 el [ mouseOver [Font.strike] ] (text "some text") 就像这样 el [ mouseOver [Bac
以下模式匹配至少有两个元素的列表有什么问题pos1和 pos2 ? type Pos = (Float, Float) type Tail = [Pos] tail_cut : Float -> Ta
我想更新 Elm 类型的记录 type CubeData = {currDirection : Vec3, translation : Vec3, transform : Mat4} 我可以使用以下代
假设有两种数据类型: type alias Player = { name : String , team : Team } type alias Team = { name : St
Python 有它们,我发现它们非常有用: def awesome_fn(x, y): """" Calculates some awesome function of x and y
我正在尝试在 Elm 中设计一个功能,该功能解析来自 Json 的数据,然后将其呈现在一个可排序的表中。 当然,我使用解码器将 Json 数据存储在记录列表中;然后在 View 中,我将记录列表转换为
假设我正在尝试遵循 Elm 架构并将我的工作流程拆分为 User s 和 Invoice s 使用 StartApp . 用户有发票,但他们必须登录才能访问它们。 该模型可能看起来像这样: type
我喜欢 React/Redux 的智能和哑组件概念,其中哑组件不处理自己的状态(Dump 组件对外界一无所知,它所做的只是根据其输入触发事件并显示值) .这是微不足道的,因为所有状态都在一个地方处理(
如何在 elm-repl 中找出 Elm 表达式或子表达式的类型? Haskell 的 :type或 :t相当于 Elm REPL 吗? 最佳答案 Elm REPL 会自动打印您输入的任何类型。例如:
在 Elm 中是否可以通过一个事件处理程序触发多个输入句柄?例如,假设我有以下内容: button [ type' "button", on "click" getAnything go.ha
我正在尝试构建一个通用映射函数,该函数将从联合类型中提取可能的内部类型,对内部值应用转换并将其映射回外部类型。 问题是,我需要一种方法来区分外部类型的特定值是否具有内部类型。 如果下面的代码实际编译了
每隔一段时间,您就会遇到如下编译器错误: It looks like the keyword `port` is being used as a variable. 这很烦人。这些关键词有完整的官方列
我刚刚开始考虑使用 Elm 构建一个简单的 Web 应用程序。我的想法是需要在浏览器中保留一些用户数据。 有没有办法直接用 Elm 处理数据持久化?例如在浏览器 session 甚至本地存储中?或者我
我有这个功能 result = add 1 2 |> \a -> a % 2 == 0) 我收到了这个错误 Elm does not use (%) as the remainder operat
编写一个函数将一个列表分成两个列表。第一部分的长度由调用者指定。 我是 Elm 的新手,所以我不确定我的推理是否正确。我认为我需要转换数组中的输入列表,以便我能够按提供的输入数字对其进行切片。我也在语
我正在尝试创建一个简单的Elm项目,仅插入“hello world!”串成div。 这是我的代码: index.html: ELM Course
我正在编写elm程序,该程序应将其输出格式化为HTML列表。我要的功能 inputs = ["first", "second", "third"] 并输出本质上是某种Elm Element,
在 Elm 中,我无法弄清楚什么时候 type 是合适的关键字,什么时候 type 别名 才是合适的。文档似乎没有对此进行解释,我也无法在发行说明中找到这一解释。这是否记录在某处? 最佳答案 我的想法
我刚刚开始学习 Elm,并且在理解为什么将自定义类型传递到期望的方法时遇到类型不匹配的问题......好吧,我称之为部分类型注释. 这是我正在使用的代码: import Graphics.Elemen
我是一名优秀的程序员,十分优秀!