找不到适合JsonObjectRequest的构造函数

时间:2015-08-20 13:36:21

标签: java android json parsing

错误:

  

错误:(164,40)错误:找不到合适的构造函数   JsonObjectRequest(int,String,>,)构造函数   JsonObjectRequest.JsonObjectRequest(字符串,JSONObject的,监听器,ErrorListener)   不适用(实际参数int不能转换为String   通过方法调用转换)构造函数   JsonObjectRequest.JsonObjectRequest(INT,字符串的JSONObject,监听器,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);
    }



}

3 个答案:

答案 0 :(得分:3)

更改行

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可以保留为null,因为仅当您想要向服务器发送数据时才需要它,例如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.

答案 1 :(得分:1)

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>(){

答案 2 :(得分:0)

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

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

假设Method.GET是一个int,您应该更改它以为jsonRequest参数添加额外的null参数:

/**
 * 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);
}

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

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);
}

使用替代构造函数:

@Override
    //Teil2
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {                //Action für Switches

    RelativeLayout lay1 = (RelativeLayout) findViewById(R.id.lay1);


    if (switch1.isChecked()){                                                                   //isChecked() => Wenn "an"

        TextView label2 = (TextView)findViewById(R.id.label2);                                  //Label label2 auswählen
        label2.setText("On");
                                                                                                //Layout aus activity_main.xml, verknüpft über die id. (Wenn in main "Relative layout", dann hier auch
        lay1.setBackgroundColor(Color.parseColor("#ff95e1ff"));                                 //Farbe muss geparst werden, damit Hexadezimal Zahlen gehen

    }else{
        TextView label2 = (TextView)findViewById(R.id.label2);
        label2.setText("Off");

        lay1.setBackgroundColor(Color.WHITE);
    }


    if (switch2.isChecked()){

        TextView label3 = (TextView)findViewById(R.id.label3);
        label3.setText("On");

        lay1.setBackgroundColor(Color.RED);

    }else{
        TextView label3 = (TextView)findViewById(R.id.label3);
        label3.setText("Off");

        lay1.setBackgroundColor(Color.WHITE);
    }


    if (switch3.isChecked()){

        TextView label4 = (TextView)findViewById(R.id.label4);
        label4.setText("On");

        lay1.setBackgroundColor(Color.GREEN);

    }else{
        TextView label4 = (TextView)findViewById(R.id.label4);
        label4.setText("Off");

        lay1.setBackgroundColor(Color.WHITE);
    }


}