getting error : 'onCreateLoader(int, Bundle)' in clashes with 'onCreateLoader(int, Bundle)' in androidx.loader.app.LoaderManager.LoaderCallbacks' - callback

I am making a fragment that uses content provider to get contacts from any phone using listview
#SuppressWarnings("ALL")
public abstract class fragment3 extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor>,
AdapterView.OnItemClickListener, androidx.loader.app.LoaderManager.LoaderCallbacks<Cursor> {
**strong text**
private LifecycleOwner owner;
private RVAdapter myadapter;
private Object CursorLoader;
public fragment3() {
}
public Loader<Cursor> loader;
private Cursor cursor;
public abstract class LoaderManager{}
ListView contactsList;
long contactId;
String contactKey;
Uri contactUri;
SimpleCursorAdapter cursorAdapter;
private final static int[] TO_IDS = {
android.R.id.text1
};
// The column index for the _ID column
final int CONTACT_ID_INDEX = 0;
// The column index for the CONTACT_KEY column
final int CONTACT_KEY_INDEX = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
// Always call the super method first
super.onCreate(savedInstanceState);
// Initializes the loader
getLoaderManager().initLoader(0, null, this);}
#SuppressLint("ResourceType")
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Set the item click listener to be the current fragment.
contactsList.setOnItemClickListener(this);
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
// Gets the ListView from the View list of the parent activity
contactsList =
(ListView) getActivity().findViewById(R.layout.list_view);
// Gets a CursorAdapter
cursorAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.list_item,
null,
FROM_COLUMNS, TO_IDS,
0);
// Sets the adapter for the ListView
contactsList.setAdapter(cursorAdapter);
getLoaderManager().initLoader(0, null, this);
}
// If non-null, this is the current filter the user has provided.
static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.CONTACT_STATUS,
ContactsContract.Contacts.PHOTO_ID,
};
// Called just before the Fragment displays its UI
#Override
public Loader<Cursor> onCreateLoader(int loaderId, Bundle args) {
/*
* Makes search string into pattern and
* stores it in the selection array
*/
selectionArgs[0] = "%" + searchString + "%";
// Starts the query
return new CursorLoader(
getActivity(),
ContactsContract.Contacts.CONTENT_URI,
PROJECTION,
SELECTION,
selectionArgs,
null
);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
// Put the result Cursor in the adapter for the ListView
cursorAdapter.swapCursor(cursor);
}
// Defines the text expression
#SuppressLint("InlinedApi")
final String SELECTION =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " LIKE ?" :
ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?";
// Defines a variable for the search string
private String searchString;
// Defines the array to hold values that replace the ?
private String[] selectionArgs = {searchString};
/*
* Defines an array that contains column names to move from
* the Cursor to the ListView.
*/
#SuppressLint("InlinedApi")
private final static String[] FROM_COLUMNS = {
Build.VERSION.SDK_INT
>= Build.VERSION_CODES.HONEYCOMB ?
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY :
ContactsContract.Contacts.DISPLAY_NAME
};
#Override
public void onItemClick(
AdapterView<?> parent, View item, int position, long rowID) {
// Get the Cursor
//Cursor cursor = parent.getAdapter().getCursor();
Cursor c = ((CursorAdapter)((parent)).getAdapter()).getCursor();
// Move to the selected contact
cursor.moveToPosition(position);
// Get the _ID value
contactId = cursor.getLong(CONTACT_ID_INDEX);
// Get the selected LOOKUP KEY
contactKey = cursor.getString(CONTACT_KEY_INDEX);
// Create the contact's content Uri
String mContactKey = "";
contactUri = ContactsContract.Contacts.getLookupUri(contactId, mContactKey);
/*
* You can use contactUri as the content URI for retrieving
* the details for a contact.
*/
}
// A UI Fragment must inflate its View
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the fragment layout
return inflater.inflate(R.layout.fragment_fragment3,
container, false);
}
#SuppressLint("InlinedApi") final String[] PROJECTION =
{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.LOOKUP_KEY,
Build.VERSION.SDK_INT
>= Build.VERSION_CODES.HONEYCOMB ?
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY :
ContactsContract.Contacts.DISPLAY_NAME
};
#Override
public void onLoaderReset(#NonNull androidx.loader.content.Loader<Cursor> loader) {
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}

Related

ClassCashException on PullToRefreshListView

I am trying to implement the PullToRefresh using ListView from eu.erikw.PullToRefreshListView project. I am using custom adapter to populate my listview. However on onItemClick event, I get this error java.lang.ClassCastException: android.widget.HeaderViewListAdapter cannot be cast to com.example.xxapp.RssAdapter where my RssAdapter class is
public class RssAdapter extends BaseAdapter{
private final List<RssItem> items;
private final Context context;
public RssAdapter(Context context, List<RssItem> items) {
this.items = items;
this.context = context;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int id) {
return id;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = View.inflate(context, R.layout.rss_item, null);
holder = new ViewHolder();
holder.itemTitle = (TextView) convertView.findViewById(R.id.itemTitle);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.itemTitle.setText(items.get(position).getTitle());
}
static class ViewHolder {
TextView itemTitle;
}
}
and RssItem class is
public class RssItem {
private final String title;
private final String link;
public RssItem(String title, String link) {
this.title = title;
this.link = link;
}
public String getTitle() {
return title;
}
public String getLink() {
return link;
}
}
and this is the onclick method giving the error
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Clicked item", "Position is " +position);
//line below gives ClasscastException error
RssAdapter adapter = (RssAdapter) parent.getAdapter();
RssItem item = (RssItem) adapter.getItem(position);
Uri uri = Uri.parse(item.getLink());
Intent i = new Intent(getActivity(),WebViewActivity.class);
i.putExtra("mystring",uri.toString());
startActivity(i);
}
Please I need help with the onclick method so I can get the link to display a webpage.
I have figured out a way. Before I set the adapter to the listview, I create another listarray with the same form as the RssItem so I can assign the adapter to this listarray. Later on when I need this adapter, I just call the new listarray which in this case is not affected by the header I added to the listview. Thanks njzk2 for your comment about keeping my adapter as an instance member. The solution looks like this:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Clicked item", "Position is " +position);
TextView title = (TextView) view.findViewById(R.id.itemTitle);
String titleItem = title.getText().toString();
Log.e("Title", titleItem);
//RssAdapter adapter = (RssAdapter) parent.getAdapter();
//RssItem item = (RssItem) adapter.getItem(position);
RssItem item = itemx.get(position);
Uri uri = Uri.parse(item.getLink());
Intent i = new Intent(getActivity(),WebViewActivity.class);
i.putExtra("mystring",uri.toString());
startActivity(i);
}
where itemx is the instance of my adapter. I don't know how effective it is to do this but it worked
You should use that
HeaderViewListAdapter hlva = (HeaderViewListAdapter)parent.getAdapter();
RssAdapter adapter = (RssAdapter)hlva.getWrappedAdapter();

Unable to load tab in PagerSlidingTabStrip when fragment is replaced

I'm trying to implement a viewpager with a PagerSlidingTabStrip instead of a TabView. The viewpager has three tabs in which each listview displays a list of events. The three tabs are called Past, Tonight and Future.
I've set up the slider as the github page suggests:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.all_events_main_strip, container, false);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
pager = (ViewPager) v .findViewById(R.id.pager_main);
tabs = (PagerSlidingTabStrip) v.findViewById(R.id.tabs);
adapter = new MyPagerAdapter(getFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
// Set Present tab as default
pager.setCurrentItem(1);
return v;
}
When the app starts the Main Activity adds for the first time this fragment and everything works great. 3 swipeable tabs with 3 listviews. (c.f. code section)
Here is the problem:
I've noticed that when I press the back button and replace the fragment again, in order to reopen the viewpager, the tab in the middle doesn't show any listview. If I swype left or right the content in the other tabs is loaded and displayed but the Present Tab remains empty.
When I debug the ToNightEvents ListFragment isn't called at all.
Do you guys have any suggestions to solve the problem?
The code:
The code is structured as follows: After the onCreateView I've added an OnDestroyView method to remove the fragment but it didn't work... Then in the fragmentPagerAdapter each page is called as a fragment in the getItem method. Finally at the end of the code you can see the three ListFragment classes in which a listview is populated through an AsyncTask
public class FragmentAllEvents extends Fragment
{
private static final String TAG_UID = "uid";
private static final String TAG_LOGO = "logo";
private static final String TAG_POKUID = "pokuid";
static ArrayList<HashMap<String, String>> userList;
ArrayList<HashMap<String, String>> userListTotal;
private final Handler handler = new Handler();
HashMap<String, String> userSelected;
EventsFunctions eventsFunctions;
UserFunctions userFunctions;
static ListView lv;
ActionBar actionBar;
MyPagerAdapter adapter;
ViewPager pager;
PagerSlidingTabStrip tabs;
private Drawable oldBackground = null;
private int currentColor = 0xFF666666;
//Context context = this;
#Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set up the action bar.
actionBar = getActivity().getActionBar();
actionBar.setHomeButtonEnabled(true);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.all_events_main_strip, container, false);
pager = (ViewPager) v .findViewById(R.id.pager_main);
tabs = (PagerSlidingTabStrip) v.findViewById(R.id.tabs);
adapter = new MyPagerAdapter(getFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
pager.setCurrentItem(1);
return v;
}
#Override
public void onDestroyView()
{
super.onDestroyView();
getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
}
public static class MyPagerAdapter extends FragmentPagerAdapter
{
public MyPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int i)
{
switch (i)
{
case 0:
return new PastEvents();
case 1:
return new ToNightEvents();
case 2:
return new FutureEvents();
/*default:
// The other sections of the app are dummy placeholders.
return new ToNightEvents();
*/
}
return null;
}
/**
* A fragment that launches past events list.
*/
public static class PastEvents extends ListFragment implements
PullToRefreshAttacher.OnRefreshListener
{
private ListView pastList;
private PullToRefreshAttacher mPullToRefreshAttacher;
ProgressBar progress;
String tabTime;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View pastView = inflater.inflate(R.layout.pastlist, container, false);
progress = (ProgressBar) pastView.findViewById(R.id.loading_spinner_past);
tabTime="past";
pastList = (ListView) pastView.findViewById(android.R.id.list);
// Now get the PullToRefresh attacher from the Activity. An exercise to the reader
// is to create an implicit interface instead of casting to the concrete Activity
mPullToRefreshAttacher = ((Home) getActivity()).getPullToRefreshAttacher();
// Now set the ScrollView as the refreshable view, and the refresh listener (this)
mPullToRefreshAttacher.addRefreshableView(pastList, this);
new AsyncLoadEvents(getActivity(), progress, pastList, mPullToRefreshAttacher).execute(tabTime);
return pastView;
}
#SuppressWarnings("unchecked")
#Override
public void onListItemClick(ListView listView, View view, int position, long id)
{
super.onListItemClick (listView, view, position, id);
HashMap<String, String> map = (HashMap<String, String>) getListView().getItemAtPosition(position);
//Log.e("AttendList Report", "Clicked list item: " + position +" Content: \n" + map.get(TAG_ID).toString());
Log.e("PastList Report", "Clicked list item: " + position +" Event's content: \n" + map.get(TAG_UID).toString());
Intent intent = new Intent(getActivity(), SingleEventActivity.class);
intent.putExtra("pokuid",map.get(TAG_POKUID)); // Maybe remove attribute toString();
intent.putExtra("uid", map.get(TAG_UID));
intent.putExtra("logo",map.get(TAG_LOGO));
getActivity().startActivity(intent);
}
#Override
public void onRefreshStarted(View view)
{
new AsyncLoadEvents(getActivity(), progress, pastList, mPullToRefreshAttacher).execute(tabTime);
}
}
/**
* A fragment that launches future event list.
*/
public static class FutureEvents extends ListFragment implements
PullToRefreshAttacher.OnRefreshListener
{
private ListView futureList;
private PullToRefreshAttacher mPullToRefreshAttacher;
ProgressBar progress;
String tabTime;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View futureView = inflater.inflate(R.layout.futurelist, container, false);
progress = (ProgressBar) futureView.findViewById(R.id.loading_spinner_future);
tabTime = "future";
futureList = (ListView) futureView.findViewById(android.R.id.list); //change to attendlist if needed
// Now get the PullToRefresh attacher from the Activity. An exercise to the reader
// is to create an implicit interface instead of casting to the concrete Activity
mPullToRefreshAttacher = ((Home) getActivity()).getPullToRefreshAttacher();
// Now set the ScrollView as the refreshable view, and the refresh listener (this)
mPullToRefreshAttacher.addRefreshableView(futureList, this);
new AsyncLoadEvents(getActivity(), progress, futureList, mPullToRefreshAttacher).execute(tabTime);
return futureView;
}
#SuppressWarnings("unchecked")
#Override
public void onListItemClick(ListView listView, View view, int position, long id)
{
super.onListItemClick (listView, view, position, id);
HashMap<String, String> map = (HashMap<String, String>) getListView().getItemAtPosition(position);
Log.e("PastList Report", "Clicked list item: " + position +" Event's content: \n" + map.get(TAG_UID).toString());
Intent intent = new Intent(getActivity(), SingleEventActivity.class);
intent.putExtra("pokuid",map.get(TAG_POKUID)); // Maybe remove attribute toString();
intent.putExtra("uid", map.get(TAG_UID));
intent.putExtra("logo",map.get(TAG_LOGO));
getActivity().startActivity(intent);
}
#Override
public void onRefreshStarted(View view)
{
new AsyncLoadEvents(getActivity(), progress, futureList, mPullToRefreshAttacher).execute(tabTime);
}
}
/**
* A fragment that launches future event list.
*/
public static class ToNightEvents extends ListFragment implements
PullToRefreshAttacher.OnRefreshListener
{
private ListView tonightList;
private PullToRefreshAttacher mPullToRefreshAttacher;
ProgressBar progress;
String tabTime;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View tonightView = inflater.inflate(R.layout.tonightlist, container, false);
progress = (ProgressBar) tonightView.findViewById(R.id.loading_spinner_tonight);
tabTime = "tonight";
tonightList = (ListView) tonightView.findViewById(android.R.id.list); //change to attendlist if needed
// Now get the PullToRefresh attacher from the Activity. An exercise to the reader
// is to create an implicit interface instead of casting to the concrete Activity
mPullToRefreshAttacher = ((Home) getActivity()).getPullToRefreshAttacher();
// Now set the ScrollView as the refreshable view, and the refresh listener (this)
mPullToRefreshAttacher.addRefreshableView(tonightList, this);
new AsyncLoadEvents(getActivity(), progress, tonightList, mPullToRefreshAttacher).execute(tabTime);
return tonightView;
}
#SuppressWarnings("unchecked")
#Override
public void onListItemClick(ListView listView, View view, int position, long id)
{
super.onListItemClick (listView, view, position, id);
HashMap<String, String> map = (HashMap<String, String>) getListView().getItemAtPosition(position);
Log.e("PastList Report", "Clicked list item: " + position +" Event's content: \n" + map.get(TAG_UID).toString());
Intent intent = new Intent(getActivity(), SingleEventActivity.class);
intent.putExtra("pokuid",map.get(TAG_POKUID)); // Maybe remove attribute toString();
intent.putExtra("uid", map.get(TAG_UID));
intent.putExtra("logo",map.get(TAG_LOGO));
getActivity().startActivity(intent);
}
#Override
public void onRefreshStarted(View view)
{
new AsyncLoadEvents(getActivity(), progress, tonightList, mPullToRefreshAttacher).execute(tabTime);
}
}
public String[] titles=
{
"Past",
"Tonight",
"Future"
};
#Override
public int getCount()
{
return titles.length;
}
#Override
public CharSequence getPageTitle(int position)
{
return titles[position];
}
}
}
This would normally work if you were in an Activity, however I guess you are in a Fragment since the code you posted is the method onCreateView(). The problem is that you are trying to use the FragmentManager of the Activity and you should be using the Fragment's FragmentManager. This FragmentManager is not what you need. Try this instead:
adapter = new MyPagerAdapter(getChildFragmentManager());
I think I'm a little bit late but if anyone happens to have the same error here is the solution =)
Q.
The following fixed it for me:
Add an OnBackStackChangedListener to the fragment manager.
In the onBackStackChanged method, get references to both the ViewPager and the PagerSlidingTabStrip (pager and tabs in your example). If the appropriate fragment is currently active, do the following:
pager.invalidate();
tabs.invalidate();
pager.setAdapter(new MyPagerAdapter(getFragmentManager()));
tabs.setViewPager(pager);

