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.
Related
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.
I have a ListView with some items, but after I update a Database I'd like to "refresh" the ListView. Anyone can help me?
EDIT: populateListView add items to ListView
public void populateListView()
{
String URL = config.getUrl_For_Query() + ",&nameq=Select&tipo=select"; // my URL
String jsonString = reading.execute_query(URL); // jsonString is formatted well
try
{
JSONObject jsonResponse = new JSONObject(jsonString);
JSONArray array = jsonResponse.getJSONArray("elenco");
for (int i=0; i<array.length(); i++) // I scan all array
{
JSONObject nameObj = (JSONObject)array.get(i);
// I retrieve all information
allNames.add(nameObj.getString("name")); // Name
allLng.add(nameObj.getString("lng")); // Another information
}
}
catch (Exception e)
{ e.printStackTrace(); }
List<String> Array = new ArrayList<String>();
for(int i=0;i<allNames.size();i++) // I add all values
{
String value = allNames.get(i).toString() + ", \n\t" + allLng.get(i).toString();
Array.add(value); // here I populate my Array
}
final ListView listView = (ListView) getActivity().findViewById(R.id.List);
listView.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Array));
//
// Click
//
}
saveChanges
public void saveChanges()
{
// I update a Database
// And then I'd like to refresh ListView's items
populateListView(); // Update ListView
}
Use a Comparator. There you define what to compare and how, in the compare() method you define what should be returned from two of your instances. Here's an example for a String Comparator.
Comparator myComparator = new Comparator<String>() {
public int compare(final String user1, final String user2) {
// This would return the ASCII representation of the first character of each string
return (int) user2.charAt(0) - (int) user1.charAt(0);
};
};
adapter.sort(myComparator);
This way, when you add an item, you don't have to recreate the whole Adapter but it will be sorted instead. But don't forget to call .notifyDataSetChanged() on your adapter, this will make (amongs other things) to refresh your layout.
Try using ArrayAdapter.insert method to insert objects in specific index.
At first take a look at this tutorial about SQlite database in Android.
So, your problem is that new items are added at the end of the list. Huh? This is because you have not notified Adapter from the changes of the Array.
ArrayAdapter<String> Adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Array);
Your first solution is to clear Adapter before updating Database. Sth like:
Adapter.clear(); can do that. This way your Adapter is empty before updating database and new items are inserted. You can use Adapter.notifyDataSetChanched(); for awaring Adapter about the changes.
In above tutorial there is a custom Adapter. It uses this code:
List<String> Array = new ArrayList<String>();
Array = (ArrayList<String>) db.getAllContacts();
Adapter = new MyCustomAdapter(getActivity() [in fragment case or getApplicationContext() in Activity case], R.layout.simple_list_item_1, Array);
This way there is no need for clearing Adapter because it automatically does that. Wherever you use this method, updated adapter is used for showing the list.
I am trying to get saved values in a list. I am creating anotepad and I want when anybody open notepad every saved list display on homepage in a list.
I have successfully saved the value in a database but when I am trying to get a value in a list it is giving full string value like this "com.todo.task.activity#4106a690" in every single row.
I think problem is in my database getlist() method please check:
public List<TaskDetailsActivity> GetAddTaskLists() {
List<TaskDetailsActivity> TaskLists = new ArrayList<TaskDetailsActivity>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TASKLISTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
TaskDetailsActivity tasks = new TaskDetailsActivity();
tasks.settaskLists_ID(cursor.getString(0));
tasks.settasklists_Title(cursor.getString(1));
// Adding Doc to list
TaskLists.add(tasks);
} while (cursor.moveToNext());
}
// return Doc list
return TaskLists;
}
Here I am calling database method like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView list_tasklistname = (ListView)findViewById(R.id.list_tasklistname);
TaskManager_Database db = new TaskManager_Database(getApplicationContext());
list = db.GetAddTaskLists();
ArrayAdapter<TaskDetailsActivity> adapter = new ArrayAdapter<TaskDetailsActivity>(getApplicationContext(),
android.R.layout.simple_list_item_1, list);
list_tasklistname.setAdapter(adapter);
adapter.notifyDataSetChanged();
Please let me know what is the error. Thanks
You are getting object representation of objects been added to ListView...
In your case you should return data in cursor.getString(1) for adapter input param i.e. String array...... i.e list must be a string array or ArrayList... if you know what I mean..
check out this sample for ref
Your TaskDetailsActivity class should define a toString() method that returns whatever you want to display for that row.
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);
}
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.