Nullpointerexception when running Listview.setAdapter (Android)

Asked

Viewed 126 times

1

i am implementing an application where I need to display a list of Dogs (already registered in BD) and allow clicking on an item in the list to display a new activy to edit the data.

The problem is that I am getting a Nullpointerexception when I try to run setAdapter. Using the debug I realized that during the entire run, my Listview that I created to receive the layout reference remains null, even after using findViewByID... Can anyone help with this? Below are the Layout and Activity:

package br.fatec.projeto.passeiacao;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

public class VerCaesActivity extends Activity{

    ListView listaCaes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        listaCaes = (ListView) findViewById(R.id.listaCaesId);

        CaoDAO dao = new CaoDAO (this);
        List <Cao> caes = dao.obterLista ();

        ArrayAdapter <Cao> adapter = new ArrayAdapter <Cao> (this, android.R.layout.simple_list_item_1, android.R.id.text1, caes);

        listaCaes.setAdapter(adapter);

        listaCaes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(getApplicationContext(), "Teste", Toast.LENGTH_LONG).show();
            }
        });
    }
}

And below the Layout of this Activity:

<ListView
    android:id="@+id/listaCaesId"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"></ListView>

From now on, I’d appreciate it if you could help!

  • Guys, I solved my problem by adding a setContentView to my onCreate. setContentView(R.layout.activity_ver_caes); Apparently without this information Android did not know which layout should be used.

  • setContentView() serves this purpose: inform which layout Acticity should use.

1 answer

0

Missed the setContentView(R.layout.NomeDoSeuLayout);, Android can’t find your list because it doesn’t know which layout to look for.

Browser other questions tagged

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