Search code examples
javaandroidlistadaptermariadb

"Null object" error when setting a adapter


I'm getting this error when I set my adapter. I already have a ListView with id lv_cine in my view.

Edit 1: added the wrong codes but they are the same as this.

Edit 2: Ok i managed to get past the first error, but now i'm getting a similar one:

12-01 20:43:44.445    7617-7617/com.example.maria.maria E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.maria.maria, PID: 7617
    java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
            at android.widget.SimpleAdapter.getCount(SimpleAdapter.java:93)
            at android.widget.ListView.setAdapter(ListView.java:487)
            at com.example.maria.maria.Cinema$GetContacts.onPostExecute(Cinema.java:146)
            at com.example.maria.maria.Cinema$GetContacts.onPostExecute(Cinema.java:67)
            at android.os.AsyncTask.finish(AsyncTask.java:632)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Here is my activity (Cinema.java):

public class Cinema extends Activity {

private ProgressDialog pDialog;
ListView listView;
private static String url = "http://viniciuscoelho.com/android/dados";

// JSON Node nomes
private static final String TAG_CATEGORIA = "cinema";
private static final String TAG_NOME = "nome";
private static final String TAG_DATA = "data";
private static final String TAG_ENDERECO = "endereco";
private static final String TAG_LINK = "link";
private static final String TAG_DESC = "desc";

// contacts JSONArray
JSONArray dados = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> listaDados;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cinema);

    listView = (ListView) findViewById(R.id.lv_cine);

    new GetContacts().execute();
}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Cinema.this);
        pDialog.setMessage("Carregando...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                dados = jsonObj.getJSONArray(TAG_CATEGORIA);

                // looping through All dados
                for (int i = 0; i < dados.length(); i++) {
                    JSONObject c = dados.getJSONObject(i);

                    String nome = c.getString(TAG_NOME);
                    String data = c.getString(TAG_DATA);
                    String endereco = c.getString(TAG_ENDERECO);
                    String link = c.getString(TAG_LINK);
                    String desc = c.getString(TAG_DESC);


                    // tmp hashmap for single contact
                    HashMap<String, String> linha = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    linha.put(TAG_NOME, nome);
                    linha.put(TAG_DATA, data);
                    linha.put(TAG_ENDERECO, endereco);
                    linha.put(TAG_LINK, link);
                    linha.put(TAG_DESC, desc);

                    // adding contact to contact list
                    listaDados.add(linha);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                Cinema.this, listaDados,
                R.layout.linha, new String[] { TAG_NOME, TAG_DATA,
                TAG_ENDERECO, TAG_LINK, TAG_DESC }, new int[] { R.id.tvNome,
                R.id.tvData, R.id.tvEndereco, R.id.tvLink, R.id.tvDescricao });

        //relaciona os dados ao próprio listview
        listView.setAdapter(adapter);
    }

}

}

And view (activity_cinema.xml):

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:padding="@dimen/activity_horizontal_margin"
    android:scrollbars="none"
    android:background="@color/pome">

    <ListView
        android:id="@+id/lv_cine"
        android:background="@color/pome"
        android:layout_width="fill_parent"
        android:scrollbars="none"
        android:layout_height="wrap_content"
        android:layout_below="@+id/logo_cine"
        android:clickable="false"
        style="@style/Listas">

    </ListView>

</RelativeLayout>

linha.xml:

<RelativeLayout
    android:layout_width="fill_parent"
    android:orientation="horizontal"
    android:id="@+id/linha"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:paddingTop="20dp"
        android:id="@+id/tvNome"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="22sp"
        android:textColor="@color/White"
        android:textStyle="bold"
        android:text="Nome"/>

    <TextView
        android:id="@+id/tvData"
        android:textStyle="bold"
        android:paddingBottom="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_below="@+id/tvNome"
        android:textSize="16sp"
        android:text="Data" />

    <TextView
        android:id="@+id/tvEndereco"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_below="@+id/tvData"
        android:text="Endereco"
        android:textColorLink="@color/White"
        android:textSize="14sp"
        android:autoLink="all"
        />

    <TextView
        android:id="@+id/tvLink"
        android:paddingBottom="5dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_below="@+id/tvEndereco"
        android:text="Link"
        android:textColorLink="@color/LightYellow"
        android:textSize="14sp"
        android:autoLink="all"
        />

    <TextView
        android:id="@+id/tvDescricao"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_below="@+id/tvLink"
        android:textSize="16sp"
        android:text="Descricao"
        android:paddingBottom="20dp"
        />

</RelativeLayout>

Solution

  • One thing I can see so far:

    You didn't initialise listaDados with a value, Can be done here:

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Cinema.this);
        pDialog.setMessage("Carregando...");
        pDialog.setCancelable(false);
        pDialog.show();
    
        listaDados = new ArrayList<HashMap<String, String>>();
    }