Java->;需要上下文、表达式吗?
我正试图通过Java和Android Studio学习并制作一个Android应用程序。我对Java的了解是两年前在youtube上学习几个小时和一门基础大学课程。但是我知道如何编码。我精通Python 我希望使用这个蓝牙库(),这样我就可以简单地在手机和支持蓝牙的ESP32微控制器之间进行通信 在我的项目中,我创建了一个按钮,用于测试这个库Java->;需要上下文、表达式吗?,java,android,android-context,Java,Android,Android Context,我正试图通过Java和Android Studio学习并制作一个Android应用程序。我对Java的了解是两年前在youtube上学习几个小时和一门基础大学课程。但是我知道如何编码。我精通Python 我希望使用这个蓝牙库(),这样我就可以简单地在手机和支持蓝牙的ESP32微控制器之间进行通信 在我的项目中,我创建了一个按钮,用于测试这个库 *snip* //my button Button btn = findViewById(R.id.myBtn); //u
*snip*
//my button
Button btn = findViewById(R.id.myBtn); //use R.id for the button id
btn.setOnClickListener(new View.OnClickListener() { //button listener
@Override
public void onClick(View v) {
//add whatever code here
Log.e("my app", "log msg test"); //outputs to logcat window
BluetoothSPP bt = new BluetoothSPP(Context);
if(!bt.isBluetoothAvailable()) {
Log.e("my app", "bluetooth is not available");
} else {
Log.e("my app", "bluetooth is available");
}
}
*snip*
我被困在:
BluetoothSPP bt = new BluetoothSPP(Context);
上下文给了我一个错误,表示表达式应为。我查看了Java中的上下文,并理解了为什么会这样。但是,我不知道如何实现它,更不用说这里的正确上下文了。如果您的代码位于从Activity类继承的类中 i、 e.类MainActivity扩展了活动 你可以试着这样传球:
BluetoothSPP bt = new BluetoothSPP(MainActivity.this);
BluetoothSPP bt = new BluetoothSPP(getContext());
(因为活动正在实现上下文)
如果它位于视图类或片段等内部,则应尝试以下操作:
BluetoothSPP bt = new BluetoothSPP(MainActivity.this);
BluetoothSPP bt = new BluetoothSPP(getContext());
如果您的代码位于从活动类继承的类中 i、 e.类MainActivity扩展了活动 你可以试着这样传球:
BluetoothSPP bt = new BluetoothSPP(MainActivity.this);
BluetoothSPP bt = new BluetoothSPP(getContext());
(因为活动正在实现上下文)
如果它位于视图类或片段等内部,则应尝试以下操作:
BluetoothSPP bt = new BluetoothSPP(MainActivity.this);
BluetoothSPP bt = new BluetoothSPP(getContext());
如果是为了活动
BluetoothSPP bt = new BluetoothSPP(MainActivity.this);
or
BluetoothSPP bt = new BluetoothSPP(this);
or
BluetoothSPP bt = new BluetoothSPP(getApplicationContext());
如果它是碎片
BluetoothSPP bt = new BluetoothSPP(getActivty());
如果是为了活动
BluetoothSPP bt = new BluetoothSPP(MainActivity.this);
or
BluetoothSPP bt = new BluetoothSPP(this);
or
BluetoothSPP bt = new BluetoothSPP(getApplicationContext());
如果它是碎片
BluetoothSPP bt = new BluetoothSPP(getActivty());
您需要发布准确的错误消息。“Context”几乎肯定不会给你一个错误,但是编译器会告诉你,“Context”是它能指向你的最接近的项目。(直接的问题是,
Context
是类的名称,您应该提供变量或方法调用的结果。)您需要发布准确的错误消息。“Context”几乎肯定不会给你一个错误,但是编译器会告诉你,“Context”是它能指向你的最接近的项目。(眼前的问题是,Context
是一个类的名称,您应该提供一个变量或方法调用的结果。)感谢您为我解释一下上下文。getApplicationContext()也起到了作用。感谢您为我解释一下上下文。getApplicationContext()也起到了作用。