Question

I'm getting these errors,

The method setContentView(int) is undefined for the type DataEdit

The method getApplicationContext() is undefined for the type DataEdit

The method findViewById(int) is undefined for the type DataEdit 

for the following code:

    public class DataEdit extends Fragment {
SQLiteDatabase db;
SQLiteDatabase d;
Cursor queryAll;

@Override
public void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.dataedit); 
    DBAdapter msdb= new DBAdapter(getApplicationContext(),"adfg", null);        
    db=msdb.getWritableDatabase(); 
    ((EditText)findViewById(R.id.edSpecies)).requestFocus();
}}

What am I missing here? Thanks in advance for patience and wisdom.

Here is revised code...

    public class DataEdit extends Fragment {
SQLiteDatabase db;
SQLiteDatabase d;
Cursor queryAll;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.dataedit, container, false);
    DBAdapter msdb= new DBAdapter(view.getApplicationContext(),"adfg", null);        
    db=msdb.getWritableDatabase(); 
    ((EditText)view.findViewById(R.id.edSpecies)).requestFocus();
    return view;
}
Was it helpful?

Solution

Fragments behave differently from Activities. The view hierarchy in a fragment is created in onCreateView which has to be overridden and returns the View object. findByViewId() is then called on the inflated view itself. See the documentation here

In onCreateView() you inflate your view like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    // your layout
    View view = inflater.inflate(R.layout.dataedit, container, false);

    // find the element in the inflated view
    ((EditText) view.findViewById(R.id.edSpecies)).requestFocus();

    // get the context from the holding activity
    DBAdapter msdb= new DBAdapter(getActivity().getApplicationContext(),"adfg", null);
    ...

    return view;

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top