如何通过为所有截击操作创建单独的类来在单个活动中调用多个API

时间:2019-05-22 07:04:47

标签: android callback android-volley

我创建了一个单独的类,其中定义了所有有关凌空的知识,在另一个活动中,我直接传递了URL,CONTEXT和Get Response ...

但是在我的 NavDrawerActivity.java 中,如何调用 subCategoryJSON(); 方法,而不必像使用 mainCategoryJSON()那样再次编写我的齐射代码; 方法,我只是简单地传递URL,即方法类型。

这也是我正在使用的正确方法吗,还是需要对代码进行一些修改?我想要的是,无论我在项目中使用API​​还是在其中使用volley的任何地方,我都不必编写代码一次又一次地简单地传递URL,方法类型

VolleyResponseListener.java

public interface VolleyResponseListener {

    void onResponse(String response, String tag);

    void onError(VolleyError error, String tag);
}

CustomStringRequestVolley.java

public class CustomStringRequestVolley {

    private String url;
    private String tag;
    Context ctx;
    private VolleyResponseListener volleyResponseListener;


    public CustomStringRequestVolley(String url, String tag,Context ctx,VolleyResponseListener volleyResponseListener){
        this.url = url;
        this.tag = tag;
        this.ctx=ctx;
        this.volleyResponseListener = volleyResponseListener;
        sendRequest();
    }

    private void sendRequest() {
        final ProgressDialog pDialog = new ProgressDialog(ctx);
        pDialog.setMessage("Loading ...");
        pDialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.GET,url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("catresponse", "response " + response);
                        if (pDialog.isShowing()) {
                            pDialog.dismiss();
                        }
                        volleyResponseListener.onResponse(response, tag);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                });


          stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                     5000,
                     DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                     DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

       VolleySingleton.getInstance(ctx).addToRequestQueue(stringRequest);

    }
}

NavDrawerActivity.java

public class NavDrawerActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, VolleyResponseListener {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nav_drawer);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

      mainCategoryJSON();
       subCategoryJSON(); 
      }


  private void mainCategoryJSON() {

        CustomStringRequestVolley request1 = new CustomStringRequestVolley(URLs.categoryURL, "TAG1", this, this);

    }

    @Override
    public void onResponse(String response, String tag) {

        switch (tag) {
            case "TAG1":
                try {
                    Log.i("Responseeeeeezaq :", response.toString() + "   " + tag);


                  JSONObject obj = new JSONObject(response);

                    JSONArray productArray = obj.getJSONArray("categories");


                    for (int i = 0; i < productArray.length(); i++) {

                        JSONObject productObject = productArray.getJSONObject(i);

                        CategoryModelClass categoryModelClass = new CategoryModelClass();
                        categoryModelClass.setCategoryID(productObject.getInt("Category-Id"));
                        categoryModelClass.setCategoryName(productObject.getString("Category-Name"));
                        categoryModelClass.setCategoryImg(productObject.getString("Category-Image"));
                        categoryArrayList.add(categoryModelClass);

                        Log.d("zpuyi", String.valueOf(categoryArrayList));

                    }

                    categoryAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }

    }

    @Override
    public void onError(VolleyError error, String tag) {
        VolleyLog.e("Error: ", error.getMessage());
    }


  private void subCategoryJSON() {

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URLs.subcategoryURL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("subcategoryJsonResponse", response.toString());

                        try {


                            JSONObject obj = new JSONObject(response);

                            JSONArray productArray = obj.getJSONArray("sub-categories");

                            for (int i = 0; i < productArray.length(); i++) {

                                JSONObject productObject = productArray.getJSONObject(i);

                                SubCategoryModelClass subCategoryModelClass = new SubCategoryModelClass();
                                subCategoryModelClass.setSubCategory_Id(productObject.getInt("Subcategories-Id"));
                                subCategoryModelClass.setCat_id(productObject.getInt("categories-Id"));
                                subCategoryModelClass.setSubCategory_Name(productObject.getString("Subcategories-Name"));
                        subCategoryModelClass.setSubCategory_Img(productObject.getString("Subcategories-Image"));
                                subCategoryModelClassList.add(subCategoryModelClass);

                                Log.d("subCategoryArraylist", String.valueOf(subCategoryModelClassList));

                            }

                            for (int i = 0; i < subCategoryModelClassList.size(); i++) {
                                subcategory_id = subCategoryModelClassList.get(i).getSubCategory_Id();
                                category_id = subCategoryModelClassList.get(i).getCat_id();
                                subcategory_name = subCategoryModelClassList.get(i).getSubCategory_Name();
                             //   subcategory_desc = subCategoryModelClassList.get(i).getSubCategory_Desc();
                                subcategory_image = subCategoryModelClassList.get(i).getSubCategory_Img();
                                Log.d("fdsaff", subcategory_image);

                                SQLiteDatabase database = dbHelper.getWritableDatabase();
                                dbHelper.insertSubCategoryProduct(subcategory_id, category_id, subcategory_name, "https://www.ecrm.sample.in/app/img/"+subcategory_image, database);
                                dbHelper.close();
                            }

                            subCategoryAdapter.notifyDataSetChanged();


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.e("Error: ", error.getMessage());
                    }
                });

        VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
    }


}

1 个答案:

答案 0 :(得分:0)

您已经正确编写了答案,但是您没有在活动类中实现书面的自定义齐射类代码。

首先如下定义排球的接口类,

现在在您编写自定义排球类的java类中实现排球接口,如下所示:

CustomStringRequestVolley.java

public class CustomStringRequestVolley implements volleyCallback {

  public Context context;

  public CustomStringRequestVolley(Context context) {
    this.context = context;
   }


public interface volleyCallback {
  void onSuccess(String result);
  void onError(String error);
}

  public void callGetServer(String URL, final 
      volleyCallback callback){

    if (!checkInternetConnection(context)) {
        showNoInternetDialogue(context);
        return;
    }

    RequestQueue requestQueue = Volley.newRequestQueue(context);
    StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new 
     Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            callback.onSuccess(response);
          }
    }, error -> {

        if (error.networkResponse == null){

            if (error.getClass().equals(TimeoutError.class)){
                Toast.makeText(context, "Timeout.Please try again", 
Toast.LENGTH_SHORT).show();
            }else if (error.getClass().equals(NoConnectionError.class)){
                Toast.makeText(context, "Timeout.Please try again", Toast.LENGTH_SHORT).show();
            }else if (error.getClass().equals(NetworkError.class)) {
                Toast.makeText(context, "Network Error.Please try again", Toast.LENGTH_SHORT).show();
            }else if (error.getClass().equals(ParseError.class)){
                Toast.makeText(context, "Parse error", Toast.LENGTH_SHORT).show();
            }else if (error.getClass().equals(ServerError.class)){
                Toast.makeText(context, "Server Error.Please try again", Toast.LENGTH_SHORT).show();
            }
            else {
                parseVolleyError(error);

            }
        }

    }
    ) {
        @Override
        protected Map<String, String> getParams() {
            return new HashMap<>();
        }

        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            return headers;
        }

    };
    //setting up the retry policy for slower connections
    int socketTimeout = 120000;//120000 milli seconds - change to what you want
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 
    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    stringRequest.setRetryPolicy(policy);

    requestQueue.add(stringRequest);
}

}

现在在您需要的每项活动中使用此自定义凌空类。它减少你   样板代码

NavDrawerActivity.java

CustomStringRequestVolley customStringRequestVolley;

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

  customStringRequestVolley = new CustomStringRequestVolley(this); 
 }

private void subCategoryJSON() {
    customStringRequestVolley.callGetServer(URLs.subcategoryURL,new volleyCallback() {
        @Override
        public void onSuccess(String result) {

            try {
                        JSONObject obj = new JSONObject(response);

                        JSONArray productArray = obj.getJSONArray("sub-categories");

                        for (int i = 0; i < productArray.length(); i++) {

                            JSONObject productObject = productArray.getJSONObject(i);

                            SubCategoryModelClass subCategoryModelClass = new SubCategoryModelClass();
                            subCategoryModelClass.setSubCategory_Id(productObject.getInt("Subcategories-Id"));
                            subCategoryModelClass.setCat_id(productObject.getInt("categories-Id"));
                            subCategoryModelClass.setSubCategory_Name(productObject.getString("Subcategories-Name"));
                    subCategoryModelClass.setSubCategory_Img(productObject.getString("Subcategories-Image"));
                            subCategoryModelClassList.add(subCategoryModelClass);

                            Log.d("subCategoryArraylist", String.valueOf(subCategoryModelClassList));

                        }

                        for (int i = 0; i < subCategoryModelClassList.size(); i++) {
                            subcategory_id = subCategoryModelClassList.get(i).getSubCategory_Id();
                            category_id = subCategoryModelClassList.get(i).getCat_id();
                            subcategory_name = subCategoryModelClassList.get(i).getSubCategory_Name();
                         //   subcategory_desc = subCategoryModelClassList.get(i).getSubCategory_Desc();
                            subcategory_image = subCategoryModelClassList.get(i).getSubCategory_Img();
                            Log.d("fdsaff", subcategory_image);

                            SQLiteDatabase database = dbHelper.getWritableDatabase();
                            dbHelper.insertSubCategoryProduct(subcategory_id, category_id, subcategory_name, "https://www.ecrm.sample.in/app/img/"+subcategory_image, database);
                            dbHelper.close();
                        }

                        subCategoryAdapter.notifyDataSetChanged();


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

        @Override
        public void onError(String error) {
             //show error code
        }
    });
}

尝试使用此@Abhishek后让我知道