Using strikethrough in ListView using ArrayAdapter - android

I have added elements in ListView through database using array adapter. Here I want the element to have a strikethrough. How can I do this?
Here is the code I am using:
String q4 = "select * from todolist;";
Cursor d = database.rawQuery(q4, null);
if(d != null && d.moveToFirst()) {
do {
String element =d.getString(d.getColumnIndex("elist"));
al.add(element);
ArrayAdapter ad = new ArrayAdapter(getContext(),android.R.layout.simple_list_item_1,al);
list.setAdapter(ad);
} while (d.moveToNext());
}

For anyone looking for an answer, Array Adapter cannot alter the view of its contents. Using Base adapter is the best option.

Related

How to position (select) a spinner on specific item by id with simplecursoradapter?

I'm populating a spinner with a number of records from my SQlite database using the following code:
DBHelper db = new DBHelper(getBaseContext());
Cursor cursor_clients = db.select("clients", "_id, name", "ORDER BY name"); // table, fields, filter/order
String[] columns = new String[] { "name" };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor_clients, columns, to, 0);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spnClients = (Spinner) findViewById(R.id.spnClients);
spnClients.setAdapter(mAdapter);
It works great, and I can use
spnAcademias.getSelectedItemId();
To get the _id of the selected record. My problem is: How to select an item on this spinner by the _id?
I have the _id of the row I want, I want it to show this row selected, and not the first row coming from the query.
Doing more research I ended up with the solution here: setSelection on Spinner based on rowId
I thought maybe there was a native solution without a loop, but there is not.
Solution:
public void setSpinnerItemById(Spinner spinner, int _id)
{
int spinnerCount = spinner.getCount();
for (int i = 0; i < spinnerCount; i++)
{
Cursor value = (Cursor) spinner.getItemAtPosition(i);
long id = value.getLong(value.getColumnIndex("_id"));
if (id == _id)
{
spinner.setSelection(i);
break;
}
}
}
If you're able to just as easily get the text value of the row you are looking for, then try the solution here, and more specifically the top comment on it: Set selected item of spinner programmatically
Use the following: spinnerObject.setSelection(INDEX_OF_CATEGORY2).
...
... I also found a way of getting the index without needing to loop through the adapter. I used the following mySpinner.setSelection(arrayAdapter.getPosition("Category 2"));

How refresh listview after search

i have a listview with data from database using an sqlite.
when first time (onCreate()) i show the data, there`s no problems, the data all shown.
the problem is, when i want to filter my list view using datepicker and button, the listview not change the data.
ive use listview.invalidateViews(), notifyDataSetChanged()... but still not solved yet. maybe theres some mistake with my code... hope you guys can give me some solution.
thx...
here`s my code
Getting Data From DataBase
public ArrayList<BonRokokModel> getBonRokokList(String userGUID, String transDate, String searchText){
dbPath = "/data/data/app.chameleon.mobile/databases/";
dbName = "SalesTrans.sqlite";
bonRokok = SQLiteDatabase.openDatabase(dbPath + dbName, null,SQLiteDatabase.OPEN_READWRITE);
String strQuery;
strQuery = "SELECT BonRokokID, TransDate, Gudang, Status FROM tblSATBonRokok WHERE UserGUID = ? AND TransDate = ?";
// if(!searchText.equals("")){
// strQuery += "AND (BonRokokID LIKE %'"+ searchText +"'% ) ORDER BY TransDate DESC, BonRokokID Desc";
// }
ArrayList<BonRokokModel> listRokok = new ArrayList<BonRokokModel>();
Cursor mCursor = bonRokok.rawQuery(strQuery, new String[]{userGUID, transDate});
if(mCursor.moveToFirst()){
do {
BonRokokModel dataRokok = new BonRokokModel();
dataRokok.setBonRokokID(mCursor.getString(mCursor.getColumnIndex("BonRokokID")));
dataRokok.setTransDate(mCursor.getString(mCursor.getColumnIndex("TransDate")));
dataRokok.setGudang(mCursor.getString(mCursor.getColumnIndex("Gudang")));
dataRokok.setStatus(mCursor.getString(mCursor.getColumnIndex("Status")));
listRokok.add(dataRokok);
} while (mCursor.moveToNext());
}
bonRokok.close();
return listRokok;
}
My Code to Get Data
public void settingTabItem() {
listView = (ListView) findViewById(R.id.bonRokokMain_lvMain);
listviewMain = new ArrayList<BonRokokModel>();
listviewMain = bonRokokDAO.getBonRokokList(Main_Login.userGUID,utilities.convertDateToDateDBString(edt1.getText().toString()),"");
BonRokokListAdapter adapter = new BonRokokListAdapter(this, listviewMain);
listView.setAdapter(adapter);
}
thank you
Try like this ..
ListArrayAdapter.clear(); // Clear your adapter
ListArrayAdapter.addAll(newItems); // Add new items to it
ListArrayAdapter.notifyDataSetChanged(); // Notify List view for new items in list
OR
You can update list view like this also ..
Firstly clear your list view ..
Then after fetching new data .... create complete list view again.
Use the logical of method settingTabItem() on refresh method. Don't forget to clear the listview. Sorry for the bad English.

