I am having an issue with my college project. I am trying to delete a row from my one of my tables using the following query.
//---deletes a particular match---
public boolean deleteMatch(String name) {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
return sqLiteDatabase.delete(TABLE_FIXTURES, MATCH_OPPONENT + " = " + name, null) > 0;
}
Here I am trying to delete a record based upon the match_opponent and passing the String value name.
I am then calling this method in my EditSchedule activity below:
public class EditSchedule extends AppCompatActivity {
public Button fixtureSearch;
public EditText opponentName;
public String searchTerm;
ListView editMatch;
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase sqLiteDatabase;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editfixture);
editMatch = (ListView) findViewById(R.id.listViewEditMatch);
opponentName = (EditText) findViewById(R.id.fixtureOpponentDelete);
searchTerm = opponentName.getText().toString();
fixtureSearch = (Button) findViewById(R.id.fixtureSearchButton);
fixtureSearch.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.deleteMatch(searchTerm);
}
}
);
}
}
So when I test my application by typing in a name of an opponent that I have in the fixture table and clicking on the delete button, I get the following error:
01-06 07:49:42.476 25778-25778/com.example.myacer.clubhub E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.database.sqlite.SQLiteException: near "=": syntax error (code 1): , while compiling: DELETE FROM fixtures WHERE match_opponent =
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.delete(SQLiteDatabase.java:1494)
at com.example.myacer.clubhub.database.DBHelper.deleteMatch(DBHelper.java:243)
at com.example.myacer.clubhub.manager.EditSchedule$1.onClick(EditSchedule.java:47)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Can anyone see where I am going wrong? All help greatly appreciated.
You are passing blank value in deleteMatch(), put searchTerm = opponentName.getText().toString(); inside onClick()
fixtureSearch.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
searchTerm = opponentName.getText().toString();
dbHelper.deleteMatch(searchTerm);
}
}
);
As well as change your deleteMatch() method
sqLiteDatabase.delete(TABLE_FIXTURES, MATCH_OPPONENT + " = ?",new String[]{name});
try this:
sqLiteDatabase.delete(TABLE_FIXTURES, MATCH_OPPONENT + " = ?", new String[]{name})
Related
I am a newcomer to Android development.
I can't figure out how to get Android Studio to just take what's in my SQLite database and paste its contents into a listview. I thought there would be a easy way after Log the output but can able to display everything there is in a database in a ListView but it appears to be much more in a different way of doing it.
public class MainActivity extends AppCompatActivity {
EditText nameEditText;
EditText phoneEditText;
ListView updateListView;
SQLiteDatabase sqLiteDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameEditText = findViewById(R.id.nameEditText);
phoneEditText = findViewById(R.id.phoneEditText);
updateListView = findViewById(R.id.updatedListView);
sqLiteDatabase = this.openOrCreateDatabase("Contact", MODE_PRIVATE, null);
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS users(name VARCHAR, phone INT(11),id INTEGER PRIMARY KEY)");
}
public void OnClick(View view) {
if (nameEditText.equals("") || phoneEditText.equals("")) {
Toast.makeText(this, "Fields shouldn't be empty", Toast.LENGTH_SHORT).show();
} else {
sqLiteDatabase.execSQL("INSERT INTO users(name, phone) VALUES('" + nameEditText.getText().toString() + "','" + phoneEditText.getText().toString() + "')");
Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM users", null);
int nameIndex = c.getColumnIndex("name");
int phoneIndex = c.getColumnIndex("phone");
int idIndex = c.getColumnIndex("id");
if (c != null && c.getCount() > 0) {
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
String str = c.getString(0);
String UpdatedList = (c.getString(nameIndex));
String phonelist = (c.getString(phoneIndex));
String list = (UpdatedList+phonelist);
ArrayList<String> arrayList = new ArrayList<String>(Integer.parseInt(list));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,arrayList);
updateListView.setAdapter(arrayAdapter);
Log.i("User Name", c.getString(nameIndex));
Log.i("userResults - age", Integer.toString(c.getInt(phoneIndex)));
Log.i("userResults - id", Integer.toString(c.getInt(idIndex)));
c.moveToNext();
}
}
}
}
}
My Logput
2020-01-22 20:22:48.353 28783-28783/? D/AndroidRuntime: Shutting down VM
2020-01-22 20:22:48.357 28783-28783/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mysqlapp, PID: 28783
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:6669)
at android.view.View.performClickInternal(View.java:6638)
at android.view.View.access$3100(View.java:789)
at android.view.View$PerformClick.run(View.java:26145)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6669)
at android.view.View.performClickInternal(View.java:6638)
at android.view.View.access$3100(View.java:789)
at android.view.View$PerformClick.run(View.java:26145)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NumberFormatException: For input string: ""
at java.lang.Integer.parseInt(Integer.java:627)
at java.lang.Integer.parseInt(Integer.java:650)
at com.example.mysqlapp.MainActivity.OnClick(MainActivity.java:65)
call setAdapter method outside, after you declare whole arrayList from sql, outside of for loop
I have update from database using set status method when click button to getting error i have send to array list to next activity while getting error
I'm new in android programming
ImageButton ibAddMore = (ImageButton) findViewById(R.id.ibAddMore);
ibAddMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper db = new DataBaseHelper(getApplicationContext());
for (People people : alertList) {//In this Line getting error
if (people.getStatus() == 1) {
db.setStatus(people.getId(), "0");
alertList.add(people);
} else {
db.setStatus(people.getId(), "1");
}
}
Intent intent = new Intent(AlertList.this, AlertListAll.class);
startActivity(intent);
}
}
);
Set Status Method
public int setStatus(String peopleId, String status) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(STATUS, status);
return sqLiteDatabase.update(TABLE_PEOPLE, values, ID + "=?",
new String[]{peopleId});
}
Exception:
java.util.ConcurrentModificationException
at java.util.AbstractList$SimpleListIterator.next(AbstractList.java:62)
at com.Jaydeep.alertme.activity.AlertList$1.onClick(AlertList.java:67)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5136)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
you can't modify the same collection you are looping on directly. But you can do it using a ListIterator. E.g.
for (ListIterator<People> iterator = alertList.listIterator(); iterator.hasNext(); ) {//In this Line getting error
People people = iterator.next();
if (people.getStatus() == 1) {
db.setStatus(people.getId(), "0");
iterator.add(people);
} else {
db.setStatus(people.getId(), "1");
}
}
You are adding elements to the same list while you are iterating. It's more java than android.
Btw why you want to add the same element again to the list you are iterating thru ?
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();
}
}
New to Android here. I've made a new Fragments app, and I'm having trouble accessing the database from the Fragment.
Here's the class:
public class ShopListActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoplist);
db = new DatabaseHelper(this); // tried getApplicationContext(), and getBaseContext() as well
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public void onClickAddProduct(View view) {
TextView productName = (TextView) findViewById(R.id.add_product_text);
SQLiteDatabase dbWritable = db.getWritableDatabase(); // <-- crashes here
ContentValues values = new ContentValues();
values.put("Name", (String) productName.getText());
dbWritable.insert("Lists", "Name", values);
}
All the other solutions I found on SO didn't help.
DatabaseHelper is a very basic DB Helper class:
public DatabaseHelper(Context context) {
super(context, dbName, null, dbVersion);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_TABLES);
db.execSQL("INSERT INTO Lists (Name) VALUES('Test')");
}
Here's the Logcat:
07-07 21:03:24.351 9641-9641/com.chas.shopforme E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3606)
at android.view.View.performClick(View.java:4211)
at android.view.View$PerformClick.run(View.java:17362)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5227)
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:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3601)
... 11 more
Caused by: java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.chas.shopforme.ShopListActivity.onClickAddProduct(ShopListActivity.java:69)
... 14 more
Note: I know there are more questions like this, but their solutions didn't work for me.
try this
db = new DatabaseHelper(this.getApplicationContext());
I tried adding this as a comment to your question, but nasty things happen to code in comments.
Assuming you've tried a) in the comment above, and it didn't work, an example of b) follows:
protected void onCreate(Bundle savedInstanceState) {
...
Handler hand = new Handler();
hand.post(new Runnable() {
public void run() {
dbInit();
}
});
}
public void dbInit() {
db = new DatabaseHelper(this);
}
This allows the fragment manager to finish setting up the fragment before you try to use it. What it is doing is sending a message to itself which is processed when the fragment's message handler loop is running.