How to correctly retrieve data? - android

I've done a list that shows titles, when i click on an item is opened an activity that shows the description of the element; i'm getting this description using the id of the element.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String descrizione=mydb.getDescription(id+1,titolo.getText().toString());
}
This is the method in my database:
public String getDescription(long id,String formulario)
{
String descrizione="NADA";
SQLiteDatabase db= this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from "+formulario+" where id="+id+"", null );
if(res!=null && res.getCount()>0){
res.moveToFirst();
descrizione = res.getString(res.getColumnIndex("Descrizione"));
res.close();
}
return descrizione;
}
THE PROBLEM: when i delete an element all the description result shifted forward. I don't know if the problem is with the cursor, the item's id acquisition or with the delete method... any help is valued
This is my delete method:
public Integer deleteFormula (String formula, String formulario)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(formulario, "Formule = ? ", new String[] { formula});
}

First off, when you want to show database data in a ListView, you should use CursorAdapter to bind database data with your ListView. From the code you've posted, can't tell whether and how it's been implemented. If you have any doubts about it I suggest you look into this article which explains this subject very well https://github.com/codepath/android_guides/wiki/Populating-a-ListView-with-a-CursorAdapter
Secondly, when you successfully bind the data to your ListView, then in onItemClick method you can use the second parameter which is View and represents the clicked ListView row , to retrieve the data that is shown in that row.
Thirdly, when you delete a row from your database table, you should synchronize your ListView by getting a new cursor and calling your CursorAdapter changeCursor method with new cursor as argument.
This is just a rough sketch, but I hope it will help at least a little bit.

Cursor adapter would be the optimal solution. But if you want to stick with the same code when you delete a row from your database table you must ensure that you also get the updated list of data from your database.
And also you don't have to add + 1 to this code. If you have to add + 1 it means you're doing things wrong.
String descrizione=mydb.getDescription(id+1,titolo.getText().toString());
This would work well if you are just constantly updating your list with the data from your database whenever there are changes, and id doesn't represent the databaseID as it represents the ID of the view within the adapter.

Your issue is using position to determine id in :-
String descrizione=mydb.getDescription(id+1,titolo.getText().toString());
At first, assuming 3 columns inserted:-
First column has an id of 1, 2nd 2 and 3rd 3. So initially if rows are sorted according to id (good chance of this happening but no guarantee) then position 0 (first row displayed) + 1, will display data for id 1, position (2nd item in the List) 1 will show data for id 2 etc and all looks good.
However if you delete id 2 then:-
The 1st item in the list will display data from id 1 and position 0 still equates to id 1.
However the 2nd Item in the list will display data from the table for row id 3 BUT position 1 + 1 = 2 so the wrong id is calculated.
In short you cannot use position to correlate to the id.
You need to somehow get the appropriate row. Perhaps the easiest solution is to use a CursorAdapater, then id will be the id (column name must be _id).

Related

Accessing SQLite record from ListView item?