getCheckedItemCount() returns wrong value after cursor change

What I'm trying to do is to put ListView in my app which uses internal SQLite database to get data. When user clicks new data is fetched from DB by executing new query.
I've implemented custom view for ListView item which extends LinearLayout and implements Checkable interface. Works.
Got custom adapter based on CursorAdapter. In OnCreate() I'm setting my adapter for ListView with empty cursor.
ListView markersList = (ListView) findViewById(R.id.markersList);
Cursor c = null;
MarkersListAdapter adapter = new MarkersListAdapter(this, c, 0);
markersList.setAdapter(adapter);
Next in AsyncTask I'm querying database in doInBackground() which passes new cursor to onPostExecute() to update ListView. I'm doing this with:
adapter.changeCursor(newCursor);
Then I'm by default checking all items (user just uncheck unwanted items)
for(int i = 0; i < this.markersList.getCount(); i++)
{
this.markersList.setItemChecked(i, true);
}
So far so good. But when I do
int s = this.markersList.getCheckedItemCount();
I'm getting wrong value. I guess it's associated with old cursor. This only happens when rows count in new cursor is smaller than rows count in new cursor.
Generally, I'm getting something like this
int s = this.markersList.getCheckedItemCount(); // s = 7
int d = this.markersList.getCount(); // d = 5
Is there a solution to this?
The easiest solution is to clear the checked count manually:
this.markersList.clearChoices();
for(int i = 0; i < this.markersList.getCount(); i++)
{
this.markersList.setItemChecked(i, true);
}

Sorting the contents of ArrayAdapter or ArrayList

