我正在尝试修改应用程序以添加其他功能。我有一个看起来像这样的函数
public class MainActivity extends Activity implements RadioGroup.OnCheckedChangeListener {
private static final int REQUEST_SELECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
public static final String TAG = "nRFUART";
private static final String TAG1 = "smsTAG";
private static final int UART_PROFILE_CONNECTED = 20;
private static final int UART_PROFILE_DISCONNECTED = 21;
public static String content = null;
private int mState = UART_PROFILE_DISCONNECTED;
private UartService mService = null;
private BluetoothDevice mDevice = null;
private BluetoothAdapter mBtAdapter = null;
private ListView messageListView;
private ArrayAdapter<String> listAdapter;
public Button btnConnectDisconnect,btnSend;
private EditText edtMessage;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBtAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
}else{
btnConnectDisconnect=(Button) findViewById(R.id.btn_select);
btnSend=(Button) findViewById(R.id.sendButton);
edtMessage = (EditText) findViewById(R.id.sendText);
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
messageListView = (ListView) findViewById(R.id.listMessage);
listAdapter = new ArrayAdapter<String>(this, R.layout.message_detail);
messageListView.setAdapter(listAdapter);
messageListView.setDivider(null);
//Call receiveBroadCast like this
receiveBroadCast(getIntent().getStringExtra("message"));
service_init();
}
...
// Handle Send button
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.sendText);
// String message = editText.getText().toString();
String message = content;
byte[] value;
try {
//send data to service
value = message.getBytes("UTF-8");
mService.writeRXCharacteristic(value);
//Update the log with time stamp
String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
listAdapter.add("["+currentDateTimeString+"] TX: "+ message);
messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
edtMessage.setText("");
Log.i(TAG1, "success, value: " + value + " message: " + message);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i(TAG1, "fail" + e.toString());
}
}
});
...
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void receiveBroadCast(String text) {
btnSend=(Button) findViewById(R.id.sendButton);
Log.i(TAG1, "test " + text);
try {
Log.i(TAG1, "success " + text);
content = text;
btnSend.performClick();
} catch (Exception e) {
Log.i(TAG1, "fail " + e.toString());
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
但是当我运行代码时,我得到了错误
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
这是包含我的按钮的main.xml文件
<Button
android:id="@+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="0dp"
android:layout_marginBottom="0dp"
android:enabled="false"
android:text="Send" />
您知道导致此错误的原因是什么吗?
每当我向我的receiveBroadcast提供一个字符串时,我都试图使我的receiveBroadcast自动单击sendButton。
这是我用来调用receiveBroadcast的SMSReceiver类:
public class SmsReceiver extends BroadcastReceiver {
private static final String TAG = "MyBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null){
try{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
String msgBody = msgs[i].getMessageBody();
Log.i(TAG, " success " + msgBody);
MainActivity Text = new MainActivity();
Text.receiveBroadCast(msgBody);
Intent intentsms = new Intent(context, MainActivity.class);
intentsms.putExtra("message", msgBody);
context.startActivity(intentsms);
}
} catch(Exception e) {
Log.i(TAG, e.toString());
}
}
}
}
}
答案 0 :(得分:0)
为了那件事为您工作。您将必须发送 LocalBroadCastManager到MainActivity,在那里您将必须获得 数据来执行您的操作。
检查以下实现:
public class MainActivity extends Activity implements RadioGroup.OnCheckedChangeListener {
private static final int REQUEST_SELECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
public static final String TAG = "nRFUART";
private static final String TAG1 = "smsTAG";
private static final int UART_PROFILE_CONNECTED = 20;
private static final int UART_PROFILE_DISCONNECTED = 21;
public static String content = null;
private int mState = UART_PROFILE_DISCONNECTED;
private UartService mService = null;
private BluetoothDevice mDevice = null;
private BluetoothAdapter mBtAdapter = null;
private ListView messageListView;
private ArrayAdapter<String> listAdapter;
public Button btnConnectDisconnect,btnSend;
private EditText edtMessage;
private BroadcastReceiver myMessageRec = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
receiveBroadCast(message);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocalBroadcastManager.getInstance(MainActivity.this).registerReceiver(myMessageRec,
new IntentFilter("myMessage"));
btnConnectDisconnect = (Button) findViewById(R.id.btn_select);
btnSend = (Button) findViewById(R.id.sendButton);
edtMessage = (EditText) findViewById(R.id.sendText);
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
messageListView = (ListView) findViewById(R.id.listMessage);
listAdapter = new ArrayAdapter<String>(this, R.layout.message_detail);
messageListView.setAdapter(listAdapter);
messageListView.setDivider(null);
service_init();
// Handle Send button
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.sendText);
// String message = editText.getText().toString();
String message = content;
byte[] value;
try {
//send data to service
value = message.getBytes("UTF-8");
mService.writeRXCharacteristic(value);
//Update the log with time stamp
String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
listAdapter.add("[" + currentDateTimeString + "] TX: " + message);
messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
edtMessage.setText("");
Log.i(TAG1, "success, value: " + value + " message: " + message);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i(TAG1, "fail" + e.toString());
}
}
});
}
public void receiveBroadCast(String text) {
Log.i(TAG1, "test " + text);
try {
Log.i(TAG1, "success " + text);
content = text;
btnSend.performClick();
} catch (Exception e) {
Log.i(TAG1, "fail " + e.toString());
}
}
@Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(MainActivity.this).unregisterReceiver(myMessageRec);
super.onDestroy();
}
}
SmsReceiver将如下所示:
public class SmsReceiver extends BroadcastReceiver {
private static final String TAG = "MyBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
}
Intent intentsms = new Intent("myMessage");
intentsms.putExtra("message", str);
LocalBroadcastManager.getInstance(context).sendBroadcast(intentsms);
}
}
}