androidsqlitelistviewfragmentsimplecursoradapter

Android. Using SimpleCursorAdapter, SQLite and ListView in Fragment: NullPointerException


I created an app for display in Listview some data from SQLite, I'm using a class that extend of fragment, when executed the method that send the SimpleCursorAdapter to ListView, appears an error: NullPointerException. I show the class, the xml files and the error.

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.ViewGroup;
//import android.widget.SimpleCursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
/**
 * Clase que muestra el listView de los hoteles de comportamiento Fragment
 * recordad que las invocaciones Activity no son con this, son con getActivity()
 * Created by rogelio on 13/09/14.
 */


public class HotelFragment extends Fragment {
    public HotelFragment() {
    }
public HotelesDBAdapter dbHelper; //clase anteriormente utilizada, ahora no
public SimpleCursorAdapter dataAdapter;
public Cursor cursor;
public ListView listView;
public SQLiteDatabase db = null;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.hotel, container, false);

    try {

        db = getActivity().openOrCreateDatabase("Hoteles", Context.MODE_PRIVATE,null);
        crearYasignar(db);
        displayListView();//Generate ListView from SQLite Database
    }catch (SQLiteException e){
        alertas("Error inesperado: " + e.getMessage());
    }
    return rootView;
}


public void displayListView() {
    cursor = db.rawQuery("Select * from Hotel;",null);//replace to cursor = dbHelper.fetchAllHotels();
    // The desired columns to be bound
    String[] fromFieldNames = {"nombre", "direccion","telefono","email"};
    // the XML defined views which the data will be bound to
    int[] toViewsID = {R.id.name,R.id.direction,R.id.phone,R.id.email};
    Log.e("Checamos que hay id",String.valueOf(R.id.name));
    dataAdapter=new SimpleCursorAdapter(getActivity(), R.layout.hotel_info, cursor, fromFieldNames, toViewsID, 0);
    listView = (ListView) getActivity().findViewById(R.id.h_listView);
    listView.setAdapter(dataAdapter);// Assign adapter to ListView.... here... the bitch error
}

    public void alertas(String alerta){ 
    ContextThemeWrapper wrapper = new ContextThemeWrapper(getActivity(), R.style.AppTheme);
    AlertDialog.Builder builder = new AlertDialog.Builder(wrapper);
    builder.setIcon(R.drawable.logopequenio);
    builder.setTitle(R.string.app_name);
    builder.setMessage(alerta);
    builder.create().show();
}

public void crearYasignar(SQLiteDatabase dbllega){
    try {

        dbllega.execSQL("CREATE TABLE if not exists Hotel (_id integer PRIMARY KEY AUTOINCREMENT UNIQUE, nombre text, direccion text, telefono text, email text);");
        Cursor ap = dbllega.rawQuery("select * from Hotel;",null);
        if(ap.getCount()<=0){
            dbllega.execSQL("insert into Hotel (nombre,direccion,telefono,email) values ('HOTEL L´ORBE','Poniente 5 #33 entre Madero y Sur 2','01 (272) 72 5 50 33','orbereservaciones@gmail.com');");
            dbllega.execSQL("insert into Hotel (nombre,direccion,telefono,email) values ('HOTEL HA','Av. Oriente 6 No. 263 Col. Centro Orizaba, Veracruz','01 272 72 53699','HotelHa.Orizaba@gmail.com');");
            dbllega.execSQL("insert into Hotel (nombre,direccion,telefono,email) values('GRAND HOTEL DE FRANCE','no hay aun','01 272 72 52311','Sin correo');");
            dbllega.execSQL("insert into Hotel (nombre,direccion,telefono,email) values('HOTEL TRUEBA','Ote. 6 Nº 485, Esq. Sur 11. Orizaba, Ver','01 (272) 724 27 44','reservaciones@hoteltrueba.com');");
            dbllega.execSQL("insert into Hotel (nombre,direccion,telefono,email) values('HOTEL PLUVIOSILLA','Sin datos','No disponible','no disponible');");
            dbllega.execSQL("insert into Hotel (nombre,direccion,telefono,email) values('HOTEL ALAMEDA SUITES','PONIENTE 3 No. 512 COLONIA CENTRO  ORIZABA, VER','01 (272) 72 5 7143','no disponible');");
        }else {
            ap.moveToFirst();
            ap.moveToNext();
            Log.e("Comprobar que hay datos: ", ap.getString(1)); //comprobamos que haya datos
        }
        ap.moveToPosition(3);
        Log.e("Comprobar que hay datos2: ", ap.getString(1)); //comprobamos que haya datos
        db = dbllega;

    }catch (SQLiteException e){
        alertas("Error desconocido: "+e.getMessage());
    }
    }

}

