Does Webservice (Asynctask) only work with Debug?

Asked

Viewed 90 times

2

I’m making my Android app upload data from a Webservice. In it, I will load date data into a Spinner and, when it is complete, the same dates will load other data types into a Listview, but for now I’m using an example to see how it turned out and already fix consistency errors. Anyway, the problem is that when I do the Asynctask, I run it and must load Spinner, the app to work. But when to put this part to debug program can work perfectly.

Java code:

public class Baixarrotas extends Opcoes{

//OPÇÃO DO MENU
private final String NAMESPACE = "";
private final String URL = "";
private final String SOAP_ACTION = "";     //Tirei estes dados por segurança
private final String METHOD_NAME = "";
private String TAG = "";

private static String resultado;
private static String WSResultado;
public List<WSGetterSetter> listaLida;

Spinner spinner_baixarrota_datas;
Button button_baixarrota_selecionar;
TextView tv;
TextView tv2;

String dataSelecionada;

String[]exemplo = { "JAN", "FEB", "MAR", "APR", "MAY", "JUNE", "JULY", "AUG", "SEPT", "OCT", "NOV", "DEC" };
ListView listView_baixarrota_escolha;
ArrayAdapter arrayAdapter;

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

    spinner_baixarrota_datas = (Spinner) findViewById(R.id.spinner_baixarrota_datas);
    button_baixarrota_selecionar = (Button) findViewById(R.id.button_baixarrota_selecionar);
    tv = (TextView) findViewById(R.id.textView_baixarrota_resultData);
    listView_baixarrota_escolha = (ListView) findViewById(R.id.listView_baixarrota_escolha);
    tv2 = (TextView) findViewById(R.id.textView_baixarrota_result);

   // início debug
   AsyncCallWS task = new AsyncCallWS();
    task.execute();

    ArrayList<String> mylist = new ArrayList<String>();
    for (int i = 0; i < listaLida.size(); i++) mylist.add(i, listaLida.get(i).getsData());

