简体   繁体   中英

Setter sets String value but Getter returns null or default String value

I want to get string value from editText so I use TextWatcher onTextChanged method to set String value on my private String cName . And it sets and gets right value.

@TargetApi(11)
@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup parent, Bundle savedInstanceState){

    View v = inflater.inflate(R.layout.fragment_add,parent,false);

    dNameText = (EditText) v.findViewById(R.id.d_name);
    dNameText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            dCloud.setName(s.toString());
            Log.e(TAG,"name " + dCloud.getName());
        }

    });

here is my setter and getter public class

private String cName = "ggg";

public String getName(){return cName;}

public void setName(String name) {cName = name;}

but when I want to use getter in other method or some where else I always getting private String cName default value "ggg" or if I leave empty I'm getting null. Why private String cName not staying on setted value and how I can fix it?

The value of cName won't change unless your TextView's text is changed from the UI.

I suggest that, before you use cName anywhere in your code, you test it for its default values (or simply null):

If cName equals its default value then the user haven't changed the text field yet. Else, then the text field has changed and you get the new value by calling getName().

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM