繁体   English   中英

R无法解析为变量-

[英]R cannot be resolved to a variable --

package br.com.buceta;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
  private static final String TAG = "bluetooth1";

  Button btnOn, btnOff;

  private BluetoothAdapter btAdapter = null;
  private BluetoothSocket btSocket = null;
  private OutputStream outStream = null;

  // SPP UUID service 
  private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

  // MAC-address of Bluetooth module (you must edit this line)
  private static String address = "00:15:FF:F2:19:5F";

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main); (error)

    btnOn = (Button) findViewById(R.id.btnOn); (error)
    btnOff = (Button) findViewById(R.id.btnOff); (error)

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    checkBTState();

    btnOn.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        sendData("1");
        Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
  }
});

btnOff.setOnClickListener(new OnClickListener() {
  public void onClick(View v) {
    sendData("0");
    Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
  }
});
  }

  private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
      if(Build.VERSION.SDK_INT >= 10){
          try {
          final Method  m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
          return (BluetoothSocket) m.invoke(device, MY_UUID);
      } catch (Exception e) {
          Log.e(TAG, "Could not create Insecure RFComm Connection",e);
      }
  }
  return  device.createRfcommSocketToServiceRecord(MY_UUID);
  }

  @Override
  public void onResume() {
super.onResume();

Log.d(TAG, "...onResume - try connect...");

// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);

// Two things are needed to make a connection:
//   A MAC address, which we got above.
//   A Service ID or UUID.  In this case we are using the
//     UUID for SPP.

try {
    btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
    errorExit("Fatal Error", "In onResume() and socket create failed: " + e1.getMessage() + ".");
    }

// Discovery is resource intensive.  Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();

// Establish the connection.  This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
  btSocket.connect();
  Log.d(TAG, "...Connection ok...");
} catch (IOException e) {
  try {
    btSocket.close();
  } catch (IOException e2) {
    errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
  }
}

// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");

try {
  outStream = btSocket.getOutputStream();
} catch (IOException e) {
  errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
  }

  @Override
  public void onPause() {
super.onPause();

Log.d(TAG, "...In onPause()...");

if (outStream != null) {
  try {
    outStream.flush();
  } catch (IOException e) {
    errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
  }
 }

try     {
  btSocket.close();
} catch (IOException e2) {
  errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
      }

   private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
    if(btAdapter==null) { 
  errorExit("Fatal Error", "Bluetooth not support");
} else {
  if (btAdapter.isEnabled()) {
    Log.d(TAG, "...Bluetooth ON...");
  } else {
    //Prompt user to turn on Bluetooth
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, 1);
  }
}
  }

  private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
  }

  private void sendData(String message) {
byte[] msgBuffer = message.getBytes();

Log.d(TAG, "...Send data: " + message + "...");

try {
  outStream.write(msgBuffer);
} catch (IOException e) {
  String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
  if (address.equals("00:00:00:00:00:00")) 
    msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
    msg = msg +  ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";

    errorExit("Fatal Error", msg);       
}
  }
}

R.layout.activity_main中没有错误,但是代码无法识别我在activity_main.xml中声明的按钮。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
    android:id="@+id/btnOff"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/btn_OFF" />

<Button
    android:id="@+id/btnOn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/btnOff"
    android:layout_centerHorizontal="true"
    android:text="@string/btn_ON" />

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:alpha="0.5"
    android:src="@drawable/cxemnet_logo" />

</RelativeLayout>      

附注:我通过“ 清理”>“构建项目 ”解决了“ R无法解析为类型”错误,然后出现了此错误。

您必须声明您的按钮。 您可以在方法中声明它们

    ...
    setContentView(R.layout.activity_main);
    Button btnOn = findViewById(R.id.btnOn);
    Button btnOff = findViewById(R.id.btnOff);
    ...

或作为本地字段

    public class Classname { 

        private Button btnOn;
        private Button btnOff;

        ...
    }

从项目中删除gen文件夹,然后清理整个项目,还删除了活动类中使用的r.class的import语句。

检查清单文件。 您可能忘了声明。 通常是一个活动。

如果其中一个XML文件存在错误,Android将无法正确生成R文件。 也许错误出在其中之一(即布局文件):您是否关闭了所有标签? 有不受支持的属性吗? 也尝试组织导入(在Windows中,快捷方式是CTRL + MAIUSC + O [这是一个声音,而不是零],在Mac中是CMD + MAIUSC + O

Eclipse自动添加了“ R”导入。 除非您尝试从另一个程序包引用资源,否则它是不必要的,可以删除。

例如,如果你有一个包com.package2但你的表现有一个包名com.package1然后在任何类com.package2将需要:

import com.package1.R;

就您而言,它似乎是自动添加的。 删除它(不要使用“组织导入”)和“清理”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM