I am having an issue with a listview refresh, I have a refresh function that works on load and when I click a button tied to it. What it will not do is refresh after I add info to the SQLite database and call the refresh function.
//Add item to order Table.
public void addItemToOrder()
{
itemNumberValue = qoItemNumber.getText().toString();
orderQtyValue = qoOrderQty.getText().toString();
itemDescValue = qoItemDesc.getText().toString();
Intent searchItem = new Intent(getApplicationContext(),inputOrder.class);
searchItem.putExtra("itemnumb", itemNumberValue);
searchItem.putExtra("orderqty", orderQtyValue);
searchItem.putExtra("qoitemdesc", itemDescValue);
startActivity(searchItem);
fillData();
}
//Load item table to listview
public void fillData() {
// Get all of the rows from the database and create the item list
mNotesCursor = mDbHelper.fetchAllOrders();
startManagingCursor(mNotesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{HDWDBHelper.KEY_ITEMNUM, HDWDBHelper.KEY_DESC, HDWDBHelper.KEY_QTY};
// and an array of the fields we want to bind those fields to (in this case just text1)
//int[] to = new int[]{R.id.text1};
int[] to = new int[]{R.id.tvItemNum, R.id.tvItemDesc, R.id.tvQty};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.itemlist, mNotesCursor, from, to);
notes.notifyDataSetChanged();
setListAdapter(notes);
notes.notifyDataSetChanged();
Log.v("fillData", "In fillData");
}
When I call fillData() at onCreate() or on button click, it works but when I call it in the addItemToOrder() function, nothing happens. The listview still shows previous items listed until I click the refresh button then it shows the new item added.
Related
I have an activity A with a listView. I've got a few items in there. If I click in one of those items, I navigate with an Intent to another page. In that other poage/Activity, I have a spinner, which contains the items of the listView ( which is populated with database). The problem is, every time, i go to that activity B, the item displayed in the spinner is always the first in my database. How can I set the item to be displayed depending on the item I clicked in the listView ?
Here's how I populate my spinner (dropdown mode) :
spinner = (Spinner)findViewById(R.id.spinner_branches);
final Cursor cursor = dbhelper.getAllCours();
String[] from = { "branche_cours" }; int[] to = { android.R.id.text1 };
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, from, to, 0);
spinner.setAdapter(adapter);
adapter.notifyDataSetChanged();
When I navigate, i pass the selected item with the intent. I remind you that my listView contains the same items of the spinner..
String selected_brancheold= intent.getExtras().getString("branche");
Thank you guys !
You can do one thing if your ListView list and Spinner List both are same.
Activity A
Intent intent = new Intent(YOUR_CONTEXT, ActivityB.class);
intent.putExtra("position",PASS_CURRENT_POSITION_LISTVIEW_ITEM_CLICKED);
startActivity(intent);
Activity B (After setting up the spinner adapter)
int currentPosition = getIntent().getIntExtra("position",0);
spinner.setSelection(currentPosition);
Hope this works for you!!
I've created a ListView and bind it to an adaptor to display data from a table. It works great. I can select on a row and it display the product name that I'm selecting. Now I've added an ImageView in the layout that will act as delete buttons on each row. My problem is I can't figure out how to add the code to make it so that when a user select the ImageView (delete button), it will delete the row. I've searched and found a lot of articles on this topic and tried a lot of them and none really work my code. Do I need to create a getView function? Also I've tried inserting the getTag(), but I couldn't make it work. Can you help me with a sample code that may work with my simple code or point me to the right direction? Here is my code:
private void displayListView() {
prodinputHelper = new DBAdaptorProductInput(this);
prodinputHelper.open();
Cursor cursor = prodinputHelper.fetchAllProductInput();
// The desired columns to be bound
String[] columns = new String[] {
DBAdaptorProductInput.KEY_PRODUCTTYPE,
DBAdaptorProductInput.KEY_PRODUCTNAME,
DBAdaptorProductInput.KEY_MANUFACTURER,
DBAdaptorProductInput.KEY_VISC40,
DBAdaptorProductInput.KEY_VISC100,
DBAdaptorProductInput.KEY_VI,
DBAdaptorProductInput.KEY_DEN15C,
DBAdaptorProductInput.KEY_VISCTEXT,
DBAdaptorProductInput.KEY_BASEOILTYPE,
DBAdaptorProductInput.KEY_BASEOIL,
DBAdaptorProductInput.KEY_ADDITIVES,
DBAdaptorProductInput.KEY_OTHERADDITIVES,
DBAdaptorProductInput.KEY_THICKENER,
DBAdaptorProductInput.KEY_NLGI,
DBAdaptorProductInput.KEY_COMMENT,
DBAdaptorProductInput.KEY_PACKAGES,
DBAdaptorProductInput.KEY_AREA,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.code,
R.id.name,
R.id.manufacturer,
R.id.visc40,
R.id.visc100,
R.id.viscindex,
R.id.den15c,
R.id.visctext,
R.id.baseoiltype,
R.id.baseoil,
R.id.additives,
R.id.otheradditives,
R.id.thickener,
R.id.nlgi,
R.id.comments,
R.id.packages,
R.id.area,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_product_review_info, cursor, columns, to, 0);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
//SetOnItemClickListener for the ListView
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the Customer Name from this row in the database.
String countryCode = cursor.getString(cursor.getColumnIndexOrThrow("ProductName"));
Toast.makeText(getApplicationContext(), countryCode, Toast.LENGTH_SHORT).show();
}
});
}
You need to have a custom adapter that extends BaseAdapter or SimpleCursorAdapter.
In the adapter's getView() method set the onClickListener for your ImageView.
In my code, right now, in order to properly refresh a listview I have to re-fetch my database information and recreate the SimpleCursorAdapter.
For example, I have a button inside a listview. When this button is clicked, it removes the entry from the database for the listview item. So all I want to happen is have the item removed from the listview, without having to recreate the adapter.
I've tried changing my global from SimpleCursorAdapter to BaseAdapater (because it extends SimpleCursorAdapater and allows for the notifyDataSetChanged() function to be used), but it still doesn't work.
Here is the code I'm using now (which does work):
Code for global declarations and onCreate():
private RoutinesDataSource datasource;
private SimpleCursorAdapter dataAdapter;
private boolean isEditing = false;
private Toast toast_deleted;
private String[] columns = new String[] { MySQLiteHelper.COLUMN_NAME };
private int[] to;
#SuppressLint("ShowToast")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_routines);
toast_deleted = Toast.makeText(this, "", Toast.LENGTH_SHORT);
datasource = new RoutinesDataSource(this);
datasource.open();
Cursor cursor = datasource.fetchAllRoutines();
to = new int[] { R.id.listitem_routine_name };
dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_routine, cursor, columns, to, 0);
setListAdapter(dataAdapter);
}
Code for the delete button inside the listview item:
public void onClick(View view) {
ListView l = getListView();
int position = l.getPositionForView(view);
Cursor cursor = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
cursor.moveToPosition(position);
long id = cursor.getLong(cursor.getColumnIndex(MySQLiteHelper.COLUMN_ID));
String name = cursor.getString(cursor.getColumnIndex(MySQLiteHelper.COLUMN_NAME));
switch (view.getId()) {
case R.id.button_routine_delete:
toast_deleted.setText(getString(R.string.toast_routine_deleted));
toast_deleted.show();
datasource.deleteRoutine(id);
onResume();
break;
}
}
Take note of me using onResume().
I know that datasource.deleteRoutine(id) works because when I close the activity and reopen it the list item is gone.
Code for onResume() which shows the list properly with the listview item removed:
#Override
protected void onResume() {
datasource.open();
Cursor cursor = datasource.fetchAllRoutines();
if (isEditing) {
to = new int[] { R.id.listitem_routine_edit_name };
dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_routine_edit, cursor, columns, to, 0);
setListAdapter(dataAdapter);
}
else {
to = new int[] { R.id.listitem_routine_name };
dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_routine, cursor, columns, to, 0);
setListAdapter(dataAdapter);
}
super.onResume();
}
I just think its bad practice to recreate the adapter every time I simply want a list item removed that has been removed from the database. Like I said I've tried notifyDataSetChanged with a BaseAdapater and it simply does not work.
Also take note of the isEditing boolean. That is set to true if the edit button is clicked in the action bar, which shows the delete button. This is useful because I also have an edit button which starts an activity when clicked, so when they come back after they are done editing it still shows the buttons for the user.
So anyways, can someone point me out how to refresh the list without having to recreate the adapter - or is what I've done the best method?
The URL in mango's comment to his resolution worked perfectly.
I just changed the code inside onResume() to this:
datasource.open();
Cursor cursor = datasource.fetchAllRoutines();
dataAdapter.changeCursor(cursor);
super.onResume();
Since onResume() is already called after someone adds or edits an item, I figured it wouldn't hurt to call it when the delete button is pressed considering it no longer recreates the adapter, rather simply changes the cursor.
I have a dialogfragment which adds an item to the database and immediately shows it in the listview .
The item added shows in the listview immediately but i don't know why the last item from the database doesn't appear .
It appears after executing the activity showing listview again , but not just after adding the item through my dialog fragment .
for example , if i have 3 items "a" , "b" and "d" in my listview and database , and when i add "c" , "d" doesn't show in the listview . it only shows after executing the fragment showing listview again .
Your adapter is using two different lists, the first is the superclass' list populated as object:
super(activity, R.layout.laundry_list_item, objects);
The other is your own:
private List my;
When you add an item to my the superclass, which provides the data for your ListView, does not know of this change until your restart the Activity.
Try changing your Save button to this:
nam = name.getText().toString();
pri = price.getText().toString();
i = new MyItem(nam, Double.parseDouble(pri));
db.addMyItem(i);
MyActivity f = (MyActivity) getActivity().getFragmentManager().findFragmentByTag("my");
f.getMyListAdapter().add(i);
// You might need this, but I believe the adapter will update itself in add()
//f.getMyListAdapter().notifyDataSetChanged();
getDialog().dismiss();
This will use the superclass' list and avoid your problem.
Alternatively with the code you have posted, I believe a SimpleCursorAdapter is a better choice than your own adapter.
In your Fragment:
public void onCreate() {
...
// Retrieve a Cursor of every row in the database, "SELECT _id, name, quantity FROM Table"
mCursor = db.getAllMyItemsCursor();
madapter = new SimpleCursorAdapter(this, R.layout.laundry_list_item, cursor,
new String[] { "name", "quantity" },
new int[] { R.id.item_name, R.id.item_qty });
}
public void updateListView() {
mCursor.requery();
madapter.notifyDataSetChanged();
}
In the Save Button:
nam = name.getText().toString();
pri = price.getText().toString();
db.addMyItem(new MyItem(nam, Double.parseDouble(pri)));
MyActivity f = (MyActivity) getActivity().getFragmentManager().findFragmentByTag("my");
f.updateListView();
Hope one of these helps!
Basicly I have two tables in my database brought together with a rawQuery and a ListActivity that is supposed to pull info from both tables and show it inside of the ListActivity. I don't get a force close or anything the problem is the information does not show up.
MY RAWQUERY
public Cursor fetchName() {
return ourdb.rawQuery("SELECT wwJobTable._id, wwJobTable.JobName, wwLatLonTable.JobLatitude FROM wwJobTable, wwLatLonTable WHERE wwLatLonTable.JobLatitude=wwJobTable.JobCode", null);
}
HOW I AM VIEWING THE TABLE INFORMATION
private void fillData() {
// Get all of the rows from the database and create the item list
mTimeNotesCursor = mDbHelper.fetchName();
mTimeNotesCursor.moveToFirst();
startManagingCursor(mTimeNotesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{WWDatabase.KEY_JOBNAME,
WWDatabase.KEY_LATITUDE};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.textView1, R.id.textView2};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.time_text_row, mTimeNotesCursor, from, to);
setListAdapter(notes);
}
What could I possibly be doing wrong?