Search code examples
androidlistviewspinnerfindby

Error ListView in findViewById


The class is an extension of another class and is experiencing an error when I mess with the listview. Can anyone help me? Layout: GridLayout

XML:

<ListView
    android:id="@+id/lvContexts"
    android:layout_width="899dp"
    android:layout_height="356dp"
    android:layout_column="1"
    android:layout_columnSpan="3"
    android:layout_gravity="left"
    android:layout_row="3"
    android:layout_rowSpan="2" >
</ListView>

Class:

public class EditarContext extends Iniciar {
    ....

    lvContext = (ListView) findViewById(R.id.lvContexts);
ArrayList<String> lvList = (ArrayList<String>) contexts;
ArrayAdapter<String> spArrayAdapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, lvList);
lvContext.setAdapter(spArrayAdapter);
lvContext.setClickable(true);
lvContext.setVisibility(View.VISIBLE);
lvContext.setVisibility(View.GONE);
}

OBS: The contents of the ListView is being picked content spinner.

Errors are these but I do not miss any of them: https://i.sstatic.net/Gdsdt.png


Solution

  • To use findViewByID you should extend the activity. If not, you need to instantiate your activity by passing it as parameter to the constructor.

    EditarContext instance = new EditarContext(this);
    
    ..
    
    public class EditarContext extends Iniciar {
    
    public Activity activity; 
    //.... other attributes 
    
    public EditarContext( Activity _activity){
    
       this.activity = _activity;
    //other initializations...
    
    }
    }
    

    Then you can use findViewById like this:

    lvContext = (ListView)this.activity.findViewById(R.id.lvContexts); 
    

    Hope this helps.