i am stuck within a fragment.below is my fragment code
public class Tab1 extends Fragment {
EditText address,contactNumber,dob;
String adds;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
contactNumber= (EditText)v.findViewById(R.id.editTextcontact);
address= (EditText)v.findViewById(R.id.editText2);
dob= (EditText) v.findViewById(R.id.editText3);
contactNumber.setHint("Your ContactNo Plz");
address.setHint("Your address Plz");
dob.setHint("Your Data Of Birth");
//receive data from main activity
TabedActivity activity = (TabedActivity) getActivity();
String myDataFromActivity = activity.getMyData();
//
adds=address.getText().toString();
return v;
}
public String getData(){
return adds;
}
}
what i want is when this fragment is called from the main activity the text in the edittext should pass to the adds variable.i check it like above but it show me a null value.how could i set this value.?please help
You need return address.getText().toString() and check for null;
Sample:
public String getData(){
if(address != null && address.getText() != null)
return address.getText().toString();
return null; // block NPE
}
In onCreateView you do:
address= (EditText)v.findViewById(R.id.editText2);
and in the same event you then do:
adds=address.getText().toString();
but offcourse the user at this point didn't set its value yet.
That said, it's also important to check when in your activity are you trying to get this value.
You should pass your desired data to fragment from your parent activity while creating fragment. Sample code can be like below
Bundle args = new Bundle();
args.putString("address", address);
fragment.setArguments(args);
Now in your fragment get the value back like
getArguments().getString("address");
Hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.