I am working on android project and am making using of a ListView that retrieves data from the SQLite database.
I am making a dataset using an ArrayList and then adding this ArrayList into an ArrayAdapter.
When the data is being retrieved from the database, I am telling SQLite to do the sorting so everything is in alphabetical order when it is added into the ListView. At certain times, the information will be added dynamically to to the ListView without it requiring to re-fetch everythin from the database again. However, I want to keep everything in alphabetical order.
How would I do this, do I sort the DataSet and then call the notifyDataSet Changes or do I do the sort directly on the ArrayAdapter. I've looked into performing the sort on the ArrayAdapter but this wants an argument that uses a Comparator but not sure what this is and can't find any working examples that may be of any help for what I want to achieve.
Below is the code that populates the array and sets the list adapter
ArrayList<Spanned> passwords = managePasswordList.getPasswordList();
if (passwords != null && passwords.size() > 0)
{
passwordArrayAdapter = new ArrayAdapter<Spanned>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_activated_1, passwords);
setListAdapter(passwordArrayAdapter);
myListView.setTextFilterEnabled(true);
txtNoRecords.setVisibility(View.GONE);
}
else
{
txtNoRecords.setVisibility(View.VISIBLE);
}
I am then adding data to the dataset and refreshing the list view using the following
String company = Encryption.decrypt(passwords.get(i).company);
String username = Encryption.decrypt(passwords.get(i).username);
details = Html.fromHtml(company + "<br />" + "<small><font color=\"#767676\">" + username + "</b></small>");
passwords.add(details);
passwordArrayAdapter.notifyDataSetChanged();
Thanks for any help you can provide.
UPDATE 1
I've tried doing what Nick Bradbury suggested but I am having a problem with the comparator. I have the following code but I don't know where to go from here.
SQLiteDatabase myDb = null;
Cursor cursor = null;
ArrayList<Spanned> passwords = new ArrayList<Spanned>();
try
{
myDb = context.openOrCreateDatabase("PasswordManager", Context.MODE_PRIVATE, null);
cursor = myDb.rawQuery("SELECT * FROM password ASC", null);
while (cursor.moveToNext())
{
final String company = Encryption.decrypt(cursor.getString(2));
final String username = Encryption.decrypt(cursor.getString(4));
Spanned details = Html.fromHtml(company + "<br />" + "<small><font color=\"#767676\">" + username + "</b></small>");
passwords.add(details);
Collections.sort(passwords, new Comparator<Spanned>() {
public int compare(Spanned lhs, Spanned rhs) {
return 0;
}
});
}
}
catch (SQLiteException ex)
{
common.showBasicAlertDialog("Unfortunately something has gone wrong.\n\nWe will fix this as soon as we can", false);
Log.e("Database Error", ex.toString());
return null;
}
In the return statement I have no idea what to do, I've tried return lhs.compareTo but the lhs and rhs variables don't have the compareTo function so I have not got a clue what to do.
Here's a simple example of sorting an ArrayList using Comparator. In this example, the ArrayList is defined as:
public class StatusList extends ArrayList<Status>
A sort routine for this ArrayList could look like this:
public void sort() {
Collections.sort(this, new Comparator<Status>() {
#Override
public int compare(Status item1, Status item2) {
return item2.getDate().compareTo(item1.getDate());
}
});
}
Replace <Status> with whatever object your ArrayList contains, then change the comparison to compare the values of the object you wish to sort by.

How to Retrive proper data on Spinner from SimpleCursorAdpter in Android

hay i used the SimpleCursorAdapter from implement the data on the spinner.its going well. also to get data i used following code:
Cursor cursor = (Cursor) (spncomapnayname.getSelectedItem());
if (cursor != null) {
companyselected = cc.getString(cc.getColumnIndex(db.COMPANY_NAME));
}
it is working well.but it is for the getting data from the spinner.but now i want to set particular data on spinner which was inserted by the user for update for normal ArrayAdapter spinner we used:
spinnername.setSelection(adapter1.getPosition(abc));
so i want to know how to set data from the database on spinner.
here is my code:
cursor = db.getProductName();
adapter1 = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] { DB_Database.PRODUCT_NAME }, new int[] { android.R.id.text1 });
adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spnproduct.setAdapter(adapter1);
purchaseproduct = purchasebundle.getString("clickedpurchaseproductname");
if(!purchaseproduct.equals("null")|| !purchaseproduct.equals("")) {
System.out.println("purchaseproduct" + purchaseproduct);
String mypurchaseproduct=purchaseproduct;
ArrayAdapter myAdap = (ArrayAdapter) spnproduct.getAdapter();
int spinnerPosition = myAdap.getPosition(mypurchaseproduct); // set the default according to value
spnproduct.setSelection(spinnerPosition);
}
here i get data from bundle.i want to retrive data on Spinner.the data is populated from SimpleCursorAdapter
First Get Selected Value From Cursor and store into mString Variable and then use below code for display this selected value into Spinner.
if (!mString.equals("null") || !mString.equals("")) {
String myString = mString; // the value you want the position for
ArrayAdapter<String> myAdap = (ArrayAdapter<String>) mSpn1.getAdapter(); // cast to an ArrayAdapter
int spinnerPosition = myAdap.getPosition(myString);
// set the default according to value
mSpn1.setSelection(spinnerPosition);
}
You can do something like this:
Cursor c = (Cursor)parent.getItemAtPosition(pos);
int id = c.getInt(c.getColumnIndexOrThrow("columm_name"));
or to get a String
String name=c.getString(c.getColumnIndexOrThrow("columm_name"));

Categories

Resources