Gwt Simple pager issues with a column sort handler

I have set up an AsyncDataProvider for my CellTable and added it to a SimplePager. I have hooked up a ListHandler to take care of sorting based on a column.
When I click the header of that column, the data doesn't change but on going to the next/previous page within the pager the data is then sorted. Also before the column is clicked there is no visual indicator on the column that would indicate that it is meant to be sortable.
How can I get the data to update when I click the header of the Column?
Here's my code snippet
service.getHosts(environment, new AsyncCallback<Set<String>>() {
#Override
public void onSuccess(final Set<String> hosts) {
final List<String> hostList = new ArrayList<String>(hosts);
//Populate the table
CellTable<String> hostTable = new CellTable<String>();
TextColumn<String> hostNameColumn = new TextColumn<String>(){
#Override
public String getValue(String string){
return string;
}
};
NumberCell numberCell = new NumberCell();
Column<String, Number> lengthColumn = new Column<String, Number>(numberCell){
#Override
public Number getValue(String string) {
return new Integer(string.length());
}
};
AsyncDataProvider<String> dataProvider = new AsyncDataProvider<String>() {
#Override
protected void onRangeChanged(HasData<String> data) {
int start = data.getVisibleRange().getStart();
int end = start + data.getVisibleRange().getLength();
List<String> subList = hostList.subList(start, end);
updateRowData(start, subList);
}
};
// Hooking up sorting
ListHandler<String> columnSortHandler = new ListHandler<String>(hostList);
columnSortHandler.setComparator(lengthColumn, new Comparator<String>(){
#Override
public int compare(String arg0, String arg1) {
return new Integer(arg0.length()).compareTo(arg1.length());
}
});
hostTable.setPageSize(10);
hostTable.addColumnSortHandler(columnSortHandler);
hostTable.addColumn(hostNameColumn,"Host Name");
lengthColumn.setSortable(true);
hostTable.addColumn(lengthColumn, "Length");
VerticalPanel verticalPanel = new VerticalPanel();
SimplePager pager = new SimplePager();
pager.setDisplay(hostTable);
dataProvider.addDataDisplay(hostTable);
dataProvider.updateRowCount(hosts.size(), true);
verticalPanel.add(hostTable);
verticalPanel.add(pager);
RootPanel.get().add(verticalPanel);
}
#Override
public void onFailure(Throwable throwable) {
Window.alert(throwable.getMessage());
}
});
I'm not sure how to make sure that the list is shared by both the table and the Pager. Before adding the pager I was using
ListDataProvider<String> dataProvider = new ListDataProvider<String>();
ListHandler<String> columnSortHandler = new ListHandler<String>(dataProvider.getList());
The AsyncDataProvider doesn't have the method getList.
To summarize I want the data to be sorted as soon as the column is clicked and not after I move forward/backward with the pager controls.
As per the suggestion I have changed the code for the AsyncDataProvider to
AsyncDataProvider<String> dataProvider = new AsyncDataProvider<String>() {
#Override
protected void onRangeChanged(HasData<String> data) {
int start = data.getVisibleRange().getStart();
int end = start + data.getVisibleRange().getLength();
List<String> subList = hostList.subList(start, end);
// Hooking up sorting
ListHandler<String> columnSortHandler = new ListHandler<String>(hostList);
hostTable.addColumnSortHandler(columnSortHandler);
columnSortHandler.setComparator(lengthColumn, new Comparator<String>(){
#Override
public int compare(String v0, String v1) {
return new Integer(v0.length).compareTo(v1.length);
}
});
updateRowData(start, subList);
}
};
But there is no change in the behavior even after that. Can someone please explain the process. The GWT showcase app seems to have this functionality but how they've done it isn't all that clear.
When using an AsyncDataProvider both pagination and sorting are meant to be done on the server side. You will need an AsyncHandler to go with your AsyncDataProvider:
AsyncHandler columnSortHandler = new AsyncHandler(dataGrid) {
#Override
public void onColumnSort(ColumnSortEvent event) {
#SuppressWarnings("unchecked")
int sortIndex = dataGrid.getColumnIndex((Column<Entry, ?>) event.getColumn());
boolean isAscending = event.isSortAscending();
service.getPage(0, sortIndex, isAscending, new AsyncCallback<List<Entry>>() {
public void onFailure(Throwable caught) {
}
public void onSuccess(List<Entry> result) {
pager.setPage(0);
provider.updateRowData(0, result);
}
});
}
};
dataGrid.addColumnSortHandler(columnSortHandler);
Clicking on a column header will then fire a columnSortEvent. Then you have to get the column clicked. I am overloading my servlet to provide both sorting and pagination, so I pass a -1 for the column index when only pagination is desired.
provider = new AsyncDataProvider<Entry>() {
#Override
protected void onRangeChanged(HasData<Entry> display) {
final int start = display.getVisibleRange().getStart();
service.getPage(start, -1, true, new AsyncCallback<List<Entry>>() {
#Override
public void onFailure(Throwable caught) {
}
#Override
public void onSuccess(List<Entry> result) {
provider.updateRowData(start, result);
}
});
}
};
provider.addDataDisplay(dataGrid);
provider.updateRowCount(0, true);
Then your servlet implementation of getPage performs the sorting and pagination. The whole thing is much easier to follow with separate event handlers.
I think the problem is with the ListHandler initialization. You are passing hostList as a parameter to List Handler and in onRangeChange method you are calling updateRowData with a different list (sublist).
Make sure you use the same list in both the places.
or
Move your ListHander initialization and cellTable.addColumnSortHandler method call to onRangeChange method after updateRowData call.

Refresh Listview in android

I"m tring it refresh my listview when my sqllite database is change (when delete or update query).
the querys itself works just fine, but it doesn't update the listview layout, only when i"m exiting the acitvity and renter it the liseview is changing.
I tried the methodes:
notifyDataSetChanged()
requery()
the code of the activiy is:
public class ShowListActivity extends ListActivity {
private ItemsDataSource itemsDataSource;
private String source[] = new String[] {MySQLiteHelper.KEY_NAME, MySQLiteHelper.KEY_QUANTITY, MySQLiteHelper.KEY_CHECKED};
private int dest[] = new int[] {R.id.itemTitle, R.id.itemQuantity, R.id.itemCheck};
public void goBackMethod(View view) {
Intent intent = new Intent(this, MainScreen.class);
startActivity(intent);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.activity_show_list);
} catch (Exception e) {
e.getMessage();
}
ApplicationController applicationController = (ApplicationController)getApplicationContext();
itemsDataSource = applicationController.itemsDataSource;
final Cursor mCursor = itemsDataSource.getAllItems();
startManagingCursor(mCursor);
CustomCursorAdapter adapter = new CustomCursorAdapter(this, mCursor);
adapter.notifyDataSetChanged();
setListAdapter(adapter);
ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selectAction(id);
}
});
}
private void selectAction(final long position) {
Builder builder = new AlertDialog.Builder(this);
builder.setTitle("בחר פעולה");
builder
.setMessage("בחר בפעולה שברצונך לבצע:");
builder.setPositiveButton("עדכן פריט קניה",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do update
}
});
builder.setNeutralButton("מחק פריט קניה",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
itemsDataSource.deleteItem(position);
Toast toast = Toast.makeText(getBaseContext(), "הפריט הנבחר נמחק בהצלחה", Toast.LENGTH_SHORT);
toast.show();
}
});
builder.setNegativeButton("חזור לרשימת הקניות",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
the code of the customadapter is:
public class CustomCursorAdapter extends CursorAdapter implements Adapter {
private Cursor mCursor;
private Context mContext;
private final LayoutInflater mInflater;
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
mInflater=LayoutInflater.from(context);
mContext=context;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView itemTitle= (TextView)view.findViewById(R.id.itemTitle);
itemTitle.setText(cursor.getString(cursor.getColumnIndex(MySQLiteHelper.KEY_NAME)));
TextView itemQuantity = (TextView)view.findViewById(R.id.itemQuantity);
itemQuantity.setText(cursor.getString(cursor.getColumnIndex(MySQLiteHelper.KEY_QUANTITY)));
CheckBox itemCheck = (CheckBox) view.findViewById(R.id.itemCheck);
itemCheck.setChecked(cursor.getInt(cursor.getColumnIndex(MySQLiteHelper.KEY_CHECKED))==1);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view=mInflater.inflate(R.layout.listview_item_row, parent, false);
TextView itemTitle= (TextView)view.findViewById(R.id.itemTitle);
itemTitle.setText(cursor.getString(cursor.getColumnIndex(MySQLiteHelper.KEY_NAME)));
TextView itemQuantity = (TextView)view.findViewById(R.id.itemQuantity);
itemQuantity.setText(cursor.getString(cursor.getColumnIndex(MySQLiteHelper.KEY_QUANTITY)));
CheckBox itemCheck = (CheckBox) view.findViewById(R.id.itemCheck);
itemCheck.setChecked(cursor.getInt(cursor.getColumnIndex(MySQLiteHelper.KEY_CHECKED))==1);
return view;
}
}
in your code you have not added your adapter class. I am sure that you will be adding the data in list view from an array list.
So in the time of updating the list view by adding or removing a data to the list view, first either add or remove the data from your array list and the call as follows
listView.invalidateViews();
then call your set Adapter method

