ListView Doubt

2

I have the following code where I am in doubt as I do to display the list on the screen, I have already tried in several ways and I have already done several examples of the internet I could not find a correct solution to my problem.

The error is:

  

Caused by: java.lang.ClassCastException:   android.support.constraint.ConstraintLayout can not be cast to   android.widget.TextView

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="br.com.escconsultoria.escoficina.view.AcompanharOrdemServicoActivity">

<ListView
    android:id="@+id/listViewAcompanharOrdemServico"
    android:layout_width="368dp"
    android:layout_height="495dp"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp" />

public class AcompanharOrdemServicoActivity extends Activity {

private ListView listViewAcompanharOrdemServico;

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

    listViewAcompanharOrdemServico = findViewById(R.id.listViewAcompanharOrdemServico);

    String cpfCliente = null;
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        cpfCliente = extras.getString("cpfCliente");
    }

    new CarregaAcompanharOrdemServicoSaidaDTOJsonAsyncTask().execute("https://escoficinawebservice.herokuapp.com/acompanharOrdemServico/" + cpfCliente);
}

    /*@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    AcompanharOrdemServico acompanharOrdemServico = (AcompanharOrdemServico) l.getAdapter().getItem(position);

    Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(acompanharOrdemServico.url));
    startActivity(it);
    }*/

class CarregaAcompanharOrdemServicoSaidaDTOJsonAsyncTask extends AsyncTask<String, Void, List<AcompanharOrdemServicoSaidaDTO>> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        Context context = getApplicationContext();

        String message = "Aguarde... Verificando CPF.";
        int time = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, message, time);
        toast.show();
    }

    @Override
    protected List<AcompanharOrdemServicoSaidaDTO> doInBackground(String... params) {
        String urlString = params[0];

        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(urlString);

        List<AcompanharOrdemServicoSaidaDTO> listaAcompanharOrdemServicoSaidaDTO = null;

        try {
            HttpResponse response = httpClient.execute(httpGet);

            HttpEntity httpEntity = response.getEntity();

            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();

                String json = toString(inputStream);
                inputStream.close();

                listaAcompanharOrdemServicoSaidaDTO = getAcompanharOrdemServico(json);
            }
        } catch (Exception e) {
            Context context = getApplicationContext();
            int time = Toast.LENGTH_SHORT;

            String message = "Erro: " + e.getMessage();

            Toast toast = Toast.makeText(context, message, time);
            toast.show();

            return null;
        }

        return listaAcompanharOrdemServicoSaidaDTO;
    }

    private List<AcompanharOrdemServicoSaidaDTO> getAcompanharOrdemServico(String jsonString) {

        List<AcompanharOrdemServicoSaidaDTO> listaAcompanharOrdemServicoSaidaDTO = new ArrayList<>();
        AcompanharOrdemServicoSaidaDTO acompanharOrdemServicoSaidaDTO = new AcompanharOrdemServicoSaidaDTO();

        List<AcompanharOrdemServicoModel> listaAcompanharOrdemServicoModel = new ArrayList<>();

        try {
            JSONObject jsonObjectConvertString = new JSONObject(jsonString);
            JSONObject jsonObjectEntity = jsonObjectConvertString.getJSONObject("entity");
            JSONArray jsonArrayAcompanharOrdemServicoModel = jsonObjectEntity.getJSONArray("listaAcompanharOrdemServicoModel");

            JSONObject jsonObjectAcompanharOrdemServicoModel;

            for (int i = 0; i < jsonArrayAcompanharOrdemServicoModel.length(); i++) {
                jsonObjectAcompanharOrdemServicoModel = new JSONObject(jsonArrayAcompanharOrdemServicoModel.getString(i));

                AcompanharOrdemServicoModel acompanharOrdemServicoModel = new AcompanharOrdemServicoModel();
                acompanharOrdemServicoModel.setCodigoOrdemServico(jsonObjectAcompanharOrdemServicoModel.getInt("codigoOrdemServico"));

                Long dataCadastroAcompanharOrdemServico = jsonObjectAcompanharOrdemServicoModel.getLong("dataCadastroAcompanharOrdermServico");
                acompanharOrdemServicoModel.setDataCadastroAcompanharOrdermServico(new Date(dataCadastroAcompanharOrdemServico));

                listaAcompanharOrdemServicoModel.add(acompanharOrdemServicoModel);
            }

            acompanharOrdemServicoSaidaDTO.setListaAcompanharOrdemServicoModel(listaAcompanharOrdemServicoModel);


            listaAcompanharOrdemServicoSaidaDTO.add(acompanharOrdemServicoSaidaDTO);

        } catch (JSONException e) {
            Context context = getApplicationContext();
            int time = Toast.LENGTH_SHORT;

            String message = "Erro: " + e.getMessage();

            Toast toast = Toast.makeText(context, message, time);
            toast.show();

            return null;
        }

        return listaAcompanharOrdemServicoSaidaDTO;
    }

    @Override
    protected void onPostExecute(List<AcompanharOrdemServicoSaidaDTO> listaAcompanharOrdemServicoSaidaDTO) {
        super.onPostExecute(listaAcompanharOrdemServicoSaidaDTO);


        if (listaAcompanharOrdemServicoSaidaDTO != null) {

            ArrayAdapter<AcompanharOrdemServicoSaidaDTO> adapter = new ArrayAdapter<AcompanharOrdemServicoSaidaDTO>(AcompanharOrdemServicoActivity.this,
                    R.layout.activity_acompanhar_ordem_servico, listaAcompanharOrdemServicoSaidaDTO);

            listViewAcompanharOrdemServico.setAdapter(adapter);

        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    AcompanharOrdemServicoActivity.this).setTitle("Atenção")
                    .setMessage("Não foi possivel acessar essas informções...")
                    .setPositiveButton("OK", null);
            builder.create().show();
        }
    }

    private String toString(InputStream is) throws IOException {

        byte[] bytes = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int lidos;
        while ((lidos = is.read(bytes)) > 0) {
            baos.write(bytes, 0, lidos);
        }
        return new String(baos.toByteArray());
    }
}
}
    
asked by anonymous 28.09.2017 / 05:19

2 answers

3

Notice that the constructor of class ArrayAdapter expects as a parameter:

  • A context
  • A layout that will be used to represent each item in the list. This layout, by default, should have a TextView
  • A list of objects
  • However, when you call

    new ArrayAdapter<AcompanharOrdemServicoSaidaDTO>(AcompanharOrdemServicoActivity.this,
                            R.layout.activity_acompanhar_ordem_servico, listaAcompanharOrdemServicoSaidaDTO);
    

    You are passing in the 2nd parameter the layout of Activity , which is a ConstraintLayout and not a TextView , as expected, so the ClassCastException error.

    To resolve this error, pass the id parameter of a layout containing just a TextView as the 2nd parameter. If you do not want to create one, you can use the android.R.layout.simple_list_item_1 layout, which is provided by Android.

        
    28.09.2017 / 22:52
    1

    Do what our friend said above and to complement, for ArrayAdapter to get popular your list you will have to write a

    @Override
    public String toString(){
      return this.variavel;
    }
    

    in your DTO by replacing this.valiavel with what you want to show in the ListView row. If you do not make a toString, a memory reference of each object in the Array will be printed.

    Tip: Force Casting on this line below to avoid future issues.

    listViewAcompanharOrdemServico = findViewById(R.id.listViewAcompanharOrdemServico);
    

    Result:

    listViewAcompanharOrdemServico = (ListView) findViewById(R.id.listViewAcompanharOrdemServico);
    
        
    29.09.2017 / 19:29