I display the user data from SQLite database using a custom CursorAdapter.
Each ListView item is actually a layout with many TextViews.
in the CursorAdapter.bindView() method I get database data from the Cursor, and display their modified, prettier versions to the user. Here's what I mean:
public void bindView(View view, Context context, Cursor cursor) {
//get listview items Views
TextView dayTextView = (TextView)view.findViewById(R.id.listview_item_day);
//...
//get data from cursor
int day = cursor.getInt(1);
//...
//display data nicely to the user
String sDay = "Day number " + String.valueOf(day) " was a very nice day";
dayTextView.setText(sDay);
}
I want that when the user long clicks an item (I'll use OnItemLongClickListener for that), the item will be deleted (easy peasy) but I also want to delete the day record from the database.
When the ListView item gets clicked, I have the next parameters supplied to me (in OnItemLongClickListener):
AdapterView<?> adapterView, View view, int position, long id
How do I get to the database record from all these parameters? I could use TextView.getText() and apply some string manipulation methods to the result (remember I added strings to the data before setting it in ListView), but I feel like there's another, more clever way.
You might use a List<Integer> days = new Arraylist<>(); to keep days you are modifying and so the index of the list alway will be same as position and you can get your day content by days.get(position) and get item from your database.
you should define your list out of bindView

Unable to delete pages when using FragmentStatePagerAdapter - What is the usual behavior of row ID's when integer primary key is used?

Please feel free to skip to the question as this background understanding may not be necessary for you.
I am new to android and sqlite and I am designing an app which has a content provider to access an sqlite database with multiple tables. There are several activities which use different adapters to display info from the database to the UI (i.e. cursor adapters, fragment state page adapter and array adapters). I have been having issues with the delete function in all of my activities which don't use the cursor adapter. When I try to update or delete a row from a table it deletes the wrong row or it doesn't delete anything at all. I believe it is a problem with the adapter where I am trying to figure out which row it is to send the correct info to the content provider.
The identical java code works perfectly with the cursor adapter and the rows delete normally and the other CRUD operations work. The insert and query functions work normally for all tables.The provider code uses a switch statement for each table but it is basically identical for each Uri case. All of the tables have _id as the integer primary key which is NOT set to auto increment. Since I don't fully understand how the row id works my java code does not reflect it and I keep having these issues. Although I have read many documents about content providers, adapters, sqlite databases, etc. certain key details are not clear to me.
My question is how does the row id get assigned numbers in the database when it is set to _id column as a primary key and what happens to those numbers when the database is changed?
For example, say I have an empty database. Initially after inserting the first row, the Uri will return a path segment for the 0 row and the adapter position would be 0... what would the row id for the database be (0 or 1) ?
Then for each row I insert, I know that row number would increase by one integer. Say I insert 4 rows - 0,1,2,3. Now when I am ready to delete - should the last path segment on the Uri be one integer less than the row number (i.e do I send a Uri with a last path segment of 2 to delete row 3)? Finally, after deleting, will the row ids then automatically get re-assigned so that row 4 now becomes row 3 ? Is there some code that I need to write to make that happen in the database? The primary keys are not set to auto increment.
I have different adapters and activities to where I can not access the actual database row ID once the data is displayed in the UI, so I am using the adapter position as a surrogate. This is why I am having trouble with update and delete.
Thank you very much if you read this entire question and take the time to answer it, it would help me tremendously.
I have an activity that is tabbed and uses FragmentStatePagerAdapter that is populated by a database. Here is the Adapter that I adjusted to keep track of the rows:
**EDITED:**
public class TankSectionsPagerAdapter extends FragmentStatePagerAdapter {
private ArrayList<Fragment> tankFragments = new ArrayList<>();
private ArrayList<String> tankTitles = new ArrayList<>();
//I added this ArrayList below to store the tankIDs to match the Fragments//
**public ArrayList<Integer> tankIDs = new ArrayList<>();**
public TankSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return tankFragments.get(position);
}
#Override
public int getCount() {
return tankFragments.size();
}
#Override
public String getPageTitle(int position) {
return tankTitles.get(position);
}
public void addPage(Fragment fragment, String tankName) {
tankFragments.add(fragment);
tankTitles.add(tankName);
// I added this below so the ID position would match each fragment position //
**tankIDs.add(tankId);**
notifyDataSetChanged();
}
// Finally I added this method below to the adapter//
** public ArrayList<Integer> getPageId(){
return tankIDs;
}**
Here is the activity where the method is called and where it pulls the data from the cursor to pass to the Adapter. There is a loop where each row creates a page(tab) in the ViewPager:
public class MyClass extends Tank implements TabLayout.OnTabSelectedListener, LoaderManager.LoaderCallbacks<Cursor> {
public TankSectionsPagerAdapter tankSectionsPagerAdapter;
TabLayout tabLayout;
private ViewPager mViewPager;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_class);
mViewPager = (ViewPager) findViewById(R.id.container);
addPages(mViewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.addOnTabSelectedListener(this);
}
public void addPages(ViewPager mViewPager) {
tankSectionsPagerAdapter = new TankSectionsPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(tankSectionsPagerAdapter)
try {
...
Cursor cursor = getContentResolver().query(MyProvider.CONTENT_URI_TABLE_TANK_SETUP, MyDatabaseHelper.ALL_TABLE_TANK_SETUP_COLUMNS, tankDataFilter, null, null);
if (cursor.moveToFirst()) {
do {
tName = cursor.getString(cursor.getColumnIndex(MyDatabaseHelper.TANK_NAME)); ...
// all the variables are stored in the bundle passed to the fragment/
...
**tankSectionsPagerAdapter.addPage(MainTankFragment.newInstance(tankBundle),tName, int tankID);**
tankDataFilter = tankDataFilter + (-1);
}
while (cursor.moveToNext());
cursor.close();
} else {
Toast...
}
} catch (Exception e) {
Toast..
}
}
...
// Get Row ID from cursor(tankID), parameter in addPage() above//
//Get ID's from Adapter //
** ArrayList <Integer> pageID= tankSectionsPagerAdapter.getPageId();**
This is the Activity with Spinner to choose the rows/fragments to edit or delete.
public class EditTank extends Tank implements LoaderManager.LoaderCallbacks<Cursor>
...
// Get the ArrayList//
ArrayList<Integer> IDtags =getIDIntent.getIntegerArrayListExtra("tank_edit_key");
loadEditTankSpinnerData();
////***Here is the Spinner. Use row ID from the ArrayList******
Note: Don't use the id of the spinner
editTankSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view int position, long id) {
*** tankID = IDtags.get(position); ***
}
private void loadEditTankSpinnerData() {
List<String> tankNames = new ArrayList<String>();
Cursor cursor = getContentResolver().query(MyProvider.CONTENT_URI_TABLE_TANK_SETUP, MyDatabaseHelper.TANK_NAMES, null, null,null);
try{
if (cursor.moveToFirst()) {
do {
tankNames.add(cursor.getString(1));
} while (cursor.moveToNext());
cursor.close();
} else {
deleteTankBtn.setEnabled(false);
editTankBtn.setEnabled(false);
Toast...
}
} catch (Exception e) {
Toast...
}
...
}
The above code worked well with CursorAdapter but not with the fragmentStatePagerAdapter (***Prior to the edits it did not work, now it works well and deletes correctly).
I spent days(weeks) on this because I didn't understand why the rows weren't deleting. I hope this helps someone.
Word of advise - Try to write your question as simple as possible also the code. You shouldn't share too much code in here. People will just ignore.
You're using a CursorLoader but not using it properly. Use the LoadFinished method's cursor data.
Then you can directly pass the cursor to your FragmentPageAdapter and use it directly there.
Hope this helps.
Thanks to #pskink, #CL, and #albeee - this is what I learned from you guys and my own research.
In order to delete rows from database which is populating FragmentStatePagerAdapter or ArrayAdapter you have to be able to link the correct row with what is being displayed in the adapter. Otherwise the rows won't delete or will be inconsistent or incorrect. The CursorAdapter will automatically handle the watching for changes and selecting the ID for you. If you can use CursorAdapter or a direct onItemClickListener and get the id directly from the AdapterView with getSelectedId() or just long ID, then that is a good way to get the row ID. However, if you are getting the id indirectly by other means then you have to handle the associations...
1.You should not use the adapter position, spinner position or even spinner id to select the row. These are useful only to determine which item/fragment you want. Only the ID of the OnClickListener on the item itself will consistently give the correct row.
2.The database rows behave as such - the integer primary key will auto increment even if AUTOINCREMENT is not chosen, but the row ID's are stable once assigned. This means that each new row will have a higher ID than the last but if you delete rows in between, it will not change the IDs of the remaining rows. So the rows will skip and not be consecutive when there are edits and deletions. For this reason you must have a method to link the item to the ID permanently. There may be a better way to do this, however, I will edit the code above to show one way that I was able to do it for the FragmentStatePagerAdapter so the user can add and delete fragments dynamically.

