每当我单击按钮时,我的应用程序就会崩溃。我究竟做错了什么?
public void onClick(View v) {
int primaryLength = PRIMARY.length;
final String primaryText = PRIMARY[rnd.nextInt(primaryLength)];
int secondaryLength = SECONDARY.length;
final String secondaryText = SECONDARY[rnd.nextInt(secondaryLength)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
final TextView textTwo = (TextView)findViewById(R.id.textView2);
textOne.setText(primaryText);
textTwo.setText(secondaryText);
String primeT = primaryText;
Uri media = Uri.parse(primeT);
mpButtonOne = MediaPlayer.create(MainActivity.this, media);
mpButtonOne.start();
mpButtonOne.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mpButtonOne) {
String primeS = secondaryText;
Uri media2 = Uri.parse(primeS);
mpButtonTwo = MediaPlayer.create(MainActivity.this, media2);
mpButtonTwo.start();
mpButtonTwo.setOnCompletionListener(new soundListener1());
{
}
}
我希望将在textviews中显示的随机选择的文本输入为mediaplayer声音文件的位置,这些单词是原始文件夹中声音文件的名称。我有点新,而且真的不确定这是否是正确的解决方法。
09-11 16:50:40.128: E/AndroidRuntime(12531): FATAL EXCEPTION: main
09-11 16:50:40.128: E/AndroidRuntime(12531): java.lang.NullPointerException
09-11 16:50:40.128: E/AndroidRuntime(12531): at com.spunktrunk.nastylittleman.MainActivity$1.onClick(MainActivity.java:62)
09-11 16:50:40.128: E/AndroidRuntime(12531): at android.view.View.performClick(View.java:2408)
09-11 16:50:40.128: E/AndroidRuntime(12531): at android.view.View$PerformClick.run(View.java:8816)
09-11 16:50:40.128: E/AndroidRuntime(12531): at android.os.Handler.handleCallback(Handler.java:587)
09-11 16:50:40.128: E/AndroidRuntime(12531): at android.os.Handler.dispatchMessage(Handler.java:92)
09-11 16:50:40.128: E/AndroidRuntime(12531): at android.os.Looper.loop(Looper.java:123)
09-11 16:50:40.128: E/AndroidRuntime(12531): at android.app.ActivityThread.main(ActivityThread.java:4669)
09-11 16:50:40.128: E/AndroidRuntime(12531): at java.lang.reflect.Method.invokeNative(Native Method)
09-11 16:50:40.128: E/AndroidRuntime(12531): at java.lang.reflect.Method.invoke(Method.java:521)
09-11 16:50:40.128: E/AndroidRuntime(12531): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:876)
09-11 16:50:40.128: E/AndroidRuntime(12531): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:634)
09-11 16:50:40.128: E/AndroidRuntime(12531): at dalvik.system.NativeStart.main(Native Method)
09-11 16:50:40.128: W/ActivityManager(237): Force finishing activity com.spunktrunk.nastylittleman/.MainActivity
最佳答案
根据您的URL,调用Media.create可能返回了空值(look at the documentation here)。如果是这样,则您的代码尝试在null上调用方法,这将导致您的NPE(空指针异常)
您当然可以像这样更改代码:
mpButtonOne = MediaPlayer.create(MainActivity.this, media);
if (mButtonOne==null){
//display a Toast message here
return;
}
mpButtonOne.start();