如何在android中将不同的回调传递给同一个函数

时间:2018-06-18 06:39:09

标签: java android callback android-volley generic-callback

我是Android新手,我目前正在尝试凌空发布请求并从API获取响应。我做的是在响应成功时调用回调。如果我从单个类调用,这个回调工作正常,例如,说MainActivity回调方法但是如果我尝试从其他类调用则不能正常工作。我试图将volleyAPIService中的回调参数作为通用参数但不能成功。任何形式的帮助都是值得的。

VolleyAPIService.java

public class VolleyAPIService {

    public void volleyPost(final MainActivity.VolleyCallback callback, String URL, Map<String, String> param, Context context) {
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        final Map<String, String> params = param;

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        callback.onSuccess(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {;
                return params;
            }
        };
        requestQueue.add(stringRequest);
    }
}

正如我之前所说,我试图使 volleyPost()的第一个参数更通用,从任何类调用此特定方法但无法成功。

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        companyLogin("abc", "123");
    }

    public interface VolleyCallback {
        void onSuccess(String result);
    }

    public void companyLogin(String companyname, String password) {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String URL = "http://...";
        final Map<String, String> params = new HashMap<String, String>();
        params.put("name", companyname);
        params.put("pwd", password);

        Intent volley_service = new Intent(MainActivity.this, VolleyAPIService.class);
        MainActivity.this.startService(volley_service);

        VolleyAPIService volleyAPIService = new VolleyAPIService();
        volleyAPIService.volleyPost(new VolleyCallback() {
            @Override
            public void onSuccess(String result) {
                //do stuff here
                Log.d("VOLLEY", "onSuccess: " + result);
                if (!result.isEmpty()) {
                    Intent userLoginActivity = new Intent(MainActivity.this, UserLogin.class);
                    startActivity(userLoginActivity);
                } else {
                    AlertDialog.Builder login_failed = new AlertDialog.Builder(MainActivity.this);
                    login_failed.setMessage("Login Failed, invalid credentials")
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            });
                    AlertDialog alert = login_failed.create();
                    alert.show();
                }
            }
        }, URL, params, MainActivity.this);
    }
}

我在volleyPost()

中使用回调来呼叫MainActivity.java

UserLogin.java

public class UserLogin extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_login);

        userLogin("xyz", "456", "1")
    }

    public interface VolleyCallback {
        void onSuccess(String result);
    }

    public void userLogin(String username, String password, String id) {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String URL = "http://...";
        final Map<String, String> params = new HashMap<String, String>();
        params.put("username", username);
        params.put("password", password);
        params.put("compId", id);

        Intent volley_service = new Intent(UserLogin.this, VolleyAPIService.class);
        UserLogin.this.startService(volley_service);

        VolleyAPIService volleyAPIService = new VolleyAPIService();
        volleyAPIService.volleyPost(new VolleyCallback() {
            @Override
            public void onSuccess(String result) {
                //do stuff here
                Log.d("VOLLEY", "onSuccess: " + result);
                if (!result.isEmpty()) {
                    Intent userLoginActivity = new Intent(UserLogin.this, HomePage.class);
                    startActivity(userLoginActivity);
                } else {
                    AlertDialog.Builder login_failed = new AlertDialog.Builder(UserLogin.this);
                    login_failed.setMessage("Login Failed, invalid credentials")
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            });
                    AlertDialog alert = login_failed.create();
                    alert.show();
                }
            }
        }, URL, params, UserLogin.this);
    }
}

我也试着从这个班级打电话给volleyPost()。我知道类型的参数回调不匹配并试图使这两个类的回调参数都通用,我无法想办法做到这一点。

任何形式的帮助都是可以理解的,并提前感谢。

1 个答案:

答案 0 :(得分:1)

我建议您使用单独的接口类,而不要将其保留在ClassActivity内。

所以声明这样的界面。创建一个单独的文件。

public interface VolleyCallback {
    void onSuccess(String result);
}

然后在public类中创建VolleyCallback接口的VolleyAPIService实例,如下所示。从volleyPost方法中删除参数以实现更清洁。

public class VolleyAPIService {

    public VolleyCallback callback; 

    public void volleyPost(String URL, Map<String, String> param, Context context) {
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        final Map<String, String> params = param;

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        callback.onSuccess(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {;
                return params;
            }
        };
        requestQueue.add(stringRequest);
    }
}

现在从MainActivity开始,实现您创建的接口,并覆盖回调函数,如下所示。

public class MainActivity extends AppCompatActivity implements VolleyCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        companyLogin("abc", "123");
    }
    public interface VolleyCallback {
        void onSuccess(String result);
    }

    public void companyLogin(String companyname, String password) {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String URL = "http://...";
        final Map<String, String> params = new HashMap<String, String>();
        params.put("name", companyname);
        params.put("pwd", password);

        Intent volley_service = new Intent(MainActivity.this, VolleyAPIService.class);
        MainActivity.this.startService(volley_service);

        VolleyAPIService volleyAPIService = new VolleyAPIService();

        // Assign the callback here to listen the response from the API service.
        volleyAPIService.callback = this; 
        volleyAPIService.volleyPost(URL, params, MainActivity.this);
    }

    @Override
    public void onSuccess(String result) {
        // Handle the success or failure here
        if (!result.isEmpty()) {
            Intent userLoginActivity = new Intent(MainActivity.this, UserLogin.class);
            startActivity(userLoginActivity);
        } else {
            AlertDialog.Builder login_failed = new AlertDialog.Builder(MainActivity.this);
            login_failed.setMessage("Login Failed, invalid credentials")
                 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                     @Override
                     public void onClick(DialogInterface dialog, int which) {

                     }
                 });

             AlertDialog alert = login_failed.create();
             alert.show();
        }
    }
}

为您的UserLogin课程执行相同操作。

如果在单个ActivityFragment中有多个API调用,您可能希望在VolleyAPIService类中保留一个标志并将其传递给您可以检测到的回调函数您在onSuccess回调中获得的API响应。

希望很清楚。请随时提出任何问题。