Android - sqlite delete all - java

i am working on an app to develop my knowledge so far i have created a calendar app which user can make appointment when clicking on a date. i then have a delete button which opens all the appointments created in a fresh activity, there i have: a list view which displays all appointments a textview which displays the selected appointment (selected by the user to delete) and a button remove. the remove button removes all the items from the sqlite but i can only see this working when the application is restarted i know i am missing something else in my code.. how do i clear the listview at the same time any help would be much appreciated
my code:
delete all method
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
button code:
public void onClick(View v) {
switch(v.getId()){
case R.id.removeBtn:
dm.deleteAll();
break;
}
thank you
}

Maybe not the most elegant, but I don't build my UI in onCreate(). Instead, in onCreate(), I call another method initializeUI(), and that is where I build my user interface. Then, anytime I do something that should be reflected in the interface (update the database or whatever), I just need to call my method initializeUI() again.
Edit: Also look into notifyDataSetChanged() for your adapter as exampled here

First check if your database is writable (getWritableDatabase)
Then check that your "TABLE_NAME" is in fact the table name.
Then you could try to use execSQL("delete from " + TABLE_NAME);
if that does not work, you could try to close the db.
finally try putting it in a transaction
beginTransaction();
.. delete..
endTransaction();

If you are actually changing the data from the Adapter used in the ListView, you could use requery() method on the cursor used to populate the Adapter. This should reflect your changes!

Related

Updating a document in firebase with an auto generated ID

I've learned how to add and delete from Firebase. It's quite straightforward.
My delete code which is activated when clicking the delete button, it's found in my adapter class (it's the only way I could get the delete button click registered correctly)
public void deleteJournal(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
}
And to add (which is in another class)
CollectionReference diaryRef = FirebaseFirestore.getInstance()
.collection("Diary");
diaryRef.add(new Diary(growName, description, priority));
But I don't even know where to begin to update. I will be putting the edit code in the adapter class which will open a dialog window to edit values.
I know how to create the window and edit the values and set new variables for this data. But how do I make sure I'm applying this updated data to the document with the corresponding edit button that clicked? Then update Firebase correctly.
diaryRef.add(new Diary(growName, description, priority)).addOnSuccessListener(documentReference -> {
String id = documentReference.getId();
db.collection("Diary").document(id).update("entryId", id);
});
now you will have a unique id to delete or update the entry
But how do I make sure I'm applying this updated data to the document
In the same way, you are deleting the document. Please see the method below:
public void updateJournal(int position) {
Diary diary = getSnapshots().getSnapshot(position).toObject(Diary.class);
//Make the changes
}
Once you have the Diary object, you can make the desired updates and then write the document back to the database, as shown in your question.

Updating an AlertDialog's ListView contents while running

I have an instance of an AlertDialog that I am using as a file selection dialog. It includes a hierarchical browsing function - if a directory is selected from the list, it should show the list of files in that directory. It also includes a 'up level' button, that returns to the previous folder. I need a way to update the contents of the AlertDialog object's built-in ListView while the dialog is displaying without reloading the dialog object from its builder. I am aware that Adapters exist, but I need a way to load data from a defined instance variable, not an external XML resource. I am overriding the onResume method to avoid dialog closure on button press, and this is where I need to run the list update.
This is the code I have now for the selection button's OnClick listener inside the onResume method.
alertDialog.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
if(position >= 0)
{
String[] list = getCurrentFileList();
if(list[position].equals(NO_ITEMS_TEXT)){
return;
}
// If the selected file is a directory, recursively update the file list and redisplay.
if(getCurrentFileRefList()[position].isDirectory()){
src = getCurrentFileRefList()[position];
parseFileList();
//todo update ListView from loaded file list
}else { // If the selected item is a file, give the value to the handler and dismiss the dialog.
handler.handleEvent(DialogActionEventHandler.ResultID.SUBMITTED, getCurrentFileRefList()[position]);
alertDialog.dismiss();
}
}
}
});
The parseFileList(); method is used to get the current list of files from the selected source file.
Any help would be appreciated!
You should notify the UI to update the list by calling notifyDatasetChanged
https://developer.android.com/reference/android/widget/BaseAdapter.html#notifyDataSetChanged()
Once you update the data in the adapter, you must call Adapter.notifyDatasetChanged.
I eventually solved the issue with a workaround - here's how.
Since the notifyDatasetChanged() method did not push updates to the dialog correctly without creating an entire adapter class for the initial creation stage - something which I considered far too time-consuming and inefficient for my purposes - I worked around the issue by relaunching the dialog every time an update was needed, and tracked the current directory's position in the master tree relative to the source directory by using an ArrayList with a pointer that updated every time the user switched folders. This process also required making the onCreate() method relaunch-aware, and enabling the onResume() method to be called manually. Once these were done, the resultant section of code looked like this:
alertDialog.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position >= 0)
{
String[] list = getCurrentFileList();
if(list[position].equals(NO_ITEMS_TEXT)){
return;
}
// If the selected file is a directory, recursively update the file list and redisplay.
if(getCurrentFileRefList()[position].isDirectory()){
src = getCurrentFileRefList()[position];
hierarchyID ++;
onCreateDialog(null);
alertDialog.dismiss();
}else { // If the selected item is a file, give the value to the handler and dismiss the dialog.
handler.handleEvent(DialogActionEventHandler.ResultID.SUBMITTED, getCurrentFileRefList()[position]);
alertDialog.dismiss();
}
}
}
});
This discards the old dialog, updates the hierarchy tree tracking array and associated pointer, and relaunches the dialog with the new path. It is significantly more complex than I hoped, but it works well. I hope someone finds this useful!

