Using pre-populated database,it gives my activity has stopped - java

I am adding one existing database in my assets folder,after that those data has to be copy and then create new database and then stored locally,In that new database i can also add.
I am showing those data in my listview activity also. Now my activity has stopped.
My db activity.
#Override
public void onCreate(SQLiteDatabase db) {
openDataBase();
}
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 {
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 (mDb == null) {
createDataBase();
mDb = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READWRITE);
}
return mDb;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS"+ DATABASE_TABLE_PROJ);
onCreate(db);
}
}
public void saveCategoryRecord(Category category) {
ContentValues values = new ContentValues();
values.put(CATEGORY_COLUMN_TITLE , category.getTitle());
values.put(CATEGORY_COLUMN_CONTENT, category.getContent());
values.put(CATEGORY_COLUMN_DATE, category.getDate());
// Inserting Row
mDb.insert(DATABASE_TABLE_PROJ, null, values);
mDb.close(); // Closing database connection
}
public Cursor fetchProject(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE_PROJ, new String[] {CATEGORY_COLUMN_ID,CATEGORY_COLUMN_TITLE,CATEGORY_COLUMN_CONTENT,CATEGORY_COLUMN_DATE}, CATEGORY_COLUMN_ID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllProjects() {
// TODO Auto-generated method stub
return mDb.query(DATABASE_TABLE_PROJ, new String[] {CATEGORY_COLUMN_ID, CATEGORY_COLUMN_TITLE, CATEGORY_COLUMN_CONTENT, CATEGORY_COLUMN_DATE }, null, null, null, null, null,null);
}
public void close() {
mDbHelper.close();
}
public long createProject(String title, String content, String date) {
ContentValues initialValues = new ContentValues();
initialValues.put(CATEGORY_COLUMN_TITLE , title);
initialValues.put(CATEGORY_COLUMN_CONTENT, content);
initialValues.put(CATEGORY_COLUMN_DATE, date);
return mDb.insert(DATABASE_TABLE_PROJ, null, initialValues);
}
public boolean updateProject(String title, String content, String date) {
ContentValues args = new ContentValues();
args.put(CATEGORY_COLUMN_TITLE, title);
args.put(CATEGORY_COLUMN_CONTENT, content);
args.put(CATEGORY_COLUMN_DATE, date);
return mDb.update(DATABASE_TABLE_PROJ, args, CATEGORY_COLUMN_TITLE + "=" + title, null) > 0;
}
public GinfyDbAdapter(Context ctx) {
this.mCtx = ctx;
String packageName = mCtx.getPackageName();
DB_PATH = String.format("//data//data//%s//databases//", packageName);
try {
externalDbStream = mCtx.getAssets().open(DB_NAME);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public GinfyDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
MY listactivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item2);
lv =(ListView)findViewById(R.id.list);
mDbHelper = new GinfyDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
My logcat error
10-04 06:26:47.273: E/AndroidRuntime(1075): FATAL EXCEPTION: main
10-04 06:26:47.273: E/AndroidRuntime(1075): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ibetter.Ginfy/com.ibetter.Ginfy.YourPrayerActivity}: android.database.sqlite.SQLiteDatabaseLockedException: database is locked (code 5): , while compiling: PRAGMA journal_mode
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.os.Handler.dispatchMessage(Handler.java:99)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.os.Looper.loop(Looper.java:137)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-04 06:26:47.273: E/AndroidRuntime(1075): at java.lang.reflect.Method.invokeNative(Native Method)
10-04 06:26:47.273: E/AndroidRuntime(1075): at java.lang.reflect.Method.invoke(Method.java:511)
10-04 06:26:47.273: E/AndroidRuntime(1075): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-04 06:26:47.273: E/AndroidRuntime(1075): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-04 06:26:47.273: E/AndroidRuntime(1075): at dalvik.system.NativeStart.main(Native Method)
10-04 06:26:47.273: E/AndroidRuntime(1075): Caused by: android.database.sqlite.SQLiteDatabaseLockedException: database is locked (code 5): , while compiling: PRAGMA journal_mode
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteConnection.executeForString(SQLiteConnection.java:627)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteConnection.setJournalMode(SQLiteConnection.java:313)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteConnection.setWalModeFromConfiguration(SQLiteConnection.java:287)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:215)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
10-04 06:26:47.273: E/AndroidRuntime(1075): at com.ibetter.Ginfy.GinfyDbAdapter$DatabaseHelper.openDataBase(GinfyDbAdapter.java:193)
10-04 06:26:47.273: E/AndroidRuntime(1075): at com.ibetter.Ginfy.GinfyDbAdapter$DatabaseHelper.onCreate(GinfyDbAdapter.java:101)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
10-04 06:26:47.273: E/AndroidRuntime(1075): at com.ibetter.Ginfy.GinfyDbAdapter.open(GinfyDbAdapter.java:276)
10-04 06:26:47.273: E/AndroidRuntime(1075): at com.ibetter.Ginfy.YourPrayerActivity.onCreate(YourPrayerActivity.java:118)
10-04 06:26:47.273: E/AndroidRuntime(1075): at android.app.Activity.performCreate(Activity.java:5104)
My activity has stopped now,i searched in google it shows error in open function.

