I keep getting an error when I launch an activity, at first it was null pointer exception but now I have no idea what the error is and its just not working anymore
Logcat:
02-18 13:15:28.885: D/dalvikvm(328): GC_EXTERNAL_ALLOC freed 50K, 53% free 2553K/5379K, external 2730K/3266K, paused 115ms
02-18 13:15:29.762: D/dalvikvm(328): GC_EXTERNAL_ALLOC freed 1K, 53% free 2552K/5379K, external 6764K/8447K, paused 51ms
02-18 13:15:45.312: D/dalvikvm(328): GC_EXTERNAL_ALLOC freed 11K, 52% free 2583K/5379K, external 8695K/10350K, paused 46ms
02-18 13:15:45.582: D/AndroidRuntime(328): Shutting down VM
02-18 13:15:45.582: W/dalvikvm(328): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-18 13:15:45.592: E/AndroidRuntime(328): FATAL EXCEPTION: main
02-18 13:15:45.592: E/AndroidRuntime(328): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.connectfour/com.example.connectfour.ScoreActivity}: java.lang.NullPointerException
02-18 13:15:45.592: E/AndroidRuntime(328): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.os.Handler.dispatchMessage(Handler.java:99)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.os.Looper.loop(Looper.java:123)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-18 13:15:45.592: E/AndroidRuntime(328): at java.lang.reflect.Method.invokeNative(Native Method)
02-18 13:15:45.592: E/AndroidRuntime(328): at java.lang.reflect.Method.invoke(Method.java:507)
02-18 13:15:45.592: E/AndroidRuntime(328): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-18 13:15:45.592: E/AndroidRuntime(328): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-18 13:15:45.592: E/AndroidRuntime(328): at dalvik.system.NativeStart.main(Native Method)
02-18 13:15:45.592: E/AndroidRuntime(328): Caused by: java.lang.NullPointerException
02-18 13:15:45.592: E/AndroidRuntime(328): at com.example.connectfour.Database.getScores(Database.java:57)
02-18 13:15:45.592: E/AndroidRuntime(328): at com.example.connectfour.ScoreActivity$MyCursorAdapter.<init>(ScoreActivity.java:21)
02-18 13:15:45.592: E/AndroidRuntime(328): at com.example.connectfour.ScoreActivity.onCreate(ScoreActivity.java:49)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-18 13:15:45.592: E/AndroidRuntime(328): ... 11 more
02-18 13:15:54.303: I/Process(328): Sending signal. PID: 328 SIG: 9
Code
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE" + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " INTEGER);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Database(Context context) {
ourContext = context;
}
public Database open() {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public Cursor getScores() {
return ourDatabase.rawQuery("SELECT * FROM "+DATABASE_TABLE, null); //No Parameter
}
}
Code Score Activity: This is score activity line 21 is where the super thing is:
#SuppressWarnings("deprecation")
public MyCursorAdapter(Context context) {
super(context, new Database(context).getScores());
scoreIdx = getCursor().getColumnIndex(Database.KEY_NAME);
// TODO Auto-generated constructor stub
}
When you create your Database class you still have not instanciated the ourDatabase variable.
So when you're doing getScores you are going to have a NPE.
Just try to open() it before.
You have not initialized ourDatabase. first initialize it by calling open()...
public MyCursorAdapter(Context context) {
super(context, new Database(context).open().getScores(););
scoreIdx = getCursor().getColumnIndex(Database.KEY_NAME);
// TODO Auto-generated constructor stub
}
Try this.
public Database open() {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public Cursor getScores() {
ourDatabase = open();
return ourDatabase.rawQuery("SELECT * FROM "+DATABASE_TABLE, null); //No Parameter
close() ;
}
Here, when you call getScores, you db will be created and assigned to ourDatabase which then can be used easily. Let me know if this works.
Related
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();
}
}
}
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();
}
}
Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (people.moveToNext()){
int NameIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
int NumIndex = people.getColumnIndex(PhoneLookup.NUMBER);
String Name = people.getString(NameIndex);
//String Num = people.getString(NumIndex);
myArr.add(Name.toString());
myNum.add(Num.toString());
}
Hello I am experiencing problems retrieving a contact's phone number where each time i enable this line of code
String Num = people.getString(NumIndex);
03-03 15:38:30.436: E/AndroidRuntime(496): FATAL EXCEPTION: main
03-03 15:38:30.436: E/AndroidRuntime(496): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.GhattasAk.RingMe/com.GhattasAk.RingMe.Main}: java.lang.IllegalStateException: get field slot from row 0 col -1 failed
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.os.Looper.loop(Looper.java:123)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread.main(ActivityThread.java:3683)
03-03 15:38:30.436: E/AndroidRuntime(496): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 15:38:30.436: E/AndroidRuntime(496): at java.lang.reflect.Method.invoke(Method.java:507)
03-03 15:38:30.436: E/AndroidRuntime(496): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-03 15:38:30.436: E/AndroidRuntime(496): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-03 15:38:30.436: E/AndroidRuntime(496): at dalvik.system.NativeStart.main(Native Method)
03-03 15:38:30.436: E/AndroidRuntime(496): Caused by: java.lang.IllegalStateException: get field slot from row 0 col -1 failed
03-03 15:38:30.436: E/AndroidRuntime(496): at android.database.CursorWindow.getString_native(Native Method)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.database.CursorWindow.getString(CursorWindow.java:329)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:49)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.database.CursorWrapper.getString(CursorWrapper.java:135)
03-03 15:38:30.436: E/AndroidRuntime(496): at com.GhattasAk.RingMe.Main.onCreate(Main.java:49)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
03-03 15:38:30.436: E/AndroidRuntime(496): ... 11 more
the application crashes.. I do not understand why
this is the edit to get a name based on a number is this true ?
if(state==TelephonyManager.CALL_STATE_RINGING)
{
// Find contact based on name.
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"NUMBER = '" + number + "'", null, null);
if (cursor.moveToFirst()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// Get all phone numbers.
Cursor phones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String numb = phones.getString(phones.getColumnIndex(Phone.DISPLAY_NAME));
}
phones.close();
}
cursor.close();
Probably becouse the contact have multiple phone nrs like work...
try this:
// Find contact based on name.
//
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"DISPLAY_NAME = '" + NAME + "'", null, null);
if (cursor.moveToFirst()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//
// Get all phone numbers.
//
Cursor phones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
switch (type) {
case Phone.TYPE_HOME:
// do something with the Home number here...
break;
case Phone.TYPE_MOBILE:
// do something with the Mobile number here...
break;
case Phone.TYPE_WORK:
// do something with the Work number here...
break;
}
}
phones.close();
}
cursor.close();
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.
I'm trying to build a small app that takes a data file in external storage and emails it. I keep getting 'null pointer exceptions' right away in logcat and then my app dies. I can't seem to locate my exception and I am wondering if there is a way to determine the line of code that is causing this. I have the MainActivity class and then a class called SendData- the code is below. I'm new at this so any help would be greatly appreciated- thank you.
private static final String TAG = "MainActivity_ErrorLog";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// Create the getData intent
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
public void onStart()
{
{
try
{
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite())
{
// verify the paths
String currentDBPath = "TLC_COMMON/database.db";
String backupDBPath = "database.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists())
{
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
}
catch (Exception e)
{
// change the V below to E when complete
Log.v(TAG,"ERROR: Database file not created");
}
startActivity(intentgetData);
}
}
}
--new class
public class SendData extends Activity
{
private static final String TAG = "MainActivity";
/* Checks if external storage is available to read */
public boolean isExternalStorageReadable()
{
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
{
return true;
}
return false;
}
/** Called when the user clicks the Send My Data button */
public SendData(View view)
{
// Send data by email
{
File root = Environment.getExternalStorageDirectory();
// verify it is saving as this file name; also path in previous class
String fileName = "database.db";
if (root.canWrite())
{
File attachment = new File(root, fileName);
Intent email = new Intent(Intent.ACTION_SENDTO);
email.putExtra(android.content.Intent.EXTRA_SUBJECT, "Exercise data");
email.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"test#gmail.com"});
// is the Uri necessary?
email.putExtra(android.content.Intent.EXTRA_TEXT, Uri.fromFile(attachment));
// look at this VVV
startActivity(Intent.createChooser(email, "Send the data via Email"));}
else
{
// Change the V below to E when complete
Log.v(TAG, "Email send failed");
}
}
}
public void finish()
{
}
}
11-13 13:29:37.343: W/dalvikvm(3319): threadid=1: thread exiting with uncaught exception (group=0x418e3300)
11-13 13:29:37.343: E/AndroidRuntime(3319): FATAL EXCEPTION: main
11-13 13:29:37.343: E/AndroidRuntime(3319): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.va.datasender/com.example.va.datasender.MainActivity}: java.lang.NullPointerException
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.os.Handler.dispatchMessage(Handler.java:99)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.os.Looper.loop(Looper.java:137)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.reflect.Method.invokeNative(Native Method)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.reflect.Method.invoke(Method.java:511)
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-13 13:29:37.343: E/AndroidRuntime(3319): at dalvik.system.NativeStart.main(Native Method)
11-13 13:29:37.343: E/AndroidRuntime(3319): Caused by: java.lang.NullPointerException
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.content.ComponentName.<init>(ComponentName.java:75)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.content.Intent.<init>(Intent.java:3301)
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.Class.newInstanceImpl(Native Method)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.Class.newInstance(Class.java:1319)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
11-13 13:29:37.343: E/AndroidRuntime(3319): ... 11 more
Find the lowest "Caused by" and continue down until you reach a line from your code:
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
at android.content.ComponentName.<init>(ComponentName.java:75)
at android.content.Intent.<init>(Intent.java:3301)
at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36)
The <init> means you are doing something as a class variable or inside a constructor before the Activity has a valid Context... But the specific problem is on line 36.
I would guess that you are trying to create an Intent with this. Initialize your Intent inside onCreate() instead.
Found it. Change this:
// Create the getData intent
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
to:
Intent intentgetData;
and inside onCreate() (or onStart() just before calling startActivity()) add:
intentgetData = new Intent(MainActivity.this, SendData.class);
Your problem comes from line 36 on your MainActivity. Check there for the problem.
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36)
The exeption from line number 36: at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36).
Since the error log also shows android.content.Intent.<init> after the MainActivity.java:36, I would check the value for the first parameter in the following line, when instantiating intentgetData:
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
Instead of having the instatiation done there, try doing it in the onStart() method just before calling startActivity(intentgetData);:
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
startActivity(intentgetData);