I have a cursor that filled my database and i would like to delete the elements from this table.
her is the removal code fro my database:
public void deleteItem(int id){
SQLiteDatabase database = this.getWritableDatabase();
database.delete(ContractParaGastos.GASTO, ContractParaGastos.Columnas.MONTO + " = ?", new String[]{String.valueOf(id)});
database.close();
}
And here is the removal code in recyclerviewAdapter:
viewHolder.button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
databaseHelper.deleteItem(i);
}
});
}
I add this line in my adapter:
databaseHelper = new DatabaseHelper(context, ContractParaGastos.GASTO, null, 4);
But when i click on the delete button nothing happens. the line is still present in my recyclerview.
Help me please!
Because you didn't initialised the databaseHelper.
Try this code:
DatabaseHelper databaseHelper = new DatabaseHelper(this); //in case of activity.
DatabaseHelper databaseHelper = new DatabaseHelper(getActivity()); //in case of Fragment.
Paste this code in onCreate() of Activity or onCreateView() of Fragment.
Thanks and let me know if some need to know more.
from the little code you provided I would check that the variable i in:
databaseHelper.deleteItem(i);
represents really an existing id of the record I need to delete.
Related
While inserting my listview gets refreshed automatically but not update when the item in the listview is updated. It only updates on database. I can see the listview is updated when I close the application and open again, or come back from previous activity.
I found some discussion related to my problem. Like: Refresh ListView with ArrayAdapter after editing an Item . Her I found that make a new method to populate the Listview and call it in the onResume method of your activity.
And the problem has been solved using this. But I do not get how to make new method mentioned like there. Could anybody help me to make it understandable?
My code in activity class:
personNamesListView = (ListView) findViewById(R.id.traineeslist);
traineeListAdapter = new ArrayAdapter<Trainee>(this,
android.R.layout.simple_list_item_1,
currentTraining.getTraineeArrayList());
personNamesListView.setAdapter(traineeListAdapter);
protected void onResume() {
super.onResume();
}
And this way I populated my personNamesListView using method stringToString() in model class;
public void loadTraineeList() {
DatabaseHelper db = DatabaseHelper.getInstance();
this.traineeArrayList = new ArrayList <Trainee>();
Cursor cursor = db.select("SELECT * FROM person p JOIN attendance a ON p._id = a.person_id WHERE training_id="+Integer.toString(this.getId())+";");
while (cursor.moveToNext()) {
Trainee trainee = new Trainee();
trainee.setID(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.PERSON_ID)));
trainee.setFirstname(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_FIRSTNAME)));
trainee.setLastname(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_LASTNAME)));
trainee.setJobTitle(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_JOBTITLE)));
trainee.setEmail(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_EMAIL)));
trainee.setCompany(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_COMPANY)));
trainee.setDepartment(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_DEPARTMENT)));
trainee.setBadgeNumber(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_BADGE)));
// Pass to the arraylist
this.traineeArrayList.add(trainee);
}
}
public ArrayList<Trainee> getTraineeArrayList() {
return traineeArrayList;
}
public void setTraineeArrayList(ArrayList<Trainee> traineeArrayList) {
this.traineeArrayList = traineeArrayList;
}
I insert and Update data into database into one method:
public void storeToDB() {
DatabaseHelper db = DatabaseHelper.getInstance();
db.getWritableDatabase();
if (this.id == -1) {
// Person not yet stored into Db => SQL INSERT
// ContentValues class is used to store a set of values that the
// ContentResolver can process.
ContentValues contentValues = new ContentValues();
// Get values from the Person class and passing them to the
// ContentValues class
contentValues.put(DatabaseHelper.PERSON_FIRSTNAME, this
.getFirstname().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_LASTNAME, this
.getLastname().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_JOBTITLE, this
.getJobTitle().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_EMAIL, this.getEmail());
contentValues.put(DatabaseHelper.PERSON_COMPANY, this.getCompany()
.trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_DEPARTMENT, this
.getDepartment().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_BADGE, this
.getBadgeNumber().trim().toUpperCase());
// here we insert the data we have put in values
this.setID((int) db.insert(DatabaseHelper.TABLE_PERSON,
contentValues));
} else {
// Person already existing into Db => SQL UPDATE
ContentValues updateTrainee = new ContentValues();
updateTrainee.put(DatabaseHelper.PERSON_FIRSTNAME, this
.getFirstname().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_LASTNAME, this
.getLastname().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_JOBTITLE, this
.getJobTitle().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_EMAIL, this.getEmail());
updateTrainee.put(DatabaseHelper.PERSON_COMPANY, this.getCompany()
.trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_DEPARTMENT, this
.getDepartment().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_BADGE, this
.getBadgeNumber().trim().toUpperCase());
db.update(DatabaseHelper.TABLE_PERSON, updateTrainee,
DatabaseHelper.PERSON_ID+"= ?", new String[]{Integer.toString(this.getId())});
System.out.println("Data updated");
}
}
You should call traineeListAdapter.notifyDataSetChanged() whenever you update your ArrayList representing the items in the ListView.
There's a similar question here that can give you some help.
Although I've accomplished something similar using
yourlistview.invalidateViews()
after changing the data to show in the listview
when notifyDataSetChanged() didn't work.
EDIT:
After making all the operations in the data that I want to show i just set the adapter and try to refresh my listview by calling invalidateViews().
selectedStrings = new ArrayList<String>(typeFilterStrings);
adapter.setArrayResultados(selectedStrings);
listTypeFilter.invalidateViews();
It's not obligatory to set the adapter again in my case worked.
use like this:
Create an instance of your custom adapter, so you can use it anywhere you like...
public class ScoreList extends SherlockFragmentActivity {
private ListView listViewScore;
private ScoreListAdapter adapter;
static List<Score> listScore = new ArrayList<Score>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.score_list);
ctx = this;
listScore = dbh.getAllScores();
listViewScore = (ListView) findViewById(R.id.score_list);
adapter = new ScoreListAdapter(ctx, R.layout.score_row_item, listScore);
listViewScore.setAdapter(adapter);
((BaseAdapter) listViewScore.getAdapter()).notifyDataSetChanged();
}
}
By the way, if your listScore array is already loaded, then you do not need to use
adapter.notifyDatasetChanged();
I feel like i am missing something simple and stupid. I have a list view with a few buttons at the top. The list view is initially populated with data. When you click a button the list view is supposed to populate its self based on a changed variable in the Where statement. In reality i could probably just start a new List activity but i feel like there is a better way.
I have been reading up on CursorAdapter.changeAdapter() and notifydatasetchanged() I have not implemented this yet because i am having a more basic problem.
I can successfully query the database and display the static results in the list. When i try to break process into steps i am running into an ERROR: Invalid statement in fillWindow. The best i understand this is caused by improperly closing cursors databases and DB helpers and for this reason people use content providers.
For now i am just trying to get this to work.
public class DListView extends ListActivity implements OnClickListener{
public static final String NAME = "Name";
public static final String DESCRIPT = "Description";
public static final String DATABASE_TABLE = "Table";
public static final String DAY = "Day_id";
/** Called when the activity is first created. */
private Cursor c = null;
private String[] colsfrom = {"_id", NAME, DESCRIPT, DAY};
private int[] to = new int[] {R.id.text01, R.id.text02, R.id.text03, R.id.text04};
public int b = 0;
public int d = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drinklistview);
View left = findViewById(R.id.left_button);
left.setOnClickListener(this);
View right = findViewById(R.id.right_button);
right.setOnClickListener(this);
Intent thisIntent = getIntent();
b = thisIntent.getIntExtra("_b", 0);
//0 is the default argument is nothing is passed.
d = thisIntent.getIntExtra("_d", 0); //same idea as above.
c = fillList();
/*this creates a new cursor adapter
#param Context is the list context that you will be filling.
#param int layout is the layout that you will use for the rows
#param Cursor is the cursor that was returned from the query
#param from is the column names
#param to is the layout ids that the fields will be put in.
#param from is the column names to map from
#param to is the layout ids that the column fields will be put in.
*/
SimpleCursorAdapter myAdapter = new SimpleCursorAdapter(this, R.layout.row, c, colsfrom, to);
setListAdapter(myAdapter);
}
private Cursor fillList() {
DBHelper DbHelper = new DBHelper(this);
Cursor cursor;
String wHERE = "_id = " + b + " AND Day_id = " + d ;
try {
myDbHelper.openDataBase();
}
catch(SQLException sqle){
throw sqle;
}
cursor = myDbHelper.getDrinks(DATABASE_TABLE, colsfrom, wHERE, null, null,null, null);
myDbHelper.close();
return cursor;
}
When i put the contents of fillList() in the onCreate() it displays data just fine. When i pull it out it gives me the ERROR. Why is this happening? If anyone has a better way of going about this i would love to read it. Or we can play a game called "What stupid thing am i doing wrong Now?
Thankyou.
EDIT:From DBHelper
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
I am thinking that my problem line is the super.close() I believe that this line closes the database and anything affiliated with it which means the cursor that i try to use after its closed. I may be wrong though. Please explain if you can.
Your problem is right here, in your fillList():
myDbHelper.close(); // <--- here
return cursor;
you make a cursor object but close your database connection before you even get to use it (this component of the database) which would render it useless or null if you would. Usually you close the cursor and then the database. But that's not throwing the error. That error specifically is because you hooked up this cursor to a cursorAdapter trying to fill your listView with nothing. Move that and it should be gone.
So where do you move it then? If you have a cursor hooked up to listView, it needs to be open the entire time, otherwise you'll get another error saying "attempting to re-open an already closed object". I'd suggest putting in the onDestroy() when then listView is being chucked as well.
YaY Solved. Mango is exactly correct. Thankyou for you suggestion to close cursor in on destroy. I am not sure if the super.close() line closes my cursor or not. but i will look into it. I am also going to put the database query in async task for kicks and giggles.
I simply moved the two lines that created a new SimpleCursorAdapter and set the list view into the fillList method.
I also implemented my buttons and just added fillList at the end.
Here is the code that fixed things. Simple Mistake.
private void fillList() {
DBHelper DbHelper = new DBHelper(this);
Cursor cursor;
String wHERE = "_id = " + b + " AND Day_id = " + d ;
try {
myDbHelper.openDataBase();
}
catch(SQLException sqle){
throw sqle;
}
cursor = myDbHelper.getDrinks(DATABASE_TABLE, colsfrom, wHERE, null, null,null, null);
SimpleCursorAdapter myAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, colsfrom, to);
setListAdapter(myAdapter);
myDbHelper.close();
}
And Here is wehre i call the fillList again that updates my list view.
public void onClick(View v) {
switch(v.getId()) {
//Mess with d based on button click
}
fillList();
}
Now the application has to create a new simple cursor adapter every time something is changed.
If anyone has any ideas on implementing this without creating a new CursorAdapter every time that would help very much but my initial problem is solved. Thankyou for your help. Just the fact that you wanted to see my stack trace told me that i was not doing anything wrong in the code that i initially presented and i forgot that i made my dbHelper close all connections. Thankyou mango. I solved this last night but couldnt post it. Thanks for the explanation good sir. If you have any insight to the constant creation of a new cursoradapter i would be very pleased to see it. Maybe i need to fix the super.close() command somehow.
EDIT
First activity opens a database: I used the code
LoginDbAdapter mDbHelper; // as a data member
called
// in my onCreate() of my main activity login
mDbHelper = new LoginDbAdapter(this);
then in my
public void onResume(){
mDbHelper.open(); // opens only when the activity is resumed
super.onResume();
}
then I do the same thing above in my second activity to add a user. This worked.
My issue is as follows:
**How do i open a link to a second table in my database to access
a users information only. And where do i close it. **
UPDATE
an alternative way that works much better is initializing my DbAdapter in the onResume and then calling DbAdapter.open(); only when i need access to the db and closing it right after the work is done with DbAdapter.close();
note: it is also important to call startManagingCursor(cursor); and stopManagingCursor(cursor);
Might these helps:
find these where you getting writeable permission like these::
SQLiteDatabase db=this.getWritableDatabase();
Now wat you need to do iz::
db.insert(TABLE, null, values);
db.close();//put these after inserting your database;
You need to go in to your DATABASEADAPTER class
then close the database connection after insertion as per above code
in your Activity
mDbHelper= new DatabaseAdapter(this);
and in your insert method of DatabaseAdapter class
SQLiteDatabase db = this.getWritableDatabase();
and at last in your insert method call db.close();
You need to Edit these line inside your LoginDbAdapter inside close() method;
public class LoginDbAdapter
{
// close the database
public void close(){
if(mDbHelper != null){
mDbHelper.close();
mDb.close;//insert these line ;these close sqlitedatabase;
}
}
}
give the command to close inside a try{} catch{}
I'm getting two contradicting Exceptions when creating and populating my new SQLiteDatabase in Android. In short my code:
SQLiteOpenHelper extending class:
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_TABLE_CREATE);
loadLevelData(db); //puts data in the database
//db.close(); <<< ?
}
In my activity class I instantiate this class (in onCreate()), and call getWritableDatabase():
dbHelper = new DbOpenHelper(getApplicationContext());
database = dbHelper.getWritableDatabase();
Now if I don't call db.close() after populating the database, like above, I get
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
However if I DO close it, I get the following exception:
java.lang.IllegalStateException: database not open
on getWritableDatabase().
This really confuses me, so could anyone help me with what's wrong?
You are not expected to close the database in the DatabaseHelper class. However you need to close it every time you open it calling getWritableDatabase:
dbHelper = new DbOpenHelper(getApplicationContext());
database = dbHelper.getWritableDatabase();
//... do something with database
database.close();
You are closing your database at the wrong time.
I typically keep the database around like this:
public class MyActivity extends Activity {
SQLiteDatabase writeableDb;
// ...
// Code
// ...
public void onStart(){
super.onCreate(savedState);
// Do stuff, get your helper, etc
writeableDb = helper.getWriteableDatabase();
}
public void onStop(){
writeableDb.close();
super.onStop();
}
}
Alternatively, wrap all your code working with that db connection in a try/finally block
db = helper.getWriteableDatabase();
try { // ... do stuff ... }
finally { db.close(); }
Note: All of the opening/closing should be done in the Activity working with the database, not the open helper.
I want to show an item from editext to spinner and save to db... how to store item in the db...
my code :
spinner populating
final DBAdapter db = new DBAdapter(this);
db.open();
Spinner spin = (Spinner) findViewById(R.id.spinner1);
AdapterCountries = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item);
AdapterCountries.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(AdapterCountries);
Cursor cursor = db.getAllTitles1();
while (cursor.moveToNext()){
results=cursor.getString(2);
AdapterCountries.add(results);
}
db.close();
and
Button d_ok=(Button)dialog.findViewById(R.id.d_ok);
final EditText filename=(EditText)dialog.findViewById(R.id.filename);
d_ok.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
//
}});
any one can help me with example
Thank you...
If you don't have one already, then I really think you should have a SQL helper class extending the given SQLiteOpenHelper Android class. It really simplifies DB operations. See: http://developer.android.com/guide/topics/data/data-storage.html#db
It's heavily recommended.
If you set up the helper class and the instance of that class is set up like SQLHelper sql = new SQLHelper(this); then modifying the database is fairly simple. You should set up a method that you call from your buttons onClickListener (and possibly run it in an AsyncTask or a background thread):
private void addFileName(final String filename) {
SQLiteDatabase db = sql.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(yourKeyHere, filename);
db.insert(yourDBNameHere, null, values);
}
And then call the method and add it to your adapter from the listener:
d_ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
addFileName(filename.getText().toString();
AdapterCountries.add(filename);
}
});