SQLite Database Rowid sorted

I have a delete Row function as according:
public boolean removeData(int position) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COL_ID+"="+position, null);
return true;
}
This function deletes a row according to its unique ID.
How can I change this so that after deleting a row, all rows below that one will be moved up to fill the empty space in the database?
That's against the design principle of a relational database. The rows are not ordered in a predictable way. So after delete you can only be sure that the deleted record appears to be away, but you have no control on the physical locations of any record, including which record(s), if any, now cover the space of the deleted one.
Querying data is another topic. You can specify a sort order, available as a parameter with the query methods. When querying your table, the results will appear exactly as you want it: If previously your results were Adam, Eve, Jack, Michael, then after deleting Jack, the result will be Adam, Eve, Michael.
The interplay between the displayed list, the domain objects behind that list, and the database is a different topic. Here are a few code snippets I use for a similar task. The basic idea is, when reading the objects that will be displayed, to include the database id with the object. So, if I read a list of products, the the domain class Product will have an id field that gets set with the database id when reading it.
To get the domain object displayed at a specific list position (e.g. the one where a user hit a delete button), the code fragment is.
public void onClick(View view) {
Product product = (Product) ProductList.this.products.get(ProductAdapter.this.listView.getPositionForView((View) view.getParent()));
... now do whatever is necessary to delete the product, probably
calling a DAO class that deletes the object based on its id,
not the list position
ProductAdapter.this.notifyDataSetChanged();
}
Solved this by removing the row in the database by the text of the TextView in the ListView instead of removing by the position of the TextView.
Now looks like this:
//Erasebutton listener
final Button eraseButton = (Button) findViewById(R.id.eraseButton);
assert eraseButton != null;
eraseButton.setOnClickListener(new View.OnClickListener() { //erasebutton onclick
public void onClick(View eraseButton) {
SparseBooleanArray checked = questionList.getCheckedItemPositions();
for(int i = questionList.getCount() - 1; i >= 0; i--)
{
if(checked.get(i)) {
//What to do with selected listitems
TextView tv = (TextView) questionList.getChildAt(i).findViewById(R.id.checkedTextView1);
db.removeData(tv.getText().toString());
}
}
checked.clear();
Cursor newCursor = db.getData();
adapter.swapCursor(newCursor);
}
});
And removeData function now looks likte this:
public boolean removeData(String question) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COL_QUESTION+"='"+question+"'", null);
return true;
}