As you are trying to open the same database twice and that leads to a conflict
android.database.sqlite.SQLiteDatabaseLockedException: database is locked (code 5)
ie. In simple words, it seems your database is already open when you try to open it again.So Please check, if you forgot to close the database after you have opened it somewhere.

Related

How to rectify this error iin Recyclerview with database

When i am trying to display the contacts in card view when i click on Button it shows fatal exception error it doesnot display cardview anyone can solve this programming with brillliance and another error is it show only one cardview when i click on again the app will be strucked?
Showcontacts.java
public class ShowContacts extends Activity
{
private SQLiteDatabase db;
DbOperations doo;
private List<Contacts> contactsList;
private RecyclerView rv;
private Cursor c;
String names,email,address;
int phone;
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle_layout);
doo = new DbOperations(this);
openDatabase();
rv = (RecyclerView)findViewById(R.id.recyclerview);
initializeData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(linearLayoutManager);
rv.setHasFixedSize(true);
ContactAdapter cc = new ContactAdapter(contactsList);
rv.setAdapter(cc);
}
public void initializeData() {
contactsList = new ArrayList<>();
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
private void openDatabase() {
db = openOrCreateDatabase("contactDB", Context.MODE_PRIVATE,null);
}
}
Logacat error
06-28 08:57:43.107 568-568/com.example.anilkumar.contactstask E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anilkumar.contactstask/com.example.anilkumar.contactstask.ShowContacts}: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:127)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:53)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1538)
at com.example.anilkumar.contactstask.ShowContacts.initializeData(ShowContacts.java:44)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:34)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 
at android.app.ActivityThread.access$600(ActivityThread.java:123) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4424) 
at java.lang.reflect.Method.invokeNative(Native Method) 
Another logact error
06-28 13:14:40.552 11252-11261/com.example.anilkumar.contactstask E/SQLiteDatabase: close() was never explicitly called on database '/data/data/com.example.anilkumar.contactstask/databases/contactDB'
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1943)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1007)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:962)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1043)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1036)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:761)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:215)
at com.example.anilkumar.contactstask.ShowContacts.openDatabase(ShowContacts.java:66)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:33)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
Just update
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
to
String read_query = "select * from "+ ContactsTask.ContactsEntry.TABLE_NAME;
Always close cursor. update your initializeData method
public void initializeData() {
try {
contactsList = new ArrayList<>();
try{
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
} catch (Exception e) {
// exception handling
} finally {
if(c != null){
c.close();
}
}
}

Couldn't read row 0, col 2 from CursorWindow

i try to delete the data from listview by using the context menu and i get this java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
public List<AssignmentRecord> getAllAssignment(){
List<AssignmentRecord> records = new ArrayList<AssignmentRecord>();
Cursor cursor = database.query(AssigmentContract.Assigment.TABLE_NAME, allColumn , null,
null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
AssignmentRecord assignmentRecord = new AssignmentRecord();
assignmentRecord.setAssname(cursor.getString(0));
assignmentRecord.setAssTime(cursor.getString(1));
assignmentRecord.setAssID(cursor.getString(2));
records.add(assignmentRecord);
cursor.moveToNext();
}
first line error assignmentRecord.setAssID(cursor.getString(2));
dbcon.open();
List<AssignmentRecord> records = dbcon.getAllAssignment();
dbcon.close();
second error is List records = dbcon.getAllAssignment();
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE "
+ AssigmentContract.Assigment.TABLE_NAME +
"(" + AssigmentContract.Assigment.COLUMN_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " +
AssigmentContract.Assigment.COLUMN_ASS + " TEXT," +
AssigmentContract.Assigment.COLUMN_ASSDATE+ " TEXT)";
public final class AssigmentContract {
public AssigmentContract(){}
public static abstract class Assigment implements BaseColumns{
public static final String TABLE_NAME ="AssignmentV2";
public static final String COLUMN_ASS ="AssignmentTitle";
public static final String COLUMN_ASSDATE ="AssignmentDate";
public static final String COLUMN_ID ="AssignmentID";
}
}
LOGCAT
my.com.chyi.schedulev2 E/CursorWindow﹕ Failed to read row 0, column 2 from a CursorWindow which has 1 rows, 2 columns.
my.com.chyi.schedulev2 D/AndroidRuntime﹕ Shutting down VM
my.com.chyi.schedulev2 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x9e4f5908)
/my.com.chyi.schedulev2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{my.com.chyi.schedulev2/my.com.chyi.schedulev2.assigmentActivity}: java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:434)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at my.com.chyi.schedulev2.SQLController.getAllAssignment(SQLController.java:102)
at my.com.chyi.schedulev2.assigmentActivity.onCreate(assigmentActivity.java:73)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230
at android.app.ActivityThread.access$600(ActivityThread.java:141)at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234 at android.os.Handler.dispatchMessage(Handler.java:99)at android.os.Looper.loop(Looper.java:137)at android.app.ActivityThread.main(ActivityThread.java:5041) 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:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)
Try this,
while(!cursor.isAfterLast()){
AssignmentRecord assignmentRecord = new AssignmentRecord();
assignmentRecord.setAssname(cursor.getString(cursor.getColumnIndex("your_respective_column_name));
assignmentRecord.setAssTime(cursor.getString(cursor.getColumnIndex("your_respective_column_name)));
assignmentRecord.setAssID(cursor.getString(cursor.getColumnIndex("your_respective_column_name)));
records.add(assignmentRecord);
cursor.moveToNext();
I have demonstrated what Harry suggested you to do. Here replace your_respective column name with the value you given for the columns which your trying to retrieve. For Ex: when you are trying to fetch the value of AssId it will be _id or some thing. Hope this helps you.
Your getAllAssignment() should be as,
List<AssignmentRecord> records = new ArrayList<AssignmentRecord>();
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery("select * from " + TABLE_NAME, null);
if(cursor.moveToFirst()){
do {
AssignmentRecord assignmentRecord = new AssignmentRecord();
assignmentRecord.setAssID(cursor.getString(0));
assignmentRecord.setAssname(cursor.getString(1));
assignmentRecord.setAssTime(cursor.getString(2));
} while(cursor.moveToNext());
}
database.close();

App closes on insert query SQLlite

My app closes when i insert this sample records for testing, i tried it in many ways. from activity class im sending string values to insert to the database.
My MainInvoiceActivity Class
public class MainInvoiceActivity extends Activity {
private DBHelper mydb ;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_invoice);
if ( mydb.insertsample( "one" , "two" , "3" )){ // LINE NO 67
Toast.makeText(getApplicationContext(), "Insert Success!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
}
}
My database SQLiteOpenHelper class
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String TABLE_SAMPLE = "sample";
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_SAMPLE_TABLE = "CREATE TABLE sample ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"one TEXT, "+
"two TEXT, "+
"three TEXT )";
db.execSQL(CREATE_SAMPLE_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS sample");
onCreate(db);
}
public boolean insertsample (String one, String two, String three)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues myValues = new ContentValues();
myValues.put(one, one);
myValues.put(two, two);
myValues.put(three, three);
db.insert(TABLE_SAMPLE, null, myValues);
return true;
}
}
LOG message
E/AndroidRuntime(1153): FATAL EXCEPTION: main
E/AndroidRuntime(1153): Process: com.ezycode.pos, PID: 1153
E/AndroidRuntime(1153): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ezycode.pos/com.ezycode.pos.MainInvoiceActivity}: java.lang.NullPointerException
E/AndroidRuntime(1153): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
E/AndroidRuntime(1153): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
E/AndroidRuntime(1153): at android.app.ActivityThread.access$800(ActivityThread.java:135)
E/AndroidRuntime(1153): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
E/AndroidRuntime(1153): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(1153): at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(1153): at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime(1153): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1153): at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(1153): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime(1153): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime(1153): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(1153): Caused by: java.lang.NullPointerException
E/AndroidRuntime(1153): at com.ezycode.pos.MainInvoiceActivity.onCreate(MainInvoiceActivity.java:67)
E/AndroidRuntime(1153): at android.app.Activity.performCreate(Activity.java:5231)
E/AndroidRuntime(1153): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime(1153): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
Correct code will be like something below
public class MainInvoiceActivity extends Activity {
private DBHelper mydb ;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_invoice);
mydb = new DBHelper(this); //This is missing your code.
if ( mydb.insertsample( "one" , "two" , "3" )){ // LINE NO 67
Toast.makeText(getApplicationContext(), "Insert Success!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
}

SQLite Application Crashes during launch

So I am trying out a tutorial for SQLite I have seen in the internet, and after tweaking it a bit I launched it and it crashes. Before modifying the code, it works. I know that some of the functions are deprecated, but that didn't seem to be the issue because as I said it ran before I modified it. I also know that the error is on line 44 on one of my classes (I have put a comment in this line to distinguish it) but I don't see why it gives me an error. Here is my code:
AndroidSQLite.java:
package com.example.sqlite;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class AndroidSQLite extends Activity {
EditText inputContent1, inputContent2, inputContent3;
Button buttonAdd, buttonDeleteAll;
private SQLiteAdapter mySQLiteAdapter;
ListView listContent;
SimpleCursorAdapter cursorAdapter;
Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inputContent1 = (EditText)findViewById(R.id.UserID);
inputContent2 = (EditText)findViewById(R.id.Password);
inputContent3 = (EditText)findViewById(R.id.Fname);
buttonAdd = (Button)findViewById(R.id.add);
buttonDeleteAll = (Button)findViewById(R.id.deleteall);
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
String[] from = new String[]{SQLiteAdapter.KEY_USERS_USERID, SQLiteAdapter.KEY_USERS_PASSWORD, SQLiteAdapter.KEY_USERS_FNAME};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2};
cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
buttonAdd.setOnClickListener(buttonAddOnClickListener);
buttonDeleteAll.setOnClickListener(buttonDeleteAllOnClickListener);
}
Button.OnClickListener buttonAddOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String data1 = inputContent1.getText().toString();
String data2 = inputContent2.getText().toString();
String data3 = inputContent3.getText().toString();
mySQLiteAdapter.insert(data1, data2, data3);
updateList();
}
};
Button.OnClickListener buttonDeleteAllOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mySQLiteAdapter.deleteAll();
updateList();
}
};
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mySQLiteAdapter.close();
}
#SuppressWarnings("deprecation")
private void updateList(){
cursor.requery();
}
}
SQLiteAdapter.java
package com.example.sqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
public static final String DB_NAME = "adserve";
public static final String DB_TABLE_USERS = "users";
public static final int DB_VERSION = 1;
public static final String KEY_USERS_USERID = "_id";
public static final String KEY_USERS_PASSWORD = "Password";
public static final String KEY_USERS_FNAME = "Fname";
//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + DB_TABLE_USERS + " ("
+ KEY_USERS_USERID + " integer primary key, "
+ KEY_USERS_PASSWORD + " text not null, "
+ KEY_USERS_FNAME + " text not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c){
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, DB_NAME, null, DB_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, DB_NAME, null, DB_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insert(String UserID, String Password, String Fname){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_USERS_USERID, UserID);
contentValues.put(KEY_USERS_PASSWORD, Password);
contentValues.put(KEY_USERS_FNAME, Fname);
return sqLiteDatabase.insert(DB_TABLE_USERS, null, contentValues);
}
public int deleteAll(){
return sqLiteDatabase.delete(DB_TABLE_USERS, null, null);
}
public Cursor queueAll(){
String[] columns = new String[]{KEY_USERS_USERID, KEY_USERS_PASSWORD, KEY_USERS_FNAME};
Cursor cursor = sqLiteDatabase.query(DB_TABLE_USERS, columns, null, null, null, null, null);
return cursor;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
}
And my logcat:
02-20 10:04:53.811: E/AndroidRuntime(1940): FATAL EXCEPTION: main
02-20 10:04:53.811: E/AndroidRuntime(1940): Process: com.example.sqlite, PID: 1940
02-20 10:04:53.811: E/AndroidRuntime(1940): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sqlite/com.example.sqlite.AndroidSQLite}: java.lang.IllegalArgumentException: column '_id' does not exist
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread.access$700(ActivityThread.java:135)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.os.Handler.dispatchMessage(Handler.java:102)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.os.Looper.loop(Looper.java:137)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread.main(ActivityThread.java:4998)
02-20 10:04:53.811: E/AndroidRuntime(1940): at java.lang.reflect.Method.invokeNative(Native Method)
02-20 10:04:53.811: E/AndroidRuntime(1940): at java.lang.reflect.Method.invoke(Method.java:515)
02-20 10:04:53.811: E/AndroidRuntime(1940): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
02-20 10:04:53.811: E/AndroidRuntime(1940): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
02-20 10:04:53.811: E/AndroidRuntime(1940): at dalvik.system.NativeStart.main(Native Method)
02-20 10:04:53.811: E/AndroidRuntime(1940): Caused by: java.lang.IllegalArgumentException: column '_id' does not exist
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:303)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.widget.CursorAdapter.init(CursorAdapter.java:172)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.widget.CursorAdapter.<init>(CursorAdapter.java:120)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.widget.ResourceCursorAdapter.<init>(ResourceCursorAdapter.java:52)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.widget.SimpleCursorAdapter.<init>(SimpleCursorAdapter.java:78)
02-20 10:04:53.811: E/AndroidRuntime(1940): at com.example.sqlite.AndroidSQLite.onCreate(AndroidSQLite.java:43)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.Activity.performCreate(Activity.java:5243)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
02-20 10:04:53.811: E/AndroidRuntime(1940): ... 11 more
Quoting the documentation for CursorAdapter:
The Cursor must include a column named "_id" or this class will not work
You do not have such a column in your Cursor, as far as I can tell.
One solution would be to switch from query() to rawQuery(), so you can add ROWID AS _id to your list of columns, to fulfil the CursorAdapter contract.
The SQLite Site says,
In SQLite, table rows normally have a 64-bit signed integer ROWID which is unique among all rows in the same table. (WITHOUT ROWID tables are the exception.)
So if you want to use a column only as an integer primary key, you can directly access the in built one using ROWID.
and the document on Cursor adapter says,
The Cursor must include a column named "_id" or this class will not work. Additionally, using MergeCursor with this class will not work if the merged Cursors have overlapping values in their "_id" columns.
which is the error you are getting.
Also if searched, you could find solution to yours on already answered SO questions like this one.

