2

我是 android 新手,目前正在尝试发出volley post 请求并从 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

用户登录.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()从这个班级打电话。我知道参数回调的类型不匹配,并试图使这两个类的回调参数通用,但我想不出一种方法来做到这一点。

任何形式的帮助都是可观的,并在此先感谢。

4

1 回答 1

1

我想建议有一个单独的接口类,而不是将其保留在 a ClassorActivity中。

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

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

然后在您的类中创建一个接口public实例,如下所示。从方法中删除参数以实现更清晰的实现。VolleyCallbackVolleyAPIServicevolleyPost

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班级做同样的事情。

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

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

于 2018-06-18T07:03:57.110 回答