delete entry from sqlite data base in android application. where to get the that row id to pass it ot delete function

After going through many posts I am posting my query. Not able to get proper resolution for my problem.
I am using sqlite and inserting some data (name, info etc..)
Now I get the all rows and show in list view.
Now user selects a one list entry for deletion, I have to call db.delete with id which is rowid of that particular record.
How will get the record id?
When user selects from list view I have position number which is index to the list. But not the database row id where that entry resides.
Do i have to save all ids returned when I call db.insert(table, data) when rows are created?
all examples show the implementation like
public void deleteRow(long id) {
db.delete(TABLE_NAME,KEY_ID + " = ?",
new String[] { String.valueOf(id) });
}
where should i get id from?
For setup a list view you have create an Adapter, right?
The adapter hold your entries and create the views.
Ask your adapter which item is on position x.
The BaseAdapter implement a getItemId method.
public long getItemId(int position) {
// Example for List<Object>
return mItems.get(position).getId();
}
You can simple call adapter.getItemId(x); or use OnItemClickListener that give the ID.
For more informations loot at the android developer pages.
SimpleAdapter:
http://developer.android.com/reference/android/widget/SimpleAdapter.html
ArrayAdapter:
http://developer.android.com/reference/android/widget/ArrayAdapter.html
BaseAdapter:
http://developer.android.com/reference/android/widget/BaseAdapter.html
I hope it helps.
Updated:
Use getItemId(int) instead of getItem(int), thanks to #pskink