    ArrayAdapter<String> spinner_datas = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mylist);
    spinner_baixarrota_datas.setAdapter(spinner_datas);
    // fim debug

    // Layouts
    if(resultado == "**Registros Carregado"){
        button_baixarrota_selecionar.setEnabled(true);
        button_baixarrota_selecionar.setClickable(true);

        tv.setTextColor(Color.BLUE);

        arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1,exemplo);
        listView_baixarrota_escolha.setAdapter(arrayAdapter);
    }
    else {
        button_baixarrota_selecionar.setEnabled(false);
        button_baixarrota_selecionar.setClickable(false);

        tv2.setVisibility(View.VISIBLE);
    }
    //escolhendo a data
    spinner_baixarrota_datas.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            dataSelecionada = spinner_baixarrota_datas.getSelectedItem().toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
        }

    });
    // escolhe o item do listView
    listView_baixarrota_escolha.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            AlertDialog alerta;
            AlertDialog.Builder builder = new AlertDialog.Builder(BaixarRotas.this);
            builder.setTitle("Confirmar escolha:");
            builder.setMessage("-DATA: "+ dataSelecionada +"\n-ROTA: " + "\n-ATIVIDADE: " + "\n-RESPONSÁVEL: " + "\n-QUANTIDADE: ");

            builder.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {

                }
            });

            builder.setNegativeButton("Não", new DialogInterface.OnClickListener()
            { public void onClick(DialogInterface arg0, int arg1) {
                }
            });
            alerta = builder.create();
            alerta.show();
        }
    });

}
// Inutilizado, pois estou usando um exemplo logo embaixo (no AsyncTask)
public void getData() {
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    PropertyInfo dataPI = new PropertyInfo();

    dataPI.setName("DATA");

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

    AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
    try {
        androidHttpTransport.debug = true;
        androidHttpTransport.call(SOAP_ACTION, envelope);

        WSResultado = androidHttpTransport.responseDump;

        Log.i("t", "doInBackground");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private class AsyncCallWS extends AsyncTask<String, Void, Void> {
    @Override
    protected Void doInBackground(String... params) {
        Log.i(TAG, "doInBackground");
        // getData();
        // WSResultado é um exemplo de XML e está substituindo o getData(), um dado obtido pelo o WebService
        WSResultado = "<diffgr:diffgram xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" xmlns:diffgr=\"urn:schemas-microsoft-com:xml-diffgram-v1\">\n" +
                "               <NewDataSet xmlns=\"\">\n" +
                "                  <Table diffgr:id=\"Table2\" msdata:rowOrder=\"1\">\n" +
                "                     <DATA>2013-08-21T00:00:00-03:00</DATA>\n" +
                "                  </Table>\n" +
                "                  <Table diffgr:id=\"Table3\" msdata:rowOrder=\"2\">\n" +
                "                     <DATA>2013-08-22T00:00:00-03:00</DATA>\n" +
                "                  </Table>\n" +
                "               </NewDataSet>\n" +
                "            </diffgr:diffgram>";

        // CHAMADA parser (analisador do Xml)
        List<WSGetterSetter> datasR = null;
        InputStream is = new ByteArrayInputStream(WSResultado.getBytes());

        WSParser parser = new WSParser();
        datasR = parser.parse(is);

        listaLida = datasR;
        resultado = "**Registros Carregado";
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        Log.i(TAG, "onPostExecute");
        tv.setText(resultado);
    }

    @Override
    protected void onPreExecute() {
        Log.i(TAG, "onPreExecute");
        tv.setText("**Carregando...");
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        Log.i(TAG, "onProgressUpdate");

    }

}

This part is where I have to put to debug (mainly in the creation of Spinner):

    AsyncCallWS task = new AsyncCallWS();
    task.execute();

    ArrayList<String> mylist = new ArrayList<String>();
    for (int i = 0; i < listaLida.size(); i++) mylist.add(i, listaLida.get(i).getsData());

    ArrayAdapter<String> spinner_datas = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mylist);
    spinner_baixarrota_datas.setAdapter(spinner_datas);

The XML of this code if necessary for better understanding:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="81dp"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="7dp"
    android:layout_marginRight="7dp"
    android:layout_marginLeft="7dp">

    <TextView
        android:text="Data:"
        android:textSize="25dp"
        android:textStyle="bold"
        android:textColor="#ff010101"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_alignParentStart="true" />

    <Spinner
        android:id="@+id/spinner_baixarrota_datas"
        android:layout_width="175dp"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_alignStart="@+id/textView"
        android:layout_marginStart="64dp" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Selecionar"
        android:id="@+id/button_baixarrota_selecionar"
        android:layout_alignBottom="@+id/spinner_baixarrota_datas"
        android:layout_toEndOf="@+id/spinner_baixarrota_datas"
        android:clickable="false"
        android:enabled="false"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="**Registros não carregado"
        android:id="@+id/textView_baixarrota_resultData"
        android:textColor="#ffff0008"
        android:layout_alignParentTop="true"
        android:layout_alignStart="@+id/spinner_baixarrota_datas" />


</RelativeLayout>
<View
    android:layout_width="fill_parent"
    android:layout_height="2dp"
    android:background="#000"
    android:layout_below="@+id/spinner_baixarrota_datas"
    android:layout_alignParentStart="true" />

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_horizontal">

    <TextView
        android:layout_width="334dp"
        android:layout_height="wrap_content"
        android:text="ROTA -  ATIVIDADE  -  RESPONSÁVEL  -  QUANTIDADE"
        android:id="@+id/tv_tabela"
        android:textColor="#000"
        android:layout_gravity="center_horizontal|top"
        android:layout_marginTop="15dp"
        android:background="#f0b4b9b7"/>

    <ListView
        android:layout_width="334dp"
        android:layout_height="356dp"
        android:id="@+id/listView_baixarrota_escolha"
        android:layout_gravity="center"
        android:divider="#FFCC00"
        android:dividerHeight="2dp"
        android:layout_weight="1"
        android:background="@drawable/borda"/>

    <TextView
        android:layout_width="334dp"
        android:layout_height="356dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="**Registros não carregado"
        android:id="@+id/textView_baixarrota_result"
        android:layout_gravity="center"
        android:textColor="#ffff0008"
        android:background="@drawable/borda"
        android:textAlignment="center"
        android:visibility="invisible"/>

</FrameLayout>

logcat displays the following error:"Attempt to invoke interface method 'int java.util.List.size()' on a null Object Reference" I’ve seen it in other questions, but none were effective. So does anyone have any idea what that problem is? Grateful.

1 answer

1


Although I have not posted the error I am 99.99% sure it is NullPointerException.

The reason is that the list listaLida is only initialized within the doInBackground() of Asynctask.

But even if you initialized the list before the code wouldn’t work as you think.
In this part of the code,

task.execute();

ArrayList<String> mylist = new ArrayList<String>();
for (int i = 0; i < listaLida.size(); i++) mylist.add(i, listaLida.get(i).getsData());

the task is executed and immediately the list that will be completed by the task is used.

The task is asynchronous or when the line task.execute(); is executed the program continues to run on ArrayList<String> mylist = new ArrayList<String>(); without waiting for the task to end and the list to be filled in.

You must pass all the code that depends on the list to be populated for a new method and call it in the method onPostExecute() of Asynctask.

The error may not happen during the debug because step-by-step is slow and should give time for the list to be filled in before it is used.

  • Thank you very much!! I already understood that I was having an error in the Asynctask process and Layout formation, but the problem is that logCat presented the problem as: "Attempt to invoke interface method 'int java.util.List.size()' on a null Object Reference" and I got caught up in it... The app worked

  • 1

    The error I indicated is not the same but the cause is the same: the list is null when trying to use it. When asking about something in which an error occurs should indicate it so that it is easier to understand the problem.

Browser other questions tagged

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