我的函数send_voice.setOnClickListener(new View.OnClickListener()有问题。我总是遇到同样的错误:
引起:java.lang.NullPointerException:尝试调用虚方法' void android.widget.ImageButton.setOnClickListener(android.view.View $ OnClickListener)'在空对象引用上
这是我的代码:
public class voice extends AppCompatActivity {
// Variables
String name_device;
String adress_device;
int color=0; // color defaut : 0 colo red : 1
private String OUTPUT_FILE;
MediaPlayer mediaPlayer;
MediaRecorder mediaRecorder;
File outFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice);
// Image Button
ImageButton btn_back;
ImageButton btn_accueil;
ImageButton btn_voice;
ImageButton btn_scan;
ImageButton btn_settings;
final ImageButton send_voice;
OUTPUT_FILE= Environment.getExternalStorageDirectory()+ "/audiorecord.wav";
outFile=new File (OUTPUT_FILE);
// Edit Text
EditText freq_value;
// Variables from other activity
name_device= getIntent().getStringExtra("DEVICE_NAME");
adress_device=getIntent().getStringExtra("DEVICE_ADRESS");
// findView by ID
btn_back = (ImageButton) findViewById(R.id.back);
btn_accueil = (ImageButton) findViewById(R.id.accueil);
btn_voice = (ImageButton) findViewById(R.id.voice);
btn_scan = (ImageButton) findViewById(R.id.scan);
btn_settings= (ImageButton) findViewById(R.id.settings);
freq_value = (EditText) findViewById(R.id.freq_value);
send_voice = (ImageButton) findViewById(R.id.send_voice);
send_voice.setOnClickListener(new View.OnClickListener() { // Bouton "send voice"
@Override
public void onClick(View view) {
try {
if (color==0)
{
send_voice.setBackgroundColor(Color.RED);
color=1;
beginRecording();
}
if (color==1)
{
send_voice.setBackgroundColor(Color.BLACK);
color=0;
stopRecording();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
和xml文件:
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_record_voice_over_black_24dp"
android:layout_marginLeft="12dp"
android:layout_marginStart="12dp"
android:id="@+id/send_voice"
android:backgroundTint="@color/colorWhite"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />`
答案 0 :(得分:1)
显然(在查看堆栈跟踪时)这里:
send_voice = (ImageButton) findViewById(R.id.send_voice);
找不到您的ImageButton,这会导致send_voice变量的空引用。确保send_voice已设置。
答案 1 :(得分:0)