2012-01-04 11 views
2

この相対レイアウトで最終的に広告を最下部にロードします。メインレイアウトを参照する際のヌルポインタの例外

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:ads="http://schemas.android.com/lib/com.google.ads" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:gravity="center" > 

なぜこれが起こっているすべてのアイデアを:

public class Main extends Activity { 
RelativeLayout mLayout; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);   
    setContentView(R.layout.main); 
    mLayout = (RelativeLayout) findViewById(R.layout.main); 

    ImageView View = new ImageView(this, null);  //example view 

    mLayout.addView(View); 

その後、NULLポインタがmLayoutがレイアウトの

RelativeLayout.LayoutParams rparams = (LayoutParams) mLayout.getLayoutParams(); 

E/AndroidRuntime(4066): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.name.project/com.name.project.Main}: java.lang.NullPointerException

XML呼び出されたときに下に起こりますhえ?

答えて

6

エラーは、この行で発生します。

mLayout = (RelativeLayout) findViewById(R.layout.main); 

それはfindViewByIdメソッドの名前でかなり明白だ - そのIDによってビューを見つけるために使用されますが、あなたが使用してビューを見つけようとしていますレイアウト参照、ID参照ではありません。以下で試してみてください。

また
mLayout = (RelativeLayout) findViewById(R.id.main); 

、あなたのRelativeLayoutandroid:idタグを含める必要があります。 RelativeLayoutに次のXMLを使用してください:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:ads="http://schemas.android.com/lib/com.google.ads" 
android:id="@+id/main" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:gravity="center" >