I'm a beginner in programming. I have a function outside of the activity that when the user types inside EditText the application displays an x to clear the form. When I call this function the error occurs:
android.content.res.Resources android.content.Context.getResources ()
on a null object reference at android.content.ContextWrapper.getResources
If I leave within the same class it works, however I will use this function a lot in other activities
I researched a lot but could not find a solution
Activity.java
public class Activity extends AppCompatActivity{
EditText edtName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acitivty);
edtName = (EditText)findViewById(R.id.edt1);
FormControl formcontrol = new FormControl();
formcontrol.ajustaEditText(edtName);
}
}
FormControl.java
public class FormControl extends AppCompatActivity {
public void ajustaEditText(final EditText et){
String value = "";
final Drawable x = getResources().getDrawable( R.drawable.ic_action_navigation_close);
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
et.setCompoundDrawables(null, null, value.equals("") ? null : x, null);
et.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (et.getCompoundDrawables()[2] == null) {
return false;
}
if (event.getAction() != MotionEvent.ACTION_UP) {
return false;
}
if (event.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {
et.setText("");
et.setCompoundDrawables(null, null, null, null);
}
return false;
}
});
et.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
et.setCompoundDrawables(null, null, et.getText().toString().equals("") ? null : x, null);
}
@Override
public void afterTextChanged(Editable arg0) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
}
}