Some help understanding columnIndex in ViewBInder

Skip to the bottom if you just want to see the question without context
The android app I'm building has a simple table with three columns:
_id INTEGER PRIMARY KEY..., name TEXT, color INT
This table is called categories. I load my categories from the database and feed them into a SimpleCursorAdapter for use with a Spinner like so:
String[] from = new String[] {
ListDbAdapter.KEY_CATEGORY_NAME,
ListDbAdapter.KEY_CATEGORY_COLOR };
int[] to = new int[] { R.id.categorySpinnerItem };
mCategorySpinnerAdapter = new SimpleCursorAdapter(this,
R.layout.category_spinner_item, categoryCursor, from, to);
mCategorySpinnerAdapter
.setViewBinder(new CategorySpinnerViewBinder());
mCategorySpinner.setAdapter(mCategorySpinnerAdapter);
I set a custom ViewBinder because I want the category name to be the text of the spinner item, and the color to be the background color. My ViewBinder looks like this:
private static final int NAME_COLUMN = 1;
private static final int COLOR_COLUMN = 2;
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
TextView textView = (TextView) view;
String name = cursor.getString(NAME_COLUMN);
int color = cursor.getInt(COLOR_COLUMN);
textView.setText(name);
textView.setBackgroundColor(color);
return true;
}
Here is my question (finally)
In the setViewValue method, what is columnIndex supposed to be doing? The documentation says "the column at which the data can be found in the cursor" but when I debug through setViewValue I hit it three times and columnIndex is always 1.
I was expecting the debugger to get into setViewValue once for each entry in the from array, with a columnIndex first of 1 and then 2. Or maybe once for each column in the query results.
The above code works, I can get the desired functionality but only because of my NAME_COLUMN and COLOR_COLUMN constants. I'd be really interested to hear an explanation of setViewValue and its parameters from someone more experienced with custom ViewBinders.
In the source of SimpleCursorAdapter, the setViewValue is called in bindView :
bound = binder.setViewValue(v, cursor, from[i]);
where the third param from[i], which is the interesting one, is an iteration over an int[], which represents the column indexes used. However the index for [i] for the iteration itself comes from the int[] to which is passed to the constructor of the adapter, and in your case, it has only 1 item - R.id.categorySpinnerItem
EDIT: In two words, the String[] and the int[] should be equivalent, same size and in same order - for each column name you need an int R.id... first view id will be connected to the first column id with from[0], second with from[1] and so on, and if you pass 10 columns, but you have only 3 R.id-s, you will get only to from[2] :)
I think that you are confused because you missed the part with the return value - true if you bind the data, false otherwise (and the adapter attempts to handle the binding on its own). I think that the idea is like with the OnTouchEvent- giving you the option to consume it or not. So, you are always returning true at index 1, and you are never offered the index 2, because you have binded the view already, that's the only explanation I can think of about having always only 1 in the columnIndex param.
However, I almost haven't used cursor adapters - I find them not-OO, it is way better to create a POJO somewhere else, initializing it however you want using the db columns, and when you have a shaped list of objects just sending them to a "normal" adapter, it sounds more MVC. For example, if at some point you decide that KEY_CATEGORY_NAME will be in the format "cat_name##cat_description" (for example) you have to change the Adapter. Sounds more reasonable to change your class Category, so the getName() will return just "cat_name", and the adapter is the same.
So, because I almost haven't used CursorAdapters , if I am right about the columnIndex, please DO tell me about it, because I am curious but I don't want to create a CursorAdapter and check it myself :)

Categories

Resources