vendredi 1 janvier 2016

Load data from sqlite to custom Listview but app stops

I have created an application to load name,phone from database auto and display as two textboxes in a listview. But nullpointer exception error occurs and app exits. My Logcat shows this.

01-01 03:52:04.267: W/dalvikvm(803): threadid=1: thread exiting with uncaught exception (group=0xb3a67ba8)
01-01 03:52:04.287: E/AndroidRuntime(803): FATAL EXCEPTION: main

01-01 03:52:04.287: E/AndroidRuntime(803): java.lang.RuntimeException: Unable to start activity ComponentInfo{}: java.lang.NullPointerException
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.os.Handler.dispatchMessage(Handler.java:102)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.os.Looper.loop(Looper.java:136)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.ActivityThread.main(ActivityThread.java:5001)
01-01 03:52:04.287: E/AndroidRuntime(803):  at java.lang.reflect.Method.invokeNative(Native Method)
01-01 03:52:04.287: E/AndroidRuntime(803):  at java.lang.reflect.Method.invoke(Method.java:515)
01-01 03:52:04.287: E/AndroidRuntime(803):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
01-01 03:52:04.287: E/AndroidRuntime(803):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
01-01 03:52:04.287: E/AndroidRuntime(803):  at dalvik.system.NativeStart.main(Native Method)
01-01 03:52:04.287: E/AndroidRuntime(803): Caused by: java.lang.NullPointerException
01-01 03:52:04.287: E/AndroidRuntime(803):  at com.onemedia.koottam.SqlHandler.copyDataBase(SqlHandler.java:75)
01-01 03:52:04.287: E/AndroidRuntime(803):  at com.onemedia.koottam.SqlHandler.<init>(SqlHandler.java:30)
01-01 03:52:04.287: E/AndroidRuntime(803):  at com.onemedia.koottam.Auto.onCreate(Auto.java:37)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.Activity.performCreate(Activity.java:5231)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)

My SQLHandler.java

public class SqlHandler {

public static final String DATABASE_NAME = "koottam.sqlite3";
public static final int DATABASE_VERSION = 1;
public static String DB_PATH;

Context context;
SQLiteDatabase sqlDatabase;
SqlDbHelper dbHelper;

public SqlHandler(Context context) {

    dbHelper = new SqlDbHelper(context, DATABASE_NAME, null,
            DATABASE_VERSION);
    String packageName = context.getPackageName();
    DB_PATH = String.format("//data//data//%s//databases//", packageName);
    sqlDatabase = dbHelper.getWritableDatabase();
    try {
        copyDataBase();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void executeQuery(String query) {
    try {

        if (sqlDatabase.isOpen()) {
            sqlDatabase.close();
        }

        sqlDatabase = dbHelper.getWritableDatabase();
        sqlDatabase.execSQL(query);

    } catch (Exception e) {

        System.out.println("DATABASE ERROR " + e);
    }

}

public Cursor selectQuery(String query) {
    Cursor c1 = null;
    try {

        if (sqlDatabase.isOpen()) {
            sqlDatabase.close();

        }
        sqlDatabase = dbHelper.getWritableDatabase();
        c1 = sqlDatabase.rawQuery(query, null);

    } catch (Exception e) {

        System.out.println("DATABASE ERROR " + e);

    }
    return c1;

}

private void copyDataBase() throws IOException {
    InputStream externalDbStream = context.getAssets().open(DATABASE_NAME);

    String outFileName = DB_PATH + DATABASE_NAME;

    OutputStream localDbStream = new FileOutputStream(outFileName);
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = externalDbStream.read(buffer)) > 0) {
        localDbStream.write(buffer, 0, bytesRead);
    }
    localDbStream.close();
    externalDbStream.close();

}

}

SQLDBHelper.java

public class SqlDbHelper extends SQLiteOpenHelper {
public static String DB_PATH;
public static String DB_NAME="koottam.sqlite3";
public SQLiteDatabase database;

public final Context context;


public static final String DATABASE_TABLE = "auto";

public static final String COLUMN1 = "SNo";
public static final String COLUMN2 = "Name";
public static final String COLUMN3 = "Number";

public SqlDbHelper(Context context, String name, CursorFactory factory,
        int version) {
    super(context, name, factory, version);

    // TODO Auto-generated constructor stub
    this.context = context;
    String packageName = context.getPackageName();
DB_PATH = String.format("//data//data//%s//databases//", packageName);
//DB_NAME = databaseName;

}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    //db.execSQL(SCRIPT_CREATE_DATABASE);
    try {
        copyDataBase();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
    onCreate(db);
}
public void createDataBase() {
    boolean dbExist = checkDataBase();
    if (!dbExist) {
        this.getReadableDatabase();
        try {
            copyDataBase();
        } catch (IOException e) {
            Log.e(this.getClass().toString(), "Copying error");
            throw new Error("Error copying database!");
        }
    } else {
        Log.i(this.getClass().toString(), "Database already exists");
    }
}

private boolean checkDataBase() {
    SQLiteDatabase checkDb = null;
    try {
        String path = DB_PATH + DB_NAME;
        checkDb = SQLiteDatabase.openDatabase(path, null,
                SQLiteDatabase.OPEN_READONLY);
    } catch (SQLException e) {
        Log.e(this.getClass().toString(), "Error while checking db");
    }

    if (checkDb != null) {
        checkDb.close();
    }
    return checkDb != null;
}

private void copyDataBase() throws IOException {
    InputStream externalDbStream = context.getAssets().open(DB_NAME);

    String outFileName = DB_PATH + DB_NAME;

    OutputStream localDbStream = new FileOutputStream(outFileName);
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = externalDbStream.read(buffer)) > 0) {
        localDbStream.write(buffer, 0, bytesRead);
    }
    localDbStream.close();
    externalDbStream.close();

}

public SQLiteDatabase openDataBase() throws SQLException {
    String path = DB_PATH + DB_NAME;
    if (database == null) {
        createDataBase();
        database = SQLiteDatabase.openDatabase(path, null,
            SQLiteDatabase.OPEN_READWRITE);
    }
    return database;
}
@Override
public synchronized void close() {
    if (database != null) {
        database.close();
    }
    super.close();
}

}

Auto.java

public class Auto extends ListActivity {

SqlHandler sqlHandler;

private ListView listView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_auto);
    // get action bar   
    ActionBar actionBar = getActionBar();

    // Enabling Up / Back navigation
    actionBar.setDisplayHomeAsUpEnabled(true);
      sqlHandler = new SqlHandler(this);
    showlist();

}


private void showlist() {

    ArrayList<listRowAuto> contactList = new ArrayList<listRowAuto>();
    contactList.clear();
    String query = "SELECT Name,Number FROM auto ";
    Cursor c1 = sqlHandler.selectQuery(query);
    if (c1 != null && c1.getCount() != 0) {
        if (c1.moveToFirst()) {
            do {
                listRowAuto contactListItems = new listRowAuto();

                contactListItems.setName(c1.getString(c1
                        .getColumnIndex("name")));
                contactListItems.setPhone(c1.getString(c1
                        .getColumnIndex("phone")));
                contactList.add(contactListItems);

            } while (c1.moveToNext());
        }
    }
    c1.close();

    listAdapterAuto contactListAdapter = new listAdapterAuto(
            Auto.this, contactList);
    listView.setAdapter(contactListAdapter);

}

}

I want to complete this application. I am new to the database and cursor adapters. Anyone help?

Aucun commentaire:

Enregistrer un commentaire