Valentino Ru
Valentino Ru

Reputation: 5052

How to get the actual Activity?

Maybe this is the dumbest question ever, but I'm having a little trouble getting the actual Activity object.

My purpose:

In order to extract error handling from the different Activitys, I made a class ErrorHandler with static methods.

Such a method looks like this for example:

public class ErrorHandler {
    ...
    public static ErrorTuple checkPlaceInput(Activity activity){
        EditText edit = (EditText) activity.findViewById(R.id.et_nbge_place);
        if(edit.getText().toString().equals("") || edit.getText()==null){
            return new ErrorTuple(false, "Please enter a place!");
        }
        return new ErrorTuple(true, "everything is fine");
    }
}

In order to access the findViewById(...) method, I have to pass the Activity as parameter. As I read in different questions here, there is no other way to access Views from outside a running Activity. But, from the Activity itself, how can I access this object? Neither the Context nor the MyActivity.class are exactly the Activity object.

Upvotes: 0

Views: 129

Answers (3)

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

Use this. keyword - it is your object instance. And within Activity scope you can just call findViewById() directly

Upvotes: 0

Khantahr
Khantahr

Reputation: 8528

If you're calling that method from an Activity, just do checkPlaceInput( this ).

Upvotes: 0

molnarm
molnarm

Reputation: 10031

Use this to get the current object. Inside an Activity, you can just call findViewByID without anything before.

Upvotes: 1

Related Questions