我已经搜索了解决方案但是我的应用程序在启动新活动时仍然崩溃了。没有错误,我也不知道问题所在。希望你们能教导并帮助我解决这个问题。我将发布logcat,androidmanifest.xml,mainactivity.class和main2activity.class,这样你就可以找到出错的地方。
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.BLUETOOTH" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Main2Activity"
android:label="@string/title_activity_main2"
android:theme="@style/AppTheme.NoActionBar"></activity>
</application>
MainActivity.java
package com.example.user.betatesting;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button b1,b2;
EditText ed1,ed2;
TextView tx1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.button);
ed1 = (EditText)findViewById(R.id.editText2);
ed2 = (EditText)findViewById(R.id.editText);
b2 = (Button)findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(ed1.getText().toString().equals("Luqman")&& ed2.getText().toString().equals("Kacax")){
startActivity(new Intent(MainActivity.this, Main2Activity.class));
Toast.makeText(getApplicationContext(),"Login Success",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Wrong Username or Password", Toast.LENGTH_SHORT).show();
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ed2.setText("");
ed1.setText("");
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@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_main, 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);
}
}
MainActivity2.java
package com.example.user.betatesting;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.os.Handler;
public class Main2Activity extends AppCompatActivity {
private final String DEVICE_ADDRESS = "98:D3:31:90:82:9A"; //MAC Address of Bluetooth Module
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
private BluetoothDevice device;
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
Thread thread;
byte buffer[];
boolean stopThread;
boolean connected = false;
String command;
Button lock_state_btn, bluetooth_connect_btn;
TextView lock_state_text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lock_state_btn = (Button) findViewById(R.id.lock_state_btn);
bluetooth_connect_btn = (Button) findViewById(R.id.bluetooth_connect_btn);
lock_state_text = (TextView) findViewById(R.id.lock_state_text);
bluetooth_connect_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
if(BTinit())
{
BTconnect();
beginListenForData();
// The code below sends the number 3 to the Arduino asking it to send the current state of the door lock so the lock state icon can be updated accordingly
command = "3";
try
{
outputStream.write(command.getBytes());
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
});
lock_state_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
if(connected == false)
{
Toast.makeText(getApplicationContext(), "Please establish a connection with the bluetooth servo door lock first", Toast.LENGTH_SHORT).show();
}
else
{
command = "1";
try
{
outputStream.write(command.getBytes()); // Sends the number 1 to the Arduino. For a detailed look at how the resulting command is handled, please see the Arduino Source Code
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
});
}
void beginListenForData() // begins listening for any incoming data from the Arduino
{
final Handler handler = new Handler();
stopThread = false;
buffer = new byte[1024];
Thread thread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopThread)
{
try
{
int byteCount = inputStream.available();
if(byteCount > 0)
{
byte[] rawBytes = new byte[byteCount];
inputStream.read(rawBytes);
final String string = new String(rawBytes, "UTF-8");
handler.post(new Runnable()
{
public void run()
{
if(string.equals("3"))
{
lock_state_text.setText("Lock State: LOCKED"); // Changes the lock state text
}
else if(string.equals("4"))
{
lock_state_text.setText("Lock State: UNLOCKED");
}
}
});
}
}
catch (IOException ex)
{
stopThread = true;
}
}
}
});
thread.start();
}
//Initializes bluetooth module
public boolean BTinit()
{
boolean found = false;
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter == null) //Checks if the device supports bluetooth
{
Toast.makeText(getApplicationContext(), "Device doesn't support bluetooth", Toast.LENGTH_SHORT).show();
}
if(!bluetoothAdapter.isEnabled()) //Checks if bluetooth is enabled. If not, the program will ask permission from the user to enable it
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter,0);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
if(bondedDevices.isEmpty()) //Checks for paired bluetooth devices
{
Toast.makeText(getApplicationContext(), "Please pair the device first", Toast.LENGTH_SHORT).show();
}
else
{
for(BluetoothDevice iterator : bondedDevices)
{
if(iterator.getAddress().equals(DEVICE_ADDRESS))
{
device = iterator;
found = true;
break;
}
}
}
return found;
}
public boolean BTconnect()
{
try
{
socket = device.createRfcommSocketToServiceRecord(PORT_UUID); //Creates a socket to handle the outgoing connection
socket.connect();
Toast.makeText(getApplicationContext(),
"Connection to bluetooth device successful", Toast.LENGTH_LONG).show();
connected = true;
}
catch(IOException e)
{
e.printStackTrace();
connected = false;
}
if(connected)
{
try
{
outputStream = socket.getOutputStream(); //gets the output stream of the socket
}
catch(IOException e)
{
e.printStackTrace();
}
try
{
inputStream = socket.getInputStream(); //gets the input stream of the socket
}
catch (IOException e)
{
e.printStackTrace();
}
}
return connected;
}
@Override
protected void onStart()
{
super.onStart();
}
}
和Logcat
02-15 22:14:23.340 11317-11317/com.example.user.betatesting E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.betatesting, PID: 11317
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.betatesting/com.example.user.betatesting.Main2Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2706)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1514)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6205)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.user.betatesting.Main2Activity.onCreate(Main2Activity.java:59)
at android.app.Activity.performCreate(Activity.java:6864)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1514)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6205)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
答案 0 :(得分:0)
错误来自MainActivity2文件的第59行。这是因为bluetooth_connect_btn
为空。
这很可能是因为xml布局文件中没有ID为R.id.bluetooth_connect_btn
的按钮。
答案 1 :(得分:0)
这是因为编译器无法找到具有此id的按钮组件。所以请检查活动布局。