Null Pointer Exception : coudnt find solution

I am getting error in my code which is not understandable.. please help me find out what issue is it.
i have database class and main activity.. it shows in log but when it comes to appear at my emulator's screen it gives me error.
my database class:
package com.example.nearby_places;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Database extends SQLiteOpenHelper {
//database name & version number
private static final String db_name = "nearby_places";
private static final int db_version = 1;
//tables
private static final String table_placetypes = "placetypes";
private static final String table_places = "table_places";
//column names
private static final String type_id = "type_id";
private static final String type_name = "type_name";
private static final String place_id = "place_id";
private static final String place_name = "place_name";
private static final String place_address = "place_address";
private static final String place_contact = "place_contact";
public Database(Context context) {
super(context, db_name, null, db_version);
// TODO Auto-generated constructor stub
}
// create table queries
String create_table_placetypes = "CREATE TABLE IF NOT EXISTS " + table_placetypes + "("
+ type_id + " INTEGER PRIMARY KEY NOT NULL," + type_name + " TEXT" + ")";
String create_table_places = "CREATE TABLE IF NOT EXISTS table_places (place_id INTEGER PRIMARY KEY NOT NULL, place_name TEXT, place_address TEXT, place_contact TEXT, type_id INTEGER, FOREIGN KEY (type_id) REFERENCES table_placetypes(type_id))";
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(create_table_placetypes);
Log.d("creating", "placetypes created");
db.execSQL(create_table_places);
Log.d("creating", "places created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + table_placetypes);
db.execSQL("DROP TABLE IF EXISTS " + table_places);
onCreate(db);
}
// add placetypes
void addplacetypes (placetypes pt) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(type_name, pt.getTypename());
db.insert(table_placetypes, null, values);
db.close();
}
// Getting single placetypes
placetypes getPlacetypes(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(table_placetypes, new String[] {type_id,
type_name }, type_id + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
placetypes pt = new placetypes(Integer.parseInt(cursor.getString(0)),
cursor.getString(1));
// return contact
return pt;
}
// Getting All placetypes
public List<placetypes> getAllPlacetypes() {
List<placetypes> placetypesList = new ArrayList<placetypes>();
// Select All Query
String selectQuery = "SELECT * FROM " + table_placetypes;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
placetypes pt = new placetypes();
pt.setTypeid(Integer.parseInt(cursor.getString(0)));
pt.setTypename(cursor.getString(1));
//String name = cursor.getString(1);
//MainActivity.ArrayofName.add(name);
// Adding contact to list
placetypesList.add(pt);
} while (cursor.moveToNext());
}
// return placetype list
return placetypesList;
}
// Getting placetypes Count
public int getPlacetypesCount() {
String countQuery = "SELECT * FROM " + table_placetypes;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
public void addplaces(places p) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(place_name, p.getPlace_name());
values.put(place_address, p.getPlace_address());
values.put(place_contact, p.getPlace_contact());
values.put(type_id, p.getT_id());
Log.d("Type ID", String.valueOf(p.getT_id()));
db.insert(table_places, null, values);
db.close();
}
places getPlaces(int pid) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(table_places, new String[] {place_id, place_name, place_address, place_contact,type_id}, place_id + "=?", new String[] { String.valueOf(pid) } , null, null, null, null);
if(cursor != null)
cursor.moveToFirst();
places p = new places(Integer.parseInt(cursor.getString(0)),
Integer.parseInt(cursor.getString(1)),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4)
);
cursor.close();
return p;
}
public List<places> getAllPlaces(String typeName) {
List<places> placeList = new ArrayList<places>();
//String selectQuery = "SELECT * FROM table_places INNER JOIN placetypes ON placetypes.type_id=table_places.type_id ";
//String selectQuery = "SELECT * FROM table_places WHERE table_places.type_id="+Integer.toString(typeid);
String selectQuery ="SELECT * FROM table_places WHERE placetypes.place_name="+typeName+" INNER JOIN placetypes ON placetypes.type_id=table_places.type_id";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst() )
{
do{
places p = new places();
/*p.setT_id(cursor.getColumnIndex(type_id));
p.setPlace_id(cursor.getColumnIndex(place_id));
p.setPlace_name(cursor.getColumnIndex(place_name));
*/
p.setT_id(cursor.getInt(0));
p.setPlace_id(cursor.getInt(1));
p.setPlace_name(cursor.getString(2));
p.setPlace_address(cursor.getString(3));
p.setPlace_contact(cursor.getString(4));
/*String t_id = cursor.getString(4);
String p_name = cursor.getString(2);
String p_address = cursor.getString(3);
String p_contact = cursor.getString(1);*/
placeList.add(p);
}while(cursor.moveToNext());
}
cursor.close();
return placeList;
}
public int getPlaceCount () {
String selectQuery = "SELECT * FROM " +table_places;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(create_table_places, null);
cursor.close();
return cursor.getCount();
}
}
MainActivity
package com.example.nearby_places;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private ListView listView;
public static ArrayList<String> ArrayofName = new ArrayList<String>();
public static final String PLACETYPE = "com.example";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Database db = new Database(this);
if(db.getAllPlacetypes().isEmpty())
{
/**
* CRUD Operations
* */
// Inserting Places
Log.d("Insert: ", "Inserting ..");
db.addplacetypes(new placetypes("RESTURAUNTS"));
db.addplacetypes(new placetypes("MALLS"));
db.addplacetypes(new placetypes("GAS STATIONS"));
db.addplacetypes(new placetypes("HOTELS"));
db.addplacetypes(new placetypes("MOTELS"));
}
// Reading all Places
Log.d("Reading: ", "Reading all placetypes..");
if(ArrayofName.isEmpty())
{
List<placetypes> placetypes = db.getAllPlacetypes();
for (placetypes pt : placetypes)
{
String log = "Id: "+pt.getTypeid()+" ,Name: " + pt.getTypename();
// Writing Places to log
Log.d("Name: ", log);
System.out.println(log);
ArrayofName.add(pt.getTypename());
}
}
listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
int pos = listView.getAdapter().getCount() -1;
listView.getAdapter().getItemId(pos);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
String type = ((TextView) v).getText().toString();
Toast.makeText(getApplicationContext(), type, Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(),MainActivity2.class);
i.putExtra(PLACETYPE, type);
startActivity(i);
/*Cursor cursor = (Cursor) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "id: " +id+ "position: " +position+ "row id: " +(cursor.getColumnIndex("" +
"")), Toast.LENGTH_LONG).show();
*/
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
}
}
);
}
}
Logcat
10-11 17:21:51.871: D/Reading:(4932): Reading all placetypes..
10-11 17:21:51.871: D/Name:(4932): Id: 1 ,Name: RESTURAUNTS
10-11 17:21:51.875: I/System.out(4932): Id: 1 ,Name: RESTURAUNTS
10-11 17:21:51.875: D/Name:(4932): Id: 2 ,Name: MALLS
10-11 17:21:51.875: I/System.out(4932): Id: 2 ,Name: MALLS
10-11 17:21:51.875: D/Name:(4932): Id: 3 ,Name: GAS STATIONS
10-11 17:21:51.875: I/System.out(4932): Id: 3 ,Name: GAS STATIONS
10-11 17:21:51.875: D/Name:(4932): Id: 4 ,Name: HOTELS
10-11 17:21:51.875: I/System.out(4932): Id: 4 ,Name: HOTELS
10-11 17:21:51.875: D/Name:(4932): Id: 5 ,Name: MOTELS
10-11 17:21:51.875: I/System.out(4932): Id: 5 ,Name: MOTELS
10-11 17:21:51.887: D/AndroidRuntime(4932): Shutting down VM
10-11 17:21:51.887: W/dalvikvm(4932): threadid=1: thread exiting with uncaught exception (group=0x41c77300)
10-11 17:21:51.894: E/AndroidRuntime(4932): FATAL EXCEPTION: main
10-11 17:21:51.894: E/AndroidRuntime(4932): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nearby_places/com.example.nearby_places.MainActivity}: java.lang.NullPointerException
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.os.Handler.dispatchMessage(Handler.java:99)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.os.Looper.loop(Looper.java:137)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-11 17:21:51.894: E/AndroidRuntime(4932): at java.lang.reflect.Method.invokeNative(Native Method)
10-11 17:21:51.894: E/AndroidRuntime(4932): at java.lang.reflect.Method.invoke(Method.java:511)
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-11 17:21:51.894: E/AndroidRuntime(4932): at dalvik.system.NativeStart.main(Native Method)
10-11 17:21:51.894: E/AndroidRuntime(4932): Caused by: java.lang.NullPointerException
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.example.nearby_places.MainActivity.onCreate(MainActivity.java:62)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.Activity.performCreate(Activity.java:5008)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-11 17:21:51.894: E/AndroidRuntime(4932): ... 11 more
10-11 17:21:53.695: I/Process(4932): Sending signal. PID: 4932 SIG: 9
Your call to getAdapter is returning null because you're calling it before setAdapter, try this instead :
listView.setAdapter(adapter);
int pos = listView.getAdapter().getCount() -1;
listView.getAdapter().getItemId(pos);
If you have a NULLPOINTER Exception please have a deep look at your LogCat. Especial at the Line where it says Caused by.
Learn how to read and use your LogCat, and try to find the Line where it mentions your class/package name and analyse this line.
Caused by: java.lang.NullPointerException
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.example.nearby_places.MainActivity.onCreate(MainActivity.java:62)
The problem is in
List<placetypes> placetypes = db.getAllPlacetypes();
The query you are using is wrong. It should be
`SELECT * FROM table_places INNER JOIN placetypes ON placetypes.type_id=table_places.type_id WHERE placetypes.place_name="+typeName+`"

Categories

Resources