java.lang.Arrayindexoutofboundsexception: length=0; index=0

Asked

Viewed 700 times

0

I am developing an application that will consume the mail price and term calculation service, however I have a problem in the service response, it returns me the following message: java.lang.Arrayindexoutofboundsexception: length=0; index=0, ie, informing that the array of arrays where I set the answers is null. Therefore, I would like help to be able to identify where is the error in the consumption of the service. The service I am consuming via SOAP.

Service class:

package com.bigboss.correios;

import android.os.AsyncTask;
import android.util.Log;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

public class CorreiosService extends AsyncTask<String, Integer, String[]>     {

private AsyncResponse parent;

public CorreiosService(AsyncResponse parent) {
    this.parent = parent;
}

@Override
protected String[] doInBackground(String... strings) {
    String SOAP_ACTION = "http://tempuri.org/CalcPrecoPrazo";
    String NAMESPACE = "http://tempuri.org/";
    String METHOD_NAME = "CalcPrecoPrazo";
    String URL = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx?WSDL";

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    request.addProperty("nCdServico", strings[0]);
    request.addProperty("sCepOrigem", strings[1]);
    request.addProperty("sCepDestino", strings[2]);
    request.addProperty("nVlPeso", strings[3]);
    request.addProperty("nCdFormato", Integer.parseInt(strings[4]));
    request.addProperty("nVlComprimento", strings[5]);
    request.addProperty("nVlAltura", Double.parseDouble(strings[6]));
    request.addProperty("nVlLargura", Double.parseDouble(strings[7]));
    request.addProperty("nVlDiametro", Double.parseDouble(strings[8]));
    request.addProperty("sCdMaoPropria", strings[9]);
    request.addProperty("nVlValorDeclarado", Double.parseDouble(strings[10]));
    request.addProperty("sCdAvisoRecebimento", strings[11]);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(request);

    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    String[] response = new String[]{};
    try {
        androidHttpTransport.call(SOAP_ACTION, envelope);


        SoapObject result = (SoapObject) envelope.getResponse();
        result = (SoapObject) result.getProperty("Servicos");
        result = (SoapObject) result.getProperty("cServico");

        if(result != null){
            response = new String[]{
                    result.getProperty("PrazoEntrega").toString(),
                    result.getProperty("ValorMaoPropria").toString(),
                    result.getProperty("ValorAvisoRecebimento").toString(),
                    result.getProperty("ValorValorDeclarado").toString(),
                    result.getProperty("DataMaxEntrega").toString(),
                    result.getProperty("Valor").toString() };
        }
    } catch (Exception ex) {
        Log.e("ERROR", ex.getMessage());
    }

    return response;
}

@Override
protected void onPostExecute(String[] strings) {
    parent.processFinish(strings);
}

public interface AsyncResponse {
    void processFinish(String[] response);
}

}

My Activity:

package com.bigboss.correios;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.ArrayList;
import java.util.List;

public class TerceiraActivity extends AppCompatActivity implements CorreiosService.AsyncResponse {

private List<Encomenda> encomendas = new ArrayList<Encomenda>();
String TAG = "Response";
private Encomenda encomenda;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_terceira);
    Intent it = getIntent();
    encomenda = (Encomenda) it.getSerializableExtra("objeto2");

    TextView resultOrigem = (TextView) findViewById(R.id.resOrigem);
    TextView resultDestino = (TextView) findViewById(R.id.resDestino);
    resultOrigem.setText(encomenda.getCepOrigem());
    resultDestino.setText(encomenda.getCepDestino());
    CorreiosService cs = new CorreiosService(this);
    cs.execute(

            getString(R.string.PAC3), encomenda.getCepOrigem(), encomenda.getCepDestino(),
            encomenda.getPeso(),String.valueOf(encomenda.getFormato()), encomenda.getComprimento(),
            encomenda.getAltura(),encomenda.getLargura(), encomenda.getDiametro(),encomenda.getMaoPropria(),
            encomenda.getValorDeclarado(), encomenda.getAvisoRecibo());

}

