0

I'm very new to android programming and am trying to learn by making a minor app to show some pictures in a slideshow kind of way using a LinearLayout inside of a HorizontalScrollView.

I want to be able to add pictures to the LinearLayout dynamically/programmatically. When using findViewById to find my LinearLayout it seems like it is returning null and later when I'm adding images to the layout I get a NullPointerException.

Here's my XML:

<HorizontalScrollView 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:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.xsiand.mtgdigitalbattlefield.MainActivity$PlaceholderFragment"
android:background="@color/purpleGray" >


     <LinearLayout
        android:id="@+id/gallery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

        </LinearLayout>

    </HorizontalScrollView>

And here is my onCreate-method:

public Integer deck[] ={
        R.drawable.card1,
        R.drawable.card2,
        R.drawable.card3,
        R.drawable.card4,
        R.drawable.card5,
        R.drawable.card6,
        R.drawable.card7
};


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getActionBar().hide();

    gallery = (LinearLayout) findViewById(R.id.gallery); // returns null when debugged.




   for(Integer card : deck)
   {    
        ImageView image = new ImageView(this);
        image.setImageResource(card);
        image.setAdjustViewBounds(true);
        gallery.addView(image);          //CRASHES HERE :'(

    }


    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }

}

What can be done to fix this?

xsiand
  • 465
  • 1
  • 4
  • 10
  • change `setContentView(R.layout.activity_main);` with `setContentView(R.layout.name_of_the_layout_with_gallery);` – Blackbelt Jun 06 '14 at 10:16
  • changed to setContentView(R.layout.fragment_main); but instead got and error saying IllegalArgumentException: No view found. Edit: Solved it by removing the following code: if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()) .commit(); – xsiand Jun 06 '14 at 11:35

0 Answers0