Sundus Bokhari Sundus Bokhari - 5 months ago 26
Android Question

Getting Id of a Textview in a fragment OnCreate() method

I am trying to get the Id of a text view in a fragment's

onCreate()
method. It returns
null
everytime.

I want to display my contacts in a fragment. For that at the end of
FetchContact()
method I assign the contact list to
TextView
.

Since my code is returning
null
when I find the
TextView
my application gives
NullPointerException
.
Anyone who could tell me how to get the
Id
of
TextView
of a
Fragment
in
onCreate()
method.

I tried making an object of activity class to get the
TextView
, still the code returned
null
. No luck.

public class ContactsFragment extends Fragment {

public TextView outputtext;
Context context;

class ActivityObj extends Activity{
public TextView text;
Context objContext;
@Override
public void onCreate(Bundle savedInstanceState) {
text =(TextView)findViewById(R.id.textContact);
objContext = getApplicationContext();
super.onCreate(savedInstanceState);
}
}


@Override
public void onCreate(Bundle savedInstanceState) {
ActivityObj obj = new ActivityObj();
super.onCreate(savedInstanceState);
outputtext =(TextView) getView().findViewById(R.id.textContact);
// outputtext= obj.text;
context=getActivity().getApplicationContext();

//fetchContacts();

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

View rootView = inflater.inflate(R.layout.contacts_layout, container, false);
return rootView;
}

Answer

You should use like this on onActivityCreated method

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        TextView tv = (TextView) getActivity().findViewById(R.id.textView1);

        }
    }

Or use callbacks

Comments