【发布时间】:2017-09-28 11:24:48
【问题描述】:
我的函数 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" />`
【问题讨论】:
-
您的“activity_voice”布局中是否有 ID 为“send_voice”的 ImageButton?
-
我的问题和@faffaffaff 一样。如果答案是“否”,那么如果按钮“send_voice”不应该在布局“activity_voice”中,您应该考虑使用LayoutInflater class
-
添加您的 xml 文件。
-
我添加了xml文件也许这可以帮助你解决我的问题。
-
尝试清理并重建您的项目。生成的
R类可能需要重建。