Doubt Listview

Asked

Viewed 53 times

2

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

The Error is:

Caused by: java.lang.Classcastexception: android.support.Constraint.Constraintlayout cannot 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());
    }
}
}

2 answers

3

Note that the class builder ArrayAdapter wait as parameter:

  1. A context
  2. A layout that will be used to represent each item in the list. This layout, by default, must have a Textview
  3. A list of objects

Yet 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 the Activity, which is a ConstraintLayout and not a TextView, as expected, hence the error of ClassCastException.

To solve this error, pass as 2nd parameter the id of a layout that contains only one TextView. If you don’t want to create one, you can use the layout android.R.layout.simple_list_item_1, which is provided by Android.

1

Do what our friend said above and to complement, so that the Arrayadapter get popular your list you will have to write a

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

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

Tip: Force Casting on this line to avoid future problems.

listViewAcompanharOrdemServico = findViewById(R.id.listViewAcompanharOrdemServico);

Upshot:

listViewAcompanharOrdemServico = (ListView) findViewById(R.id.listViewAcompanharOrdemServico);

Browser other questions tagged

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