XML File hotel_info

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="6dp"
android:background="@drawable/abc_ab_transparent_dark_holo">


<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="Name: "
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:text="Direction: "
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView2"
    android:layout_below="@+id/textView2"
    android:text="Phone: "
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/textView4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView3"
    android:layout_below="@+id/textView3"
    android:text="Email: "
    android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView2"
    android:layout_alignLeft="@+id/direction"
    android:text="TextView" />
<TextView
    android:id="@+id/direction"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView3"
    android:layout_toRightOf="@+id/textView2"
    android:text="TextView" />
<TextView
    android:id="@+id/phone"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView3"
    android:layout_alignBottom="@+id/textView3"
    android:layout_toRightOf="@+id/textView3"
    android:text="TextView" />

<TextView
    android:id="@+id/email"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView4"
    android:layout_alignBottom="@+id/textView4"
    android:layout_alignLeft="@+id/phone"
    android:text="TextView" />

</RelativeLayout>

XML File hotel

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/fondocelular">

<TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:padding="10dp"
    android:text="@string/some_text" android:textSize="20sp" />



<ListView android:id="@+id/h_listView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#00000000"
    android:cacheColorHint="#00000000"
    android:divider="#00000000"/>

</LinearLayout>

Error.

09-15 23:33:21.250  13630-13630/com.itorizaba.innovaciontecnologica2014 E/Trace﹕ error opening trace file: No such file or directory (2)
09-15 23:33:22.590  13630-13630/com.itorizaba.innovaciontecnologica2014 D/libEGL﹕ loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_121.so
09-15 23:33:22.660  13630-13630/com.itorizaba.innovaciontecnologica2014 D/libEGL﹕ loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_121.so
09-15 23:33:22.710  13630-13630/com.itorizaba.innovaciontecnologica2014 D/libEGL﹕ loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_121.so
09-15 23:33:22.830  13630-13630/com.itorizaba.innovaciontecnologica2014 W/IMGSRV﹕ :0: gralloc_register_buffer: ID: 4664 handle: 0x52f9c070 size: 540 x 888 fmt: 5 usage: 0xb00
09-15 23:33:22.880  13630-13630/com.itorizaba.innovaciontecnologica2014 D/OpenGLRenderer﹕ Enabling debug mode 0
09-15 23:33:23.160  13630-13630/com.itorizaba.innovaciontecnologica2014 W/IMGSRV﹕ :0: gralloc_register_buffer: ID: 4665 handle: 0x54b40a00 size: 540 x 888 fmt: 5 usage: 0xb00
09-15 23:33:24.920  13630-13630/com.itorizaba.innovaciontecnologica2014 W/IMGSRV﹕ :0: gralloc_register_buffer: ID: 4666 handle: 0x54b44d80 size: 540 x 888 fmt: 5 usage: 0xb00
09-15 23:33:25.070  13630-13630/com.itorizaba.innovaciontecnologica2014 W/IMGSRV﹕ :0:    gralloc_register_buffer: ID: 4667 handle: 0x54b7ed50 size: 540 x 888 fmt: 5 usage: 0xb00
09-15 23:33:25.100  13630-13630/com.itorizaba.innovaciontecnologica2014 W/IMGSRV﹕ :0: gralloc_register_buffer: ID: 4668 handle: 0x5388ffa0 size: 540 x 888 fmt: 5 usage: 0xb00
09-15 23:33:25.140  13630-13630/com.itorizaba.innovaciontecnologica2014 W/IMGSRV﹕ :0: gralloc_unregister_buffer: ID: 4664 handle: 0x52f9c070 size: 540 x 888 fmt: 5 usage: 0xb00
09-15 23:33:25.140  13630-13630/com.itorizaba.innovaciontecnologica2014 W/IMGSRV﹕ :0: gralloc_unregister_buffer: ID: 4665 handle: 0x54b40a00 size: 540 x 888 fmt: 5 usage: 0xb00
09-15 23:33:29.800  13630-13707/com.itorizaba.innovaciontecnologica2014 I/Parsher﹕ notcia:0
09-15 23:33:29.800  13630-13707/com.itorizaba.innovaciontecnologica2014 I/Parsher﹕ notcia:1
09-15 23:33:29.810  13630-13707/com.itorizaba.innovaciontecnologica2014 I/Parsher﹕ notcia:2
09-15 23:33:29.820  13630-13707/com.itorizaba.innovaciontecnologica2014 I/Parsher﹕ notcia:3
09-15 23:33:29.820  13630-13707/com.itorizaba.innovaciontecnologica2014 I/Parsher﹕ notcia:4
09-15 23:33:29.830  13630-13707/com.itorizaba.innovaciontecnologica2014 I/Parsher﹕ notcia:5
09-15 23:33:29.830  13630-13707/com.itorizaba.innovaciontecnologica2014 I/Parsher﹕ notcia:6
09-15 23:33:29.830  13630-13707/com.itorizaba.innovaciontecnologica2014 I/Parsher﹕ notcia:7
09-15 23:33:29.830  13630-13707/com.itorizaba.innovaciontecnologica2014 I/Parsher﹕ notcia:8
09-15 23:33:30.970  13630-13634/com.itorizaba.innovaciontecnologica2014 D/dalvikvm﹕ GC_CONCURRENT freed 1003K, 6% free 21901K/23080K, paused 5ms+2ms, total 18ms
09-15 23:33:35.630  13630-13630/com.itorizaba.innovaciontecnologica2014 W/IInputConnectionWrapper﹕ clearMetaKeyStates on inactive InputConnection
09-15 23:33:37.120  13630-13630/com.itorizaba.innovaciontecnologica2014 E/mDrawerToggle pushed﹕ x
09-15 23:33:37.560  13630-13630/com.itorizaba.innovaciontecnologica2014 E/Apertura completa﹕ !!
09-15 23:33:38.330  13630-13630/com.itorizaba.innovaciontecnologica2014 E/Comprobar que hay datos:﹕ HOTEL HA
09-15 23:33:38.330  13630-13630/com.itorizaba.innovaciontecnologica2014 E/Comprobar que hay datos2:﹕ HOTEL TRUEBA
09-15 23:33:38.330  13630-13630/com.itorizaba.innovaciontecnologica2014 E/Checamos que hay id﹕ 2131296329
09-15 23:33:38.340  13630-13630/com.itorizaba.innovaciontecnologica2014 D/AndroidRuntime﹕ Shutting down VM
09-15 23:33:38.340  13630-13630/com.itorizaba.innovaciontecnologica2014 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4184c7d0)
09-15 23:33:38.360  13630-13630/com.itorizaba.innovaciontecnologica2014 E/AndroidRuntime﹕   FATAL EXCEPTION: main
java.lang.NullPointerException
        at com.itorizaba.innovaciontecnologica2014.HotelFragment.displayListView(HotelFragment.java:64)
        at com.itorizaba.innovaciontecnologica2014.HotelFragment.onCreateView(HotelFragment.java:47)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:829)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
        at android.app.BackStackRecord.run(BackStackRecord.java:635)
        at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
        at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
        at android.os.Handler.handleCallback(Handler.java:615)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5031)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at       com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
        at dalvik.system.NativeStart.main(Native Method)

Solution

  • (ListView) getActivity().findViewById(R.id.h_listView)
    

    A method called in onCreateView() is too early find your views in the activity. The fragment view hierarchy is not yet a part of the activity and this will return null.

    Call findViewById() on the rootView you inflated in onCreateView(). You can pass it to your displayListView() method as an argument. For example,

    displayListView(rootView);
    
    ...
    
    private void displayListView(View root) { // also changed to private, no need to be public
    
         ...
    
         ListView = (ListView)root.findViewById(...);
    

    (getView() as suggested by another answer won't work - onCreateView() has not returned yet.)