从Android活动类调用接口方法

时间:2016-02-17 11:23:38

标签: java android android-layout android-fragments

以下是接口类

public interface ICasAuthentication {
    String getTicketGrantingTicket(String username, String password, String hostUrl, String casUrl);
}

这是实现接口的类方法。

public class CasAuthentication  implements ICasAuthentication{
    private IServiceHandler _iServiceHandler = null;
    public CasAuthentication(IServiceHandler iServiceHandler)
    {
        this._iServiceHandler = iServiceHandler;

    }
}

 public String getTicketGrantingTicket(String username, String password, String hostUrl, String casUrl) {
        Map<String,String> postData = new HashMap<String,String>();
        postData.put("username", username);
        postData.put("password", password);
        postData.put("hostUrl", hostUrl);
       String response = _iServiceHandler.makeServiceCallString(casUrl, MethodTypes.POST.toString(), postData);
        return null;
    }
}

现在我将android活动类作为下面的代码。我想从我的android类中调用ICasAuthentication方法。我怎样才能完成这项任务。

public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        String username = "test";
        String Password = "test2";
        String hostUrl= "";
        String casUrl= "";
    }
}

3 个答案:

答案 0 :(得分:4)

要调用接口方法,必须创建已实现类的对象,然后可以使用该对象引用该函数。 例如:

 public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor>,IServiceHandler {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ............
        ............
        ............
        CasAuthentication casAuthentication = new CasAuthentication(this);
        String expectedResult = casAuthentication.getTicketGrantingTicket(username, password, hostUrl, casUrl)

    }}

答案 1 :(得分:0)

您应该尝试为此实施model class

答案 2 :(得分:-1)

如果我理解正确,你可以实例化该类并调用这样的方法:

ICasAuthentication myClass = newCasAuthentication(new IServiceHandler());
myClass.getTicketGrandingTicket(...);