how to convert flextable cell into editable text cell in GWT

Here is the code I tried to make the flextable's cell editable
The flex table is loaded with db values, when user clicks on the cell of flextable, it has to become editable and the user entered value has to be stored in db, after the user clicks submit button which is present at each row.
I'm using EditTextCell(), to make the cell editable but it not becoming editable when I test it. I have included all my codes below. Please let me know , if i'm missing anything.
private List<PendingChange<?>> pendingChanges = new ArrayList<PendingChange<?>>();
private List<AbstractEditableCell<?, ?>> editableCells = new ArrayList<AbstractEditableCell<?, ?>>();
CellTable cellTable= new CellTable<MessageEvent>();
EditTextCell editCell = new EditTextCell();
protected FlexTable flextable;
//flextable creation
private final void createWorkflows(List<MessageEvent> theWorkflowMessageEvents, boolean isSelectAll) {
int row = 1;
if (theWorkflowMessageEvents != null) {
for (final MessageEvent workflowMessageEvent : theWorkflowMessageEvents) {
flextable.getRowFormatter().setStyleName(row,ACTIVE_COLLECTION);
flextable.getCellFormatter().setHorizontalAlignment(row, 0, HasHorizontalAlignment.ALIGN_LEFT);
flextable.getCellFormatter().setWordWrap(row, 0, false);
flextable.setText(row, 0, workflowMessageEvent.getTransferReceived());
flextable.getCellFormatter().setHorizontalAlignment(row, 1, HasHorizontalAlignment.ALIGN_LEFT);
flextable.getCellFormatter().setWordWrap(row, 1, false);
flextable.setText(row, 1, workflowMessageEvent.getLoadReceived());
makeFlexTableEditable() ;
Button submitButton= new Button("Submit");
flextable.getCellFormatter().setHorizontalAlignment(row, 3, HasHorizontalAlignment.ALIGN_LEFT);
flextable.getCellFormatter().setWordWrap(row, 3, false);
flextable.setWidget(row, 3,submitButton );
submitWorklow(submitButton,row, workflowMessageEvent);
flextable.getRowFormatter().setVisible(row, true);
row++;
}
}
}
//adding flextable to main panel
protected void displayPendingWorkflows(final List<MessageEvent> theWorkflowMessageEvents) {
this.createPendingWorkflows(theWorkflowMessageEvents, false);
//some code
mainPanel.add(flextable);
mainPanel.add(cellTable);
}
//code for making flex table editable for TransferReceived column
private void makeFlexTableEditable() {
addColumn(new EditTextCell(), new GetValue() {
#Override
public String getValue(MessageEvent workflowMessageEvent) {
return workflowMessageEvent.getTransferReceived();
}
}, new FieldUpdater<MessageEvent, String>() {
public void update(int index, MessageEvent workflowMessageEvent, String value) {
try { pendingChanges.add(new TransferReceived(workflowMessageEvent, value));
}catch (Exception e) {
}
}
});
}
private <C> Column<MessageEvent, String> addColumn(EditTextCell cell,
final GetValue<String> getter,FieldUpdater<MessageEvent, String> fieldUpdater) {
Column<MessageEvent, String> transColumn = new Column<MessageEvent, String>(cell){
#Override
public String getValue(MessageEvent object) {
return getter.getValue(object);
}
};
transColumn.setFieldUpdater(fieldUpdater);
if (cell instanceof AbstractEditableCell<?, ?>) {
editableCells.add((AbstractEditableCell<?, ?>) cell);
}
cellTable.addColumn(transColumn);
return transColumn;
}
/**
* A pending change to a {#link MessageEvent}. Changes aren't committed
* immediately to illustrate that cells can remember their pending changes.
*
* #param <T> the data type being changed
*/
private abstract static class PendingChange<T> {
private final MessageEvent message;
private final T value;
public PendingChange(MessageEvent message, T value) {
this.message = message;
this.value = value;
}
/**
* Commit the change to the contact.
*/
public void commit() {
doCommit(message, value);
}
/**
* Update the appropriate field in the .
*
* #param message to update
* #param value the new value
*/
protected abstract void doCommit(MessageEvent message, T value);
}
/**
* Updates the Transfered Received.
*/
private static class TransferReceived extends PendingChange<String> {
public TransferReceived(MessageEvent message, String value) {
super(message, value);
}
#Override
protected void doCommit(MessageEvent message, String value) {
message.setTransferReceived(value);
}
}
/**
* Get a cell value from a record.
*
* #param <C> the cell type
*/
private static interface GetValue<C> {
C getValue(MessageEvent message);
}
I did something like this in my app. Sorry if the syntax is a bit off but the main idea is to use a clickevent and then get this events position and exchange the widget in that position.
final FlexTable flexTable = new FlexTable();
flexTable.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
Cell cell = flexTable.getCellForClickEvent(event);
final int row = cell.getRow();
final int column = cell.getIndex();
final TextBox textBox = new TextBox();
// Get the text from the cell in some way. Maybe use flextTable.getHTML(row, column) or what ever you prefer
// textBox.setText("Something other than this");
textBox.addKeyDownHandler(new KeyDownHandler() {
public void onKeyDownEvent(KeyDownEvent event) {
int code = event.getNativeKeyCode();
if (KeyCodes.KEY_ENTER == code) {
flexTable.setWidget(row, column, new Label(textBox.getText()));
}
}
});
flexTable.setWidget(row, column, textBox);
// You may also need something like this
textBox.setFocus(true);
}
});