【问题标题】:No suitable constructor found for JsonObjectRequest没有为 JsonObjectRequest 找到合适的构造函数
【发布时间】:2015-11-14 04:29:07
【问题描述】:

错误:

错误:(164, 40) 错误: 找不到合适的构造函数 JsonObjectRequest(int,String,>,) 构造函数 JsonObjectRequest.JsonObjectRequest(String,JSONObject,Listener,ErrorListener) 不适用(实际参数 int 不能转换为 String 通过方法调用转换)构造函数 JsonObjectRequest.JsonObjectRequest(int,String,JSONObject,Listener,ErrorListener) 不适用(实际参数列表和形式参数列表的长度不同)

我认为问题出在 makeJsonObjectRequest 类上,有人可以帮助我吗?

我的班级:

<!-- language: java -->


public class MainActivity extends ActionBarActivity {

    public static String api_pvp_net = ".api.pvp.net/api/lol/"; // URL API
    // Insira a Sua Key depois do sinal de igual exemplo = "?api_key=sua-key-da-riot"
    public static String DEVELOPMENT_API_KEY = "?api_key=xxxxx-c258-48ab-9f52-af4f52b45e4c"; // Key Api RIOT
    // ---------------------------------
    public static String summoner_by_name = "v1.4/summoner/by-name/"; // Classe API URL
    public static String aUrl; // Url
    public static String Res_Web; // Resultado do WebBroser
    public static String Nome_Invocador; // Pega o Nome do invocador Do Txt_INVOCADOR


    private EditText etNick;
    private String nick;
    private Button btnOk;
    private Spinner rg;
    private invocador inv;
    private TextView tvLevel;
    private TextView Level;
    private TextView Id;
    private static String TAG = MainActivity.class.getSimpleName();
    private String jsonResponse;
    private ProgressDialog pDialog;

    ArrayAdapter<String> adapter;

    ArrayList<String> arrayInv;

    Summoner summoner = new Summoner();

    private void preencherInv() {
        arrayInv.add("BR");
        arrayInv.add("EUNE");
        arrayInv.add("EUW");
    }

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


        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);

        etNick = (EditText) findViewById(R.id.etNick);
        btnOk = (Button) findViewById(R.id.btnOk);
        rg = (Spinner) findViewById(R.id.spRG);
        tvLevel = (TextView) findViewById(R.id.tvLevel);
        inv = new invocador();
        Level = (TextView) findViewById(R.id.level);
        Id = (TextView) findViewById(R.id.id);

        arrayInv = new ArrayList<>();

        preencherInv();

        adapter = new ArrayAdapter<String>(
                this,
                android.R.layout.simple_dropdown_item_1line,
                arrayInv);

        rg.setAdapter(adapter);


        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                inv.setNick(etNick.getText().toString());

                inv.setRg((String) rg.getSelectedItem());

                RequestQueue mRequestQueue;

                // Instantiate the cache
                Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap

                // Set up the network to use HttpURLConnection as the HTTP client.
                BasicNetwork network = new BasicNetwork(new HurlStack());

                // Instantiate the RequestQueue with the cache and network.
                mRequestQueue = new RequestQueue(cache, network);

                // Start the queue
                mRequestQueue.start();

                Pesquisa_invocador();

                // Formulate the request and handle the response.
                makeJsonObjectRequest();


            }
        });

    }

    public void Pesquisa_invocador() {

        // Eu tiro os espacos da String do _nome por que nas resposta ela vem [sem espacos e Toda minuscula]
        Nome_Invocador = inv.getNick().toLowerCase();
        // Monto a URL API [CLASSE DA API] com 2 Parametro [Regiao] [NomeInvocador]  + [CHAVE DE DESENVOLVEDOR]
        aUrl = "https://" + inv.getRg().toLowerCase() + api_pvp_net + inv.getRg().toLowerCase() + "/" + summoner_by_name + Nome_Invocador + DEVELOPMENT_API_KEY; ;
        //Abro a URL no Webbroser

    }

    private void makeJsonObjectRequest() {

        showpDialog();


        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
                aUrl, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());

                try {
                    // Parsing json object response
                    // response will be a json object
                    String id = response.getString("id");
                    String name = response.getString("name");
                    String summonerLevel = response.getString("summonerLevel");


                    jsonResponse = "";
                    jsonResponse += "Name: " + name + "\n\n";
                    jsonResponse += "Level: " + summonerLevel + "\n\n";
                    jsonResponse += "ID: " + id + "\n\n";


                    tvLevel.setText(jsonResponse);

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),
                            "Error: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }
                hidepDialog();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
                // hide the progress dialog
                hidepDialog();
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(jsonObjReq);
    }
    private void showpDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hidepDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }



}

