Access data in Adapter From Activity - android-activity

i want to access data inside Adapter from Activity, and then i will passing the data from activity to call API.. here is my data inside PremiumAdapter.java :
public class PremiumVideoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
static List<PremiumVideo> data;
public PremiumVideoAdapter(List<PremiumVideo> data) {
this.data = data;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
PremiumVideo video = data.get(position);
final VH vh = (VH) holder;
String harga = video.price; //Target Data
String content_id = video.content_id; // Target Data
and i want to access from here PreviewActivity.java :
btnBuy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
// Access data in Adapter from here
Call<APIResponse<DataJsonCharging>> call = ServicesFactory.getService().getCharging(/* Passing data from adapter here*/);

Related

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

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) {
}
}

Unable to get GWT ListDataProvider to work with DataGrid

I had my data in a FlexTable, but am migrating to a DataGrid so I can easily add pagination. I get the data via a REST call. I can't seem to get the data to actually display. Here are the relevant snippets:
private DataGrid<SearchResult> resultsGrid = new DataGrid<SearchResult>();
resultsGrid.setAutoHeaderRefreshDisabled(true);
TextColumn<SearchResult> titleColumn = new TextColumn<SearchResult>() {
#Override
public String getValue(SearchResult object) {
return object.getTitle();
}
};
resultsGrid.addColumn(titleColumn, "Document Title");
ButtonCell buttonCell = new ButtonCell();
Column<SearchResult, String> buttonColumn = new Column<SearchResult, String>(buttonCell){
#Override
public String getValue(SearchResult object) {
return "Show";
}
};
resultsGrid.addColumn(buttonColumn, "");
buttonColumn.setFieldUpdater(new FieldUpdater<SearchResult, String>() {
public void update(int index, SearchResult object, String value) {
doPreview(object.title);
}
});
TextColumn<SearchResult> roleColumn = new TextColumn<SearchResult>() {
#Override
public String getValue(SearchResult object) {
return object.getRoles();
}
#Override
public String getCellStyleNames(Context context, SearchResult object) {
if (object.containsCurrentRole)
return "highlight";
else
return null;
}
};
resultsGrid.addColumn(roleColumn, "Associated Roles");
final SingleSelectionModel<SearchResult> selectionModel = new SingleSelectionModel<SearchResult>();
resultsGrid.setSelectionModel(selectionModel);
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
public void onSelectionChange(SelectionChangeEvent event) {
SearchResult selected = selectionModel.getSelectedObject();
if (selected != null) {
clearWordCloud();
getWordCloud(selected.getTitle());
}
}
});
dataProvider.addDataDisplay(resultsGrid);
// Create a Pager to control the table.
SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class);
pager = new SimplePager(TextLocation.CENTER, pagerResources, false, 0, true);
pager.setDisplay(resultsGrid);
resultsGrid.setVisible(true);
resultsGrid.addStyleName("results");
mainPanel.add(resultsGrid);
...
The function that gets called after a search:
private void updateTable(List<SearchResult> results) {
dataProvider.getList().addAll(results);
dataProvider.refresh();
dataProvider.flush();
resultsGrid.setVisible(true);
resultsFlexTable.setVisible(true);
}
At first I was missing the flush and refresh, but adding them had no effect. I'm kind of stumped.
The most likely problem is that your DataGrid has a height of zero. DataGrid implements RequiresResize, which means that its height either has to be set explicitly, or it will acquire its height from a parent widget if this parent widget implements ProvidesResize. FlexTable does not implement ProvidesResize interface.
NB: You don't need flush and refresh - adding data to the DataProvider refreshes the grid.

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();

How to create CellTable based on the response from the server

I want to create a CellTable. But Columns of the celltable should be based on the response from the server. I'm getting the server response as List.
No of Columns = Size of the list.
CellTable column header should be the value from the server.
For ex. Server response: List<Contacts> contacts
Header should be contacts.getName().
I achieved it by the following code.
for (Contacts contact : contacts) {
final String city = contact.getCity();
final TextColumn<String> addressColumn = new TextColumn<String>() {
#Override
public String getValue(Contacts object) {
return city;
}
};
cellTable.addColumn(addressColumn, contact.getAddress());
}
Regards,
Gnik
Use CellList with an AsyncDataProvider:
//Create a cellList
#UiField
CellList<Contact> cellList;
//Creating dataProvider and completion of the cellList
#UiFactory
CellList<Contact> makeCellList() {
private AsyncDataProvider<Contact> provider = new AsyncDataProvider<Contact>() {
#Override
public void onRangeChanged(final HasData<Contact> display) {
rpcService.getContact(new AsyncCallback<List<Contact>>() {
#Override
public void onSuccess(List<Contact> result) {
display.setRowData(0, result);
}
#Override
public void onFailure(Exception ex) {
//TODO
}
});
}
};
//Adding the cellList to the provider in a constructor
provider.addDataDisplay(cellList);
Here's full example and docs.

SuggestBox override addSelectionHandler

I have a custom Oracle with Objects to pass to the SuggestBox. Then I need get back a object when it's selected from de SuggestBox.
public HandlerRegistration addSelectionHandler(SelectionHandler<SuggestOracle.Suggestion> handler)
The problem is that I don't have Suggestion. I have "CustomSuggestion". I read de API and I try to write a Custom SuggestBox implementing the interface HasSelectionHandlers but I can't because the SuggestBox have a implementation of the interface. I get the error:
The interface HasSelectionHandlers cannot be implemented more than once with different arguments: HasSelectionHandlers<SuggestOracle.Suggestion> and HasSelectionHandlers<CustomSuggestion>
Can you help me? Sorry for my bad english.
Not sure I understand your problem. Have a look at the following example (really basic but you should get an idea on how to deal with custom suggestions). Hope that helps:
public void onModuleLoad() {
SuggestBox box = new SuggestBox(new CustomOracle<CustomSuggestion>());
box.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
#Override
public void onSelection(SelectionEvent<Suggestion> event) {
String value = ((CustomSuggestion) event.getSelectedItem()).fSomeOtherValue;
Window.alert(value);
}
});
RootPanel.get().add(box);
}
private class CustomOracle<CustomSuggestion> extends SuggestOracle {
private LinkedList<Starter.CustomSuggestion> fStore;
public CustomOracle() {
fStore = new LinkedList<Starter.CustomSuggestion>();
fStore.add(new Starter.CustomSuggestion("2", "two", "foo"));
fStore.add(new Starter.CustomSuggestion("22", "twenty-two", "bar"));
fStore.add(new Starter.CustomSuggestion("222", "two-hundred twenty-two", "w000t"));
}
#Override
public void requestSuggestions(Request request, Callback callback) {
String query = request.getQuery();
LinkedList<Starter.CustomSuggestion> result = new LinkedList<Starter.CustomSuggestion>();
for (Starter.CustomSuggestion entry : fStore) {
if (entry.fDisplay.contains(query)) {
result.add(entry);
}
}
callback.onSuggestionsReady(request, new Response(result));
}
}
private class CustomSuggestion implements Suggestion {
private String fReplace;
private String fDisplay;
private String fSomeOtherValue;
public CustomSuggestion(String display, String replace, String someOtherValue) {
fDisplay = display;
fReplace = replace;
fSomeOtherValue = someOtherValue;
}
#Override
public String getDisplayString() {
return fDisplay;
}
#Override
public String getReplacementString() {
return fReplace;
}
}