private void EncomendaList() {
    encomendas.add(new Encomenda());
    encomendas.add(new Encomenda());
    encomendas.add(new Encomenda());
    encomendas.add(new Encomenda());
    encomendas.add(new Encomenda());
    encomendas.add(new Encomenda());
}

private void EncomendaListView() {
    ArrayAdapter<Encomenda> adapter = new MinhaLista();
    ListView list = (ListView) findViewById(R.id.listview);
    list.setAdapter(adapter);
}

@Override
public void processFinish(String[] response) {
    AlertDialog.Builder dialogo = new AlertDialog.Builder(TerceiraActivity.this);

    dialogo.setTitle("Resultado"); 
    if(response.equals(null)){
        dialogo.setMessage(
                "Retornando null ");
        dialogo.setNeutralButton("OK", null); // setando botão

        dialogo.show();
    }else{
    // setando mensagem
    dialogo.setMessage(// AQUI ONDE SE REFERENCIA O ERRO DADO
            "Prazo de Entrega: " + response[0] + "\n " +
                    "Valor Mão própria: " + response[1] + " \n" +
                    "Aviso de recebimento: " + response[2] + " \n" +
                    "Valor declarado: " + response[3] + " \n" +
                    "Data de entrega: " + response[4] + " \n"+
                    "Valor: " + response[5] + " \n");
    dialogo.setNeutralButton("OK", null); // setando botão

    dialogo.show();   // chamando o AlertDialog
}}

private class MinhaLista extends ArrayAdapter<Encomenda> {

    MinhaLista() {
        super(TerceiraActivity.this, R.layout.item_view, encomendas);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View itemview = convertView;
        if (itemview == null) {
            itemview = getLayoutInflater().inflate(R.layout.item_view, parent, false);
        }

        Encomenda enc = encomendas.get(position);

        ImageView img = (ImageView) itemview.findViewById(R.id.item_icon);
        img.setImageResource(enc.getIdIcon());


        TextView textPrazo = (TextView) itemview.findViewById(R.id.prazo);
        textPrazo.setText("Prazo de entrega: " + enc.getPrazoEntrega());

        //TextView textMao = (TextView)itemview.findViewById(R.id.maopropria);
        // textMao.setText("Mão própria: R$"+enc.getMaoPropria());

        TextView textAR = (TextView) itemview.findViewById(R.id.AR);
        textAR.setText("Aviso de recebimento: ERRO R$" + enc.getDiametro());

        TextView textVlDecl = (TextView) itemview.findViewById(R.id.vlDecl);
        textVlDecl.setText("Valor declarado: R$" + enc.getValorDeclarado());

        return itemview;
    }
}

}

Exit: Note: this 29.0 is one of the values I passed for the calculation. and did not understand why he returned with this message. inserir a descrição da imagem aqui

  • Carlos, could you put all the Error Stack? So it makes it easier !

  • Ready @Thiagoluizdomacoski had forgotten

  • In fact @Thiagoluizdomacoski he is not Serializing my height = 29.0

  • make a Log.d("LOGTEST", String.valueOf(reponse));, what appears on the console?

1 answer

1


You took the test

if(response.equals(null)){

and actually Sponse is not null, but is returning an empty vector.

This is Sponse has zero size, hence the length=0; index=0. When trying to access array elements

response[0], response[1]...etc

in row 81 of the Code

dialogo.setMessage...etc

happens the Arrayindexoutofboundsexception.

Arrayindexoutofboundsexception is literally "Out-of-Bounds Array Index Exception", and happens when trying to access an element with an index not present in array.

  • Guy I solved the problem by passing strings even and did not decimal as I had done in the code above. Now I have another problem regarding ERROR: System.Web.Services.Protocols.Soapexception: Server was Unable to read request

Browser other questions tagged

You are not signed in. Login or sign up in order to post.