I have a program that retrieves data from a database and displays it in a list adapter, But i want to sort the data by the planned date in Ascending order. Can anyone help
ArrayList<HashMap<String, String>> TimesheetList = controller.getAllworkinstructions();
if(TimesheetList.size()!=0) {
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Id = (TextView) view.findViewById(R.id.Id);
String valId = Id.getText().toString();
Intent objIndent = new Intent(getApplicationContext(),ViewCuttingtask.class);
objIndent.putExtra("Id", valId);
startActivity(objIndent);
}
});
SimpleAdapter adapter = new SimpleAdapter(Menu.this,TimesheetList, R.layout.list,
new String[] { "Id","weekcomm","jobid","taskid","planneddate","name","Priority"},
new int{R.id.Id,R.id.weekcomm,R.id.jobid,R.id.taskid,R.id.planneddate,R.id.name,R.id.priority});
setListAdapter(adapter);
}
This has nothing to do with adapters.
You should sort your collection depending on your needs then pass it to your adapter (or notify it if you already passed it to a ListView, for instance).
By sort, I mean:
database query time sorting
using Collection.sort(yourCollection, aComparator)
I assume one of these Strings refers to date ArrayList<HashMap<String, String>> TimesheetList Just sort TimesheetList by date and give sorted list to array adapter
Related
Scenario : I have 2 spinners with one adapter and global array. When any one select an item from one spinner then that item will delete from global array.Problem is when an item suppose select with 0 index again after deleting that item from global array and another item at acquire position with 0 index . If I will select that 0 index changed item then it will not select other than all items will select.
So can any one explain or suggest what i want to do in this scenario.
List<String> spinnerArray = new ArrayList<String>();
HashMap<String, String> index_val = new HashMap<String, String>();
ArrayAdapter<String> adapter_left;
spinnerArray.add("None");
spinnerArray.add("Task");
spinnerArray.add("Priority");
spinnerArray.add("Deadline");
spinnerArray.add("Assigned to");
spinnerArray.add("Created by");
spinnerArray.add("Closed by");
spinnerArray.add("Category");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, R.layout.spinner_selected_item, noneArray);
adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
adapter_left = new ArrayAdapter<String>(activity, R.layout.spinner_selected_item_left, spinnerArray);
adapter_left.setDropDownViewResource(R.layout.spinner_dropdown_item);
task_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(!index_val.get("1").equalsIgnoreCase("None")){
spinnerArray.add(index_val.get("1"));
}
current_selected_val = adapterView.getItemAtPosition(i).toString();
index_val.put("1", current_selected_val);
if(!current_selected_val.equalsIgnoreCase("none")) {
spinnerArray.remove(spinnerArray.indexOf(current_selected_val));
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Your Array Adapter should be notify every time, when ever you modify an array list like adding, deleting or updating.
So notify your adapter.
I hope this might help you.
It's not possible, because spinner maintains their items on behalf of index instead of actual items.
Using the following code, when an item from the list is selected it updates a data table. The problem is when there are several items listed, regardless of which one is selected, it always updates the first listed item showing rather than the one selected. Thanks in advance!
Edited-Updated. Incorporated (position) and tried to simplify a bit of the code. Still will not capture the selected item, always returns the top item showing on the listview, regardless. The DB controller is working fine, all else is good except this...
setContentView(R.layout.list_messages);
ArrayList<HashMap<String, String>> phraseList = controller
.getUnreadMessage();
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(
ReadUnReadMessages.this,
phraseList,
R.layout.view_list_messages,
new String[] { "mFromName", "mToAddress", "mBody",
"mToName", "messageTime", "mFromAddress", "mRead",
"messageId" },
new int[] { R.id.messageFrom, R.id.messageToAdd,
R.id.messageBody, R.id.messageTo, R.id.messageTime,
R.id.messageFromAdd, R.id.readCode, R.id.messageId });
setListAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long arg) {
#SuppressWarnings("unchecked")
HashMap<String, String> queryValues = (HashMap<String, String>)parent.getItemAtPosition(position);
messageBody = (TextView) findViewById(R.id.messageBody);
readCode = (TextView) findViewById(R.id.readCode);
messageId = (TextView) findViewById(R.id.messageId);
String readCode = "1";
queryValues
.put("messageId", messageId.getText().toString());
queryValues.put("mRead", readCode);
queryValues.put("mBody", messageBody.getText().toString());
controller.markMessage(queryValues);
this.callSplash(view);
}
public void callSplash(View view) {
Intent objSplash = new Intent(getApplicationContext(),
Splash.class);
startActivity(objSplash);
}
});
It's hard to tell exactly how you were expecting it to work, but it seems like your central problem is that you are ignoring the 'position' parameter to onItemClick. This is Android's way of telling you which item was clicked. Somehow you need to pass that parameter, or else the corresponding item object that you fetch first from the adapter, on to the functions you call from onItemClick:
this.insertData(position);
Otherwise those functions would have to guess which item was clicked. And apparently that is what they are doing: they are assuming the first item was clicked.
I have a Spinner which is filled from a query using a SimpleCursorAdapter, this works fine... but now I need to put an option "Please Select" before all the items retrieved from the query, just for usability issues... but I'm not quite sure of how to do so... HELP please...
Here is my code...
private Spinner comboForm;
...
comboForm = (Spinner) findViewById(R.id.comboFormularios);
...
mDbH.abrir();
final Cursor cu = mDbH.consultaFormularios(idU);
if(cu.moveToFirst() == false){
cu.close();
mDbH.cerrar();
}else{
SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(getApplicationContext(),R.layout.spinner,cu,new String[] {"nombre"},new int[] {R.id.textoCombo});
adapter2.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
comboForm.setAdapter(adapter2);
}
mDbH.cerrar();
...
comboForm.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parentView, View selectedItemView,int position, long id) {
idF = (int) id;
obtenerDatosRutas(idU,idF);
tabla.removeAllViews();
llenarTabla();
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
Where mDbH is an instance of the class I'm using to manipulate the Database... as you can see the Spinner is filled up from Cursor resulting of the query consultaFormularios(idU)
When you create your cursor, one possible solution would be to use a SQL UNION and construct second SELECT that simply contains the label you need (adding hard-coded dummy fields for ordering).
Alternatively, and this is most likely the simplest solution. Instead of using a cursor adapter, use an array adapter and start by populating the array with your default value you want, then stick in all the items from your cursor. Something like,
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("Please select");
final Cursor cu = mDbH.consultaFormularios(idU);
while(cu.moveToNext()) {
arrayList.add(cu.getString(0)); // assuming you want a
//string from the first column
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, arrayList);
comboForm.setAdapter(spinnerArrayAdapter);
I have a spinner which is populated with Category objects that are retrieved from the db. The Categories table has _id and category_name columns. I want to show the category name in the spinner, but when the user selects an item, I need it to retrieve the selected item's ID. I tried the following:
Declaring variables (in class level):
int currCategoryId;
ArrayAdapter<String> adapter;
NotesManager manager = new NotesManager(this);
ArrayList<Category> arrListCategories;
ArrayList<String> arrListCategoriesString = new ArrayList<String>();
Spinner spCategories;
Instantiating them in onCreate method:
manager.getAllCategories();
arrListCategories = manager.getAllCategories();
for (int i = 0; i < arrListCategories.size(); i++)
{
Category currCategory = arrListCategories.get(i);
arrListCategoriesString.add(currCategory.getCategory_name().toString());
}
adapter=new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, arrListCategoriesString);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCategories.setAdapter(adapter);
spCategories.setOnItemSelectedListener(spinnerListener);
And this is the spinnerListener I tried:
OnItemSelectedListener spinnerListener = new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected.
//currCategory = (String) parent.getItemAtPosition(pos).toString();
//selectedCategory =
Category selectedCategory = (Category)spCategories.getItemAtPosition(pos);
currCategoryId = selectedCategory.getId();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
};
But in this case the app crashes and I'm getting a "
String cannot be cast to Category" at this line: Category
selectedCategory = (Category)spCategories.getItemAtPosition(pos);
I also tried this:
currCategoryId = view.getId();
But then instead of 1 or 2 (depending on what category I selected, currently I have 2 of them), I'm getting a very long number...
How can I fix it? How can I retrieve the ID of the selected object?
I would use a SimpleCursorAdapter because it stores multiple columns, instead of an ArrayAdapter that only stores one.
First change NotesManager.getAllCategories() to return a Cursor that uses:
"SELECT _id, category_name FROM Table;"
You could alphabetize the results if you want:
"SELECT _id, category_name FROM Table ORDER BY category_name;"
Next bind this Cursor straight to your Spinner:
Cursor cursor = manager.getAllCategories();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] {"category_name"}, new int[] {android.R.id.text1});
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCategories.setAdapter(adapter);
Finally in your OnItemSelectedListener everything is ready and waiting:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// The parameter id already refers to your Category table's id column,
}
No extra get() calls or converting Cursors into Lists necessary!
You can't use the ArrayAdapter anyway because it's for Strings only (not Categories). Hence why you're getting a casting exception. Since you have your Category ArrayList and your String ArrayList (which is used for the ArrayAdapter) in the same order, just use
Category selectedCategory = arrListCategories.get(pos);
in your onItemSelected() method
I'm new to android. What i'm trying to do is to populate a listview from my sqlite database.I know how to do it using arrays. Can somebody help me doing this? I know there is a away to adapt the following code and using it for populating the listview using SQLite but i don't know how to do it.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
final ListView lt = (ListView)findViewById(R.id.ListView01);
List<String> w= new ArrayList<String>();
ArrayAdapter<String> aa;
w.add("waka");
w.add("weka");
w.add("woka");
aa = new ArrayAdapter<String>(this, R.layout.listW, w);
lt.setAdapter(aa);
lt.setTextFilterEnabled(true);
lt.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
final String aux= (String) lt.getItemAtPosition(position);
Intent myIntent = new Intent(infoList.this, tabList.class);
startActivity(myIntent);
}});
}
Thanks
The best way to poputaling a ListView with data is using Content Providers: http://developer.android.com/guide/topics/providers/content-providers.html
Using content providers will you safe headaches regarding open/close operation for the database.
You can use SimpleCursorAdapter.
Image you have a list view (named 'list_item') item with two fields having ids txtOne and txtTwo respectively. Also, you are having a database table with tow fields - field1 and field2.
When you sgolud use the following adapter call.
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
ctx,
R.layout.list_item,
getContentResolver().query(....), // getting cursor for database query here.
new String[] { "field1", "field2" },
new int[] { R.id.txtOne, R.id.txtTwo }
);
This adapter will map a text from field1 to txtOne and from field2 to txtTwo.