Search code examples
android-fragmentsandroid-studioandroid-asynctaskandroid-studio-2.0

How to delegate class into an Async Task instance?


I could write postAsync = new PostAsync(); postAsync.delegate = this; outside the setOnClickListener which will work smoothly, but I need to write it within setOnClickListener.

public class Sign_inFragment extends Fragment implements AsyncResponse {
PostAsync postAsync;

String email, password, logInResult;
EditText ev, pv;
Button bv;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.sign_in_fragment, container, false);

    bv = (Button) v.findViewById(R.id.signinButton);
    ev = (EditText) v.findViewById(R.id.emailTextView);
    pv = (EditText) v.findViewById(R.id.passwordTextView);

    bv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (ev.getText() != null && pv.getText() != null) {
                email = ev.getText().toString();
                password = pv.getText().toString();

                postAsync = new PostAsync();
                postAsync.delegate = this;//this will not work.
                postAsync.execute(email, password);

                //Toast.makeText(getActivity().getApplicationContext(), "SIGN IN SUCCESFUL", Toast.LENGTH_LONG).show();
            }
        }
    });

    return v;
}

@Override
public void processFinish(String output) {
    logInResult = output;

    if (logInResult.equals("true") ) {
        Intent intent = new Intent(getActivity().getApplicationContext(), SignedInActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    } else if(logInResult.equals("false")) {
        ev.setError("Invalid Account");
    }
}

}

Apparently writing postAsync.delegate = this will not work. Do you have any suggestions?


Solution

  • In your case this is consider as view of button because you are using it inside button click method. If you want to pass fragment you have to write like postAsync.delegate = Sign_inFragment.this or if you want activity then postAsync.delegate = getActivity();