Android:方法回调不工作



我正在尝试使用反射实现方法回调,但它没有调用所需的方法。这是我的主要活动

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RetrofitCalls retrofitCalls = new RetrofitCalls();
        retrofitCalls.requestAccesstoken();
        retrofitCalls.requestDataFromServer(MainActivity.this,"onCountryListReceived");
    }
    public void onCountryListReceived(JsonObject jsonObject)
    {
        String temp = "hello";
    }
}

这是requestDataServer方法

 public void requestDataFromServer(final Activity activity, final String callBackMethod){
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(new HeaderInterceptor())
            .build();
    retrofit = new Retrofit.Builder()
            .baseUrl(Constants.ROOT_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();
    Api api = retrofit.create(Api.class);
    Call<JsonObject> call = api.getDataFromServer(Constants.COUNTRY_LIST);
    call.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            if(response.errorBody() != null){
                try {
                    String j1 = response.errorBody().string();
                    String temp = "hello";
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else if(response.body() != null) {
                JsonObject jsonObject = response.body();
                JsonArray jsonArray = jsonObject.getAsJsonArray("Data");
                String temp = "hello";
                try {
                    String x = activity.getClass().toString();
                    Method method = activity.getClass().getDeclaredMethod(callBackMethod.trim(),Object.class);
                    method.invoke(activity,jsonObject);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            String temp = "hello";
        }
    });
}

为什么没有调用onCountryListReceived ?它给出了NoSuchMethodException。有什么问题吗?

在getDeclaredMethod中传入JsonObject.class而不是Object.class,因为它是要调用的方法的参数。
getDeclaredMethod接受两个参数
1。回调方法名称

相关内容

  • 没有找到相关文章

最新更新