Search code examples
javaandroidandroid-fragmentsgridviewbaseadapter

How can i access fragment layout in parent activity?


I have got a tabpager and fragments. And a frament has got a "GridView". I am using a basedapter innerclass in the fragment parent activity.

But when i want to set adapter to my gridview i m getting nullpointerexception. Because GridView variable is always null.how can solve this issue?

Fragment Parent MainActivity OnCreate Method;

GridView gv = (GridView)findViewById(R.id.gridview); // debugging and always null
gv.setAdapter(new AdapterB(this,WallPaperList)); 

Fragment xml

<!-- TODO: Update blank fragment layout -->
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    />

MyGrid.xml (For populate with adapter)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/imagepart"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Seç"
        android:id="@+id/checkBox" />
</LinearLayout>

Solution

  • You cant acces fragment views like that, becouse they could be not yet in the activity view hierarchy.

    You have to add some method to your fragment, like

    myCustomFragment.setGridAdapter(MyCustomGridViewAdapter adapter)
    

    and in this method in your custom fragment:

    public void setGridAdapter(){
        this.myCustomGridAdapter = adapter;
        GridView gv = (GridView)findViewById(R.id.gridview); 
    
        if(gv != null)
            gv.setAdapter(this.myCustomGridAdapter);
    }