RecyclerView doesn't refresh after modifying database's row

I am programming an app for Android. I uploaded it to GitHub: app
I have a ViewPager (MainActivity.java) controlling two Fragments. On the first Fragment (FirstFragment.java) you can add People (People.java) which appears on the RecyclerView (also on FirstFragment.java). When you click one of the list items on the RecyclerView its details (name and id) appear on the second fragment (SecondFragment.java). The SecondFragment.java also contains a button you can delete the selected People with.
To store the People objects I used a List of People and managed it with the methods in PeopleLab.java. The program was working fine: I could add/remove People objects to the list and it appeared on the RecyclerView fine.
After that, I decided to replace the List with a database. It only meant creating the database (the 3 files in database folder) and editing the already existing and two new methods in PeopleLab.java. The other files remained untouched.
The database is working as expected (checked it with sqlite3), I can add/remove People like before and the queries work. My only problem is that the changes don't appear on the RecyclerView. But if I close and reopen the app, the changes appear.
It's like the RecyclerView doesn't care about the database in runtime, only do when the app starts (or closes, not sure).
Do you have any idea what could cause the problem? My only guess is I miss something about how Android apps handle databases.
P.S.: sorry for my English.
You do call notifyDataSetChanged() on the adapter but you don't provide any new data for that adapter.
In your FirstFragment :
private void updateUI() {
PeopleLab peopleLab = PeopleLab.get(getActivity());
List<People> peoples = peopleLab.getPeople();
if(mAdapter == null) {
mAdapter = new PeopleAdapter(peoples);
mRecyclerView.setAdapter(mAdapter);
} else {
// You actually have to change your dataset
mAdapter.changeDataSet(peoples);
}
}
And in your Adapter :
public void changeDataSet(List<People> people) {
this.mPeoples = people;
notifyDataSetChanged();
}
This some brutal way to do it though.
It would be better to notify your adapter on insertion / removal calling notifyItemInserted(int itemPosition) or notifyItemRemoved(int itemPosition). (And refreshing your dataset, by the way)
It will not work automatically.You can either use to notify the adapter the underlying data has been changed so that adapter can fetch and reload the data.It can be done using adapter.notifyDataSetChanged()
Or use can use CursorLoader to achieve the same

JavaFX ListView adding item into observable list doesn't reflect change and it's not selectable

