[英]Why is this returning “Unfortunately your app has crashed”?
我絕對是新手,我正在從新波士頓學習編碼。
MainActivity.java:
package com.tipsoftech.fastfart;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer fartsound = MediaPlayer.create(MainActivity.this,
R.raw.fartsound);
Button fartnow = (Button) findViewById(R.id.bFartNow);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Full screen Open
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Full screen Close
fartnow.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
fartsound.start();
}
});
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
tools:context=".MainActivity" >
<ImageButton
android:id="@+id/bFartNow"
android:contentDescription="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/fartnow" />
</RelativeLayout>
我很肯定我沒有弄亂@ drawable /東西。 但是,每當我嘗試在模擬器上運行該應用程序時,它都會顯示“不幸的是,Fast Fart已崩潰。”。 我不確定發生了什么,如果有人幫助我,我真的會喜歡。 我是一名新開發人員,只有14歲。請幫幫我。
您需要在擴大布局后檢索UI元素,否則findViewById
返回null
,因此在fartnow.setOnClickListener
行處返回NullPointerException
,這會使您的應用程序崩潰。
解決方法如下:
Button fartnow;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main); //layout inflated
fartnow = (Button) findViewById(R.id.bFartNow); //now it's ok
如注釋中所指出的, 必須在setContentView()
之前調用requestWindowFeature
請注意,出現此類錯誤時,您應始終讀取/發布您的stacktrace,它應該告訴您發生錯誤的行,並且可以更輕松地調試應用程序。
在onCreate()方法中的setContentView()方法之后編寫此行-
fartnow = (Button) findViewById(R.id.bFartNow);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.