【问题讨论】:

    标签: java android json parsing


    【解决方案1】:

    换行

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
                aUrl, new Response.Listener<JSONObject>(){
    

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
                aUrl, null, new Response.Listener<JSONObject>(){
    

    对于 GET 请求,aJsonObject 可以为空,因为它仅在您想要向服务器发送数据时需要,例如对于 POST/PUT/PATCH 请求,java doc 中对该参数的描述是:

    @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
    indicates no parameters will be posted along with request.
    

    【讨论】:

      【解决方案2】:

      在 JsonObjectRequest 中没有您尝试在 makeJsonObjectRequest 方法顶部调用的构造函数。

      如错误中所述,JsonObjectRequest 存在以下 2 个构造函数:

          JsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener, 
      ErrorListener errorListener)
      

      JsonObjectRequest(int method, String url, JSONObject jsonRequest,
                  Listener<JSONObject> listener, ErrorListener errorListener)
      

      所以换行

      JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
                      aUrl, new Response.Listener<JSONObject>(){
      

      JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
                      aUrl, aJsonObject, new Response.Listener<JSONObject>(){
      

      【讨论】:

      • 关于最后一行,aJsonObject 是对什么的引用?我应该创建它吗?对不起新手问题;-;
      • aJsonObject 指的是您在代码中初始化的新JSONObject,或者只是将new JSONObject放在构造函数中。
      【解决方案3】:

      您没有在这一行向构造函数传递正确的参数:

      JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, aUrl,新的 Response.Listener() {

      假设 Method.GET 是一个 int 你应该改变它来为 jsonRequest 参数添加一个额外的 null 参数:

      JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
                  aUrl, null, new Response.Listener<JSONObject>() {
      

      使用https://android.googlesource.com/platform/frameworks/volley/+/kitkat-cts-dev/src/com/android/volley/toolbox/JsonObjectRequest.java中的这个构造函数:

      /**
       * Creates a new request.
       * @param method the HTTP method to use
       * @param url URL to fetch the JSON from
       * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
       *   indicates no parameters will be posted along with request.
       * @param listener Listener to receive the JSON response
       * @param errorListener Error listener, or null to ignore errors.
       */
      public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
              Listener<JSONObject> listener, ErrorListener errorListener) {
          super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                      errorListener);
      }
      

      或者,您可以将其更改为

      JsonObjectRequest jsonObjReq = new JsonObjectRequest(
                  aUrl, null, new Response.Listener<JSONObject>() {
      

      使用替代构造函数:

      /**
       * Constructor which defaults to <code>GET</code> if <code>jsonRequest</code> is
       * <code>null</code>, <code>POST</code> otherwise.
       *
       * @see #JsonObjectRequest(int, String, JSONObject, Listener, ErrorListener)
       */
      public JsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener,
              ErrorListener errorListener) {
          this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,
                  listener, errorListener);
      }
      

      【讨论】:

      • 我尝试更改为JsonObjectRequest jsonObjReq = new JsonObjectRequest( aUrl, null, new Response.Listener&lt;JSONObject&gt;() {,但没有成功。我想我需要输入类似this(JsonRequest == null ? Request.Method.GET, aUrl, JsonRequest, Listener&lt;JSONObject&gt;, Response.ErrorListener); 的内容,但不能,当我尝试时会出错。你能再指导我一点吗?感谢和抱歉打扰
      • 不,这只能在构造函数中使用。当你说它不起作用时,你得到了什么错误?
      • 发生错误是因为我试图将构造函数部分放入我的方法中,但现在它几乎可以工作了,但由于某种原因它崩溃了stackoverflow.com/questions/32119792/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      • 2017-03-30
      相关资源
      最近更新 更多