I have run into pretty messed up behaviour with my ListView, I have listview created in controller with data attached to it.
#FXML
private ListView<Weapon> listViewWeapons;
...
private final ObservableList<Loadout> loadoutList;
public LoadoutViewController() {
...
loadoutList =FXCollections.observableList(CsgoRr.getModel().getLoadoutCache());
...
}
#Override
public void initialize(URL location, ResourceBundle resources) {
...
listViewLoadouts.setItems(loadoutList);
...
}
I call method attached to button, which has function of adding new loadout into list
#FXML
private void newLoadoutOnAction() {
try {
Loadout loadoutToBeStored = new Loadout(new Long[10], "Loadout" + newDuplicateNameLoadoutIncrement);
loadoutToBeStored.setId(DbUtil.storeLoadout(loadoutToBeStored));//store and set id.
CsgoRr.getModel().getLoadoutCache().add(loadoutToBeStored);
System.out.println("Stored new loadout ");
listViewLoadouts.getSelectionModel().select(loadoutToBeStored);
for (Loadout loadout : loadoutList) {
System.out.println("DEBUG LOADOUT CONTAINER OBSERVABLE:" + loadout);
}
} catch (SQLException ex) {//duplicate name
if (ex.getErrorCode() == 23505) {
newDuplicateNameLoadoutIncrement++;
newLoadoutOnAction();
}
Logger.getLogger(LoadoutViewController.class.getName()).log(Level.SEVERE, null, ex);
}
}
All the data is correctly loaded and stored, I have debugged that part of course. But even though I call method newLoadoutOnAction and I put data into list which observable list has reference to, change is not seen up until I resize that listView. That's not the only problem, even after I resize listView and I'm able to see item in a list I can't select it I have to call construstor and initializer again to be able to select this item. I have never encountered this behaviour, how do I fix these problems?
Problem with refreshing item in the list: I have tried to remove items and set them again, and some other solutions common to this problem bud nothing worked even if I put setItems(null) I can't get it to work, items are still there.
Latest item inserted is not selectable (through UI) until I call my controller again and recreate everything. I have this item selected with code.
listViewLoadouts.getSelectionModel().select(loadoutToBeStored);
This actually selected needed item bud I don't see any feedback in the UI and I can't select it with my mouse. Even if I remove this line I still can't select it with a mouse till I call my view again (constructor and initializer).
I know this is a bit more complex problem so I decided to show you what's happening with a gif.
Hope it's clear.
The Javadoc for FXCollections.observableList states:
Note that mutation operations made directly to the underlying list are not reported to observers of any ObservableList that wraps it.
For this reason loadoutList is not connected to the list in CsgoRr.getModel().getLoadoutCache() after creation. This means that when newLoadoutOnAction() calls:
CsgoRr.getModel().getLoadoutCache().add(loadoutToBeStored);
it is not picked up by loadoutList, or the ListView watching it. If you change CsgoRr.getModel().getLoadoutCache() to use an ObservableList, and assign that directly to loadoutList your function should work as desired.
The other option would be to add your loadoutToBeStored to loadoutList instead, but then you would need to also synchronise with the List in CsgoRr.getModel()

android listview pagination implementation

Hi am working on an android application. And am using a listview in some of my activities.
The problem is all of my listviews displayed are much longer so that the user needs to scroll the whole list to go for the last item.
Am trying to implement a pagination for this, like at first say only 20 items need to displayed on the listview. And at the end of my listview i need a titlebar which have next & previous buttons and on clicking on next button the listview will load the next records from 21st to 40 and so on.
Am using java rest webservice to load the listview.
Can anyone give me a good suggestion for solving my problem.?
Solution 1:
You can load all the data at once if its not TOO MUCH, store it locally & then you can navigate in that locally stored data. Define some variables like StartPoint & EndPoint & get the desired data from that stored data. Increment decrement the values of StartPoint & EndPoint by using the PreviouButton & NextButton.
Solution 2:
Get only the desired data from your data source for example 10 records each time when a Navigation button is clicked.
I suggest than you load list data in a custom Adapter class that extends BaseAdapter class. Like #oriolpons suggested, you should add a footer view, and when you click on button next call some method that is fetching next for example 20 rows, and then add them in your adapter object and call notifyDataSetChanged().
For example
private OnClickListener mListener = new OnClickListener() {
public void onClick(View v) {
ArrayList<YourObject> al = getSomeData(int startRow, int endRow);
MyCustomAdapter adapter = new MyCustomAdapter();
for(YourObject a : al)
adapter.add(a);
getListView.setAdapter(adapter);
notifyDataSetChanged();
}
};
Hope this helps.
The easiest solution is to add a footer view to the listview. And on the item click listener you can see if it is the last position (load more items), or not
//add the footer before adding the adapter, else the footer will not load!
View footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false);
this.getListView().addFooterView(footerView);
#Tijo . Refer this site http://www.androidhive.info/2012/03/android-listview-with-load-more-button/. You can have a button which would call the execute method of Async task and that will load the remaining list for you.

Categories

Resources