Im trying to implement a contact listview with a pageloader to manage loading on demand and a searchview to search within the list, but I cant get it working. I am all contacts in app.allContacts. The problem is that the searchview is not working. and I dont know if its the loaderCallback or the searchview.
public class ContactsFragment extends SherlockListFragment {
private SeparatedListAdapter sl;
private SumaApplication app;
private ContactAdapter allContacts;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
app = (SumaApplication) getActivity().getApplication();
allContacts = new ContactAdapter(getActivity());
sl = new SeparatedListAdapter(new HeaderAdaptor(getActivity(), R.layout.section_title, new ArrayList<String>()));
sl.addSection(getResources().getString(R.string.all_contacts), allContacts);
setListAdapter(sl);
getLoaderManager().initLoader(0, null, loaderCallbak);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_list_contacts, container, false);
((SearchView) v.findViewById(R.id.contacts_to)).setOnQueryTextListener(queryListener);
searchView = new SearchViewImpl(getActivity());
searchView.setOnQueryTextListener(queryListener);
searchView.setOnCloseListener(closeListener);
searchView.setIconifiedByDefault(true);
return v;
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
private SearchView searchView;
private OnCloseListener closeListener = new OnCloseListener() {
#Override
public boolean onClose() {
searchView.setQuery(null, true);
return true;
}
};
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" +((Contact) l.getItemAtPosition(position)).getInfo()));
startActivity(callIntent);
}
private LoaderCallbacks<List<Contact>> loaderCallbak = new LoaderCallbacks<List<Contact>>() {
#Override
public Loader<List<Contact>> onCreateLoader(int arg0, Bundle arg1) {
ContactPageLoader cpl = new ContactPageLoader(getActivity(), app);
cpl.setFilter(currentFilter);
return cpl;
}
#Override
public void onLoadFinished(Loader<List<Contact>> arg0, List<Contact> contacts) {
app.getAllContacts().subList(0, Math.min(app.getAllContacts().size() - 1, 3)));
allContacts.update(app.getAllContacts());
((SeparatedListAdapter) getListAdapter()).notifyDataSetInvalidated();
((SeparatedListAdapter) getListAdapter()).notifyDataSetChanged();
}
#Override
public void onLoaderReset(Loader<List<Contact>> arg0) {
}
};
private static class ContactAdapter extends ArrayAdapter<Contact> {
private LayoutInflater inflater;
public ContactAdapter(Context context) {
super(context, -1);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void update(List<Contact> contacts) {
if (contacts == null) {
return;
}
setNotifyOnChange(false);
clear();
addAll(contacts);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflate(getContext());
}
fill((ViewGroup) convertView, getItem(position));
return convertView;
}
private View inflate(Context context) {
View convertView = inflater.inflate(R.layout.contact_row, null, false);
convertView.setTag(R.id.contact_avatar, convertView.findViewById(R.id.contact_avatar));
convertView.setTag(R.id.contact_name, convertView.findViewById(R.id.contact_name));
convertView.setTag(R.id.contact_info, convertView.findViewById(R.id.contact_info));
return convertView;
}
private static void fill(ViewGroup rl, Contact contact) {
fillTextView(rl, R.id.contact_name, contact.getName());
fillTextView(rl, R.id.contact_info, contact.getInfo());
}
private static void fillTextView(ViewGroup rl, int id, String description) {
TextView t = ((TextView) rl.getTag(id));
t.setText(description);
}
}
public static class ContactPageLoader extends AsyncTaskLoader<List<Contact>> {
private SumaApplication app;
private String filter = null;
public ContactPageLoader(Context context, SumaApplication app) {
super(context);
this.app = app;
}
public void setFilter(String filter) {
this.filter = filter;
}
#Override
public List<Contact> loadInBackground() {
List<Contact> temp = new ArrayList<Contact>();
for(Contact c : app.getAllContacts()){
if(c.getName().matches("(.*)"+filter+"(.*)")){
temp.add(c);
}
}
return temp;
}
#Override
protected void onStartLoading() {
super.onStartLoading();
forceLoad();
}
}
private String currentFilter = null;
private OnQueryTextListener queryListener = new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// Called when the action bar search text has changed. Update
// the search filter, and restart the loader to do a new query
// with this filter.
String newFilter = newText;
// Don't do anything if the filter hasn't actually changed.
// Prevents restarting the loader when restoring state.
if (currentFilter == null && newFilter == null) {
return true;
}
if (currentFilter != null && currentFilter.equals(newFilter)) {
return true;
}
currentFilter = newFilter;
getLoaderManager().restartLoader(0, null, loaderCallbak);
return true;
}
};
private static class SearchViewImpl extends SearchView {
public SearchViewImpl(Context context) {
super(context);
}
// The normal SearchView doesn't clear its search text when
// collapsed, so we will do this for it.
#Override
public void onActionViewCollapsed() {
setQuery("", false);
super.onActionViewCollapsed();
}
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawingCacheQuality="high"
android:orientation="vertical" >
<SearchView
android:id="#+id/contacts_to"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#f1f1f1"
android:iconifiedByDefault="false"
android:paddingBottom="20dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="20dp"
android:queryHint="#string/query_hint"
android:visibility="visible"
android:/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f7f7f7"
android:orientation="vertical"
android:padding="20dp"
android:visibility="visible" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#color/separator_line"
android:dividerHeight="1dp" >
</ListView>
</LinearLayout>
Change the onCreateView like this.. Your using SearchView in your layout xml(not SearchViewImpl)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_list_contacts, container, false);
searchView = (SearchView) v.findViewById(R.id.contacts_to);
searchView.setOnQueryTextListener(queryListener);
searchView.setOnCloseListener(closeListener);
searchView.setIconifiedByDefault(true);
return v;
}
private LoaderCallbacks<List<Contact>> loaderCallbak = new LoaderCallbacks<List<Contact>>() {
#Override
public Loader<List<Contact>> onCreateLoader(int arg0, Bundle arg1) {
ContactPageLoader cpl = new ContactPageLoader(getActivity(), app);
cpl.setFilter(currentFilter);
return cpl;
}
#Override
public void onLoadFinished(Loader<List<Contact>> arg0, List<Contact> contacts) {
if(currentFilter == null){
allContacts.update(app.getAllContacts());
} else{
allContacts.update(temp);
}
((SeparatedListAdapter) getListAdapter()).notifyDataSetInvalidated();
((SeparatedListAdapter) getListAdapter()).notifyDataSetChanged();
}
Related
I'm creating a searchable spinner using third party library. I have added library classes(SearchableListDialog, SearchableSpinner) in my app. Everything is working fine but still one problem I'm facing for example, In search-view widget if I search Abc, I'm not getting the result filtered as Abc but when clicking on the list-view items, results is showing item as Abc. It is like the position is change for the items but the list is not showing the searchable result. I'm not getting where is I'm wrong. I modified code many times but didn't get desirable result.
Searchable Spinner xml code:
<com.example.my.currencyconverterapp.activity.SearchableSpinner
android:id="#+id/spinner"
android:layout_below="#+id/rl_currency_converterted_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
This is my Fragment code where I'm setting a adapter to searchable spinner.
countriesCustomAdapterInr = new CountriesCustomAdapterInr(getActivity(), R.layout.custom_spinner_items, arrayList,res);
spinner.setAdapter(countriesCustomAdapterInr);
assert spinner != null;
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getActivity(), ""+arrayList.get(i).getFull_name()+i, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {}
});
This is third party SearchableSpinner class:
public class SearchableSpinner extends android.support.v7.widget.AppCompatSpinner implements View.OnTouchListener,
SearchableListDialog.SearchableItem {
public static final int NO_ITEM_SELECTED = -1;
private Context _context;
private List _items;
private SearchableListDialog _searchableListDialog;
private boolean _isDirty;
private ArrayAdapter _arrayAdapter;
private String _strHintText;
private boolean _isFromInit;
public SearchableSpinner(Context context) {
super(context);
this._context = context;
init();
}
public SearchableSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
this._context = context;
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SearchableSpinner);
final int N = a.getIndexCount();
for (int i = 0; i < N; ++i) {
int attr = a.getIndex(i);
if (attr == R.styleable.SearchableSpinner_hintText) {
_strHintText = a.getString(attr);
}
}
a.recycle();
init();
}
public SearchableSpinner(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this._context = context;
init();
}
private void init() {
_items = new ArrayList();
_searchableListDialog = SearchableListDialog.newInstance
(_items);
_searchableListDialog.setOnSearchableItemClickListener(this);
setOnTouchListener(this);
_arrayAdapter = (ArrayAdapter) getAdapter();
if (!TextUtils.isEmpty(_strHintText)) {
ArrayAdapter arrayAdapter = new ArrayAdapter(_context, android.R.layout
.simple_list_item_1, new String[]{_strHintText});
_isFromInit = true;
setAdapter(arrayAdapter);
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (null != _arrayAdapter) {
// Refresh content #6
// Change Start
// Description: The items were only set initially, not reloading the data in the
// spinner every time it is loaded with items in the adapter.
_items.clear();
for (int i = 0; i < _arrayAdapter.getCount(); i++) {
_items.add(_arrayAdapter.getItem(i));
}
// Change end.
_searchableListDialog.show(scanForActivity(_context).getFragmentManager(), "TAG");
}
}
return true;
}
#Override
public void setAdapter(SpinnerAdapter adapter) {
if (!_isFromInit) {
_arrayAdapter = (ArrayAdapter) adapter;
if (!TextUtils.isEmpty(_strHintText) && !_isDirty) {
ArrayAdapter arrayAdapter = new ArrayAdapter(_context, android.R.layout
.simple_list_item_1, new String[]{_strHintText});
super.setAdapter(arrayAdapter);
} else {
super.setAdapter(adapter);
}
} else {
_isFromInit = false;
super.setAdapter(adapter);
}
}
#Override
public void onSearchableItemClicked(Object item, int position) {
setSelection(_items.indexOf(item));
if (!_isDirty) {
_isDirty = true;
setAdapter(_arrayAdapter);
setSelection(_items.indexOf(item));
}
}
public void setTitle(String strTitle) {
_searchableListDialog.setTitle(strTitle);
}
public void setPositiveButton(String strPositiveButtonText) {
_searchableListDialog.setPositiveButton(strPositiveButtonText);
}
public void setPositiveButton(String strPositiveButtonText, DialogInterface.OnClickListener onClickListener) {
_searchableListDialog.setPositiveButton(strPositiveButtonText, onClickListener);
}
public void setOnSearchTextChangedListener(SearchableListDialog.OnSearchTextChanged onSearchTextChanged) {
_searchableListDialog.setOnSearchTextChangedListener(onSearchTextChanged);
}
private Activity scanForActivity(Context cont) {
if (cont == null)
return null;
else if (cont instanceof Activity)
return (Activity) cont;
else if (cont instanceof ContextWrapper)
return scanForActivity(((ContextWrapper) cont).getBaseContext());
return null;
}
#Override
public int getSelectedItemPosition() {
if (!TextUtils.isEmpty(_strHintText) && !_isDirty) {
return NO_ITEM_SELECTED;
} else {
return super.getSelectedItemPosition();
}
}
#Override
public Object getSelectedItem() {
if (!TextUtils.isEmpty(_strHintText) && !_isDirty) {
return null;
} else {
return super.getSelectedItem();
}
}
}
This is third party SearchableListDialog class:
public class SearchableListDialog extends DialogFragment implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private static final String ITEMS = "items";
private CountriesCustomAdapterInr listAdapter;
private ListView _listViewItems;
private SearchableItem _searchableItem;
private OnSearchTextChanged _onSearchTextChanged;
private SearchView _searchView;
private String _strTitle;
private String _strPositiveButtonText;
private DialogInterface.OnClickListener _onClickListener;
public SearchableListDialog() {
}
public static SearchableListDialog newInstance(List items) {
SearchableListDialog multiSelectExpandableFragment = new
SearchableListDialog();
Bundle args = new Bundle();
args.putSerializable(ITEMS, (Serializable) items);
multiSelectExpandableFragment.setArguments(args);
return multiSelectExpandableFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams
.SOFT_INPUT_STATE_HIDDEN);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Getting the layout inflater to inflate the view in an alert dialog.
LayoutInflater inflater = LayoutInflater.from(getActivity());
// Crash on orientation change #7
// Change Start
// Description: As the instance was re initializing to null on rotating the device,
// getting the instance from the saved instance
if (null != savedInstanceState) {
_searchableItem = (SearchableItem) savedInstanceState.getSerializable("item");
}
// Change End
View rootView = inflater.inflate(R.layout.searchable_list_dialog, null);
setData(rootView);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setView(rootView);
String strPositiveButton = _strPositiveButtonText == null ? "CLOSE" : _strPositiveButtonText;
alertDialog.setPositiveButton(strPositiveButton, _onClickListener);
// String strTitle = _strTitle == null ? "Select Country" : _strTitle;
// alertDialog.setTitle(strTitle);
final AlertDialog dialog = alertDialog.create();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams
.SOFT_INPUT_STATE_HIDDEN);
return dialog;
}
// Crash on orientation change #7
// Change Start
// Description: Saving the instance of searchable item instance.
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putSerializable("item", _searchableItem);
super.onSaveInstanceState(outState);
}
// Change End
public void setTitle(String strTitle) {
_strTitle = strTitle;
}
public void setPositiveButton(String strPositiveButtonText) {
_strPositiveButtonText = strPositiveButtonText;
}
public void setPositiveButton(String strPositiveButtonText, DialogInterface.OnClickListener onClickListener) {
_strPositiveButtonText = strPositiveButtonText;
_onClickListener = onClickListener;
}
public void setOnSearchableItemClickListener(SearchableItem searchableItem) {
this._searchableItem = searchableItem;
}
public void setOnSearchTextChangedListener(OnSearchTextChanged onSearchTextChanged) {
this._onSearchTextChanged = onSearchTextChanged;
}
private void setData(View rootView) {
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
_searchView = (SearchView) rootView.findViewById(R.id.search);
_searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName
()));
_searchView.setIconifiedByDefault(false);
_searchView.setOnQueryTextListener(this);
_searchView.setOnCloseListener(this);
_searchView.setQueryHint("Search Country");
_searchView.clearFocus();
InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(_searchView.getWindowToken(), 0);
List items = (List) getArguments().getSerializable(ITEMS);
_listViewItems = (ListView) rootView.findViewById(R.id.listItems);
//create the adapter by passing your ArrayList data
// listAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, items);
listAdapter = new CountriesCustomAdapterInr(getActivity(), R.layout.custom_spinner_items, arrayList, getResources());
//
//attach the adapter to the list
_listViewItems.setAdapter(listAdapter);
_listViewItems.setTextFilterEnabled(true);
_listViewItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
_searchableItem.onSearchableItemClicked(listAdapter.getItem(position), position);
getDialog().dismiss();
}
});
}
#Override
public boolean onClose() {
return false;
}
#Override
public boolean onQueryTextSubmit(String s) {
_searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String s) {
// listAdapter.filterData(s);
if (TextUtils.isEmpty(s)) {
// _listViewItems.clearTextFilter();
((ArrayAdapter) _listViewItems.getAdapter()).getFilter().filter(null);
} else {
((ArrayAdapter) _listViewItems.getAdapter()).getFilter().filter(s);
}
if (null != _onSearchTextChanged) {
_onSearchTextChanged.onSearchTextChanged(s);
}
return true;
}
public interface SearchableItem<T> extends Serializable {
void onSearchableItemClicked(T item, int position);
}
public interface OnSearchTextChanged {
void onSearchTextChanged(String strText);
}
}
Here OnQueryTextListener() not working fine. Please help me. I tried but didn't any solution. Can anyone please help me. Above, I have mentioned my query. Thanks
Instead of using a Spinner with SearchView, I would suggest you to achieve this with ListView and SearchView, I tried and it works very well.
Put a button on your activity. Now clicking on this button will open a custom dialog.
Your custom_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.SearchView
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Then set your button onClick event and do the following.
#Override
public void onClick(View view) {
Dialog dialog = new Dialog(SearchText.this);
LayoutInflater inflater = LayoutInflater.from(SearchText.this);
View view1 = inflater.inflate(R.layout.custom_search_layout, null);
ListView listView = view1.findViewById(R.id.listView);
SearchView searchView = view1.findViewById(R.id.searchView);
final ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<String>(SearchText.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.my_currency));
listView.setAdapter(stringArrayAdapter);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String newText) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
stringArrayAdapter.getFilter().filter(newText);
return false;
}
});
dialog.setContentView(view1);
dialog.show();
}
Now do your search, and add OnItemClickListener on your listview, and do whatever you want after selecting your choice.
you can search in your adapter... i didn't see your adapter
you can look my adapter
https://github.com/kenmeidearu/SearchableSpinner/blob/master/searchablespinnerlibrary/src/main/java/com/kenmeidearu/searchablespinnerlibrary/ListAdapterSpinner.java
i give you example
I am trying to display an Empty view in an app that displays movie posters. I am using a recyclerview - for example when I put my device in flight mode and click refresh I was expecting the app to display the empty state view but this is not the case.
The posters are still displayed in the Activity. Why is this the case?
The data is from the moviedatabase api & I am retrieving a movie title & relative image path
MAIN ACTIVITY
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Movie>> {
private static final String LOG_TAG = MainActivity.class.getSimpleName();
private static final int LOADER_ID = 1;
private MovieAdapter mMovieAdapter;
private RecyclerView mRecyclerView;
private GridLayoutManager mGridLayoutManager;
private LoaderManager mLoaderManager;
private View mLoadingIndicator;
private TextView mEmptyTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLoadingIndicator = findViewById(R.id.loadingIndicator);
mEmptyTextView = (TextView) findViewById(R.id.emptyStateTextView);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mLoadingIndicator.setVisibility(View.VISIBLE);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mGridLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(mGridLayoutManager);
mMovieAdapter = new MovieAdapter();
mRecyclerView.setAdapter(mMovieAdapter);
mLoaderManager = getSupportLoaderManager();
mLoaderManager.initLoader(LOADER_ID, null, this);
}
public void showMovieDataView() {
mEmptyTextView.setVisibility(View.INVISIBLE);
mRecyclerView.setVisibility(View.VISIBLE);
}
public void showErrorMessage() {
mRecyclerView.setVisibility(View.INVISIBLE);
mEmptyTextView.setVisibility(View.VISIBLE);
}
#Override
public Loader<List<Movie>> onCreateLoader(int id, Bundle args) {
return new MovieLoader(this, TmdbUrlUtils.BASE_URL);
}
#Override
public void onLoadFinished(Loader<List<Movie>> loader, List<Movie> data) {
mLoadingIndicator.setVisibility(View.INVISIBLE);
if (data == null) {
showErrorMessage();
} else {
showMovieDataView();
mMovieAdapter.setMovieData(data);
}
}
#Override
public void onLoaderReset(Loader<List<Movie>> loader) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.refresh:
mLoadingIndicator.setVisibility(View.VISIBLE);
mMovieAdapter.setMovieData(null);
getSupportLoaderManager().restartLoader(LOADER_ID, null, this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
ADAPTER CLASS
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {
List<Movie> mMovieList;
public static final String BASE_POSTER_URL = "http://image.tmdb.org/t/p/w185";
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Context context = holder.mImageView.getContext();
String imagePath = mMovieList.get(position).getmPosterPath();
Uri baseUri = Uri.parse(BASE_POSTER_URL);
Uri.Builder builder = baseUri.buildUpon();
builder.appendEncodedPath(imagePath);
String imageUrl = builder.toString();
Picasso.with(context).load(imageUrl).into(holder.mImageView);
}
#Override
public int getItemCount() {
if (null == mMovieList) return 0;
return mMovieList.size();
}
public void setMovieData(List<Movie> data) {
mMovieList = data;
this.notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public ViewHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.imagePoster);
}
}
}
ACTIVITY_MAIN XML
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f48fb1"
tools:context="com.example.android.cinemate.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#d4e157">
</android.support.v7.widget.RecyclerView>
<ProgressBar
android:id="#+id/loadingIndicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="invisible"/>
<TextView
android:id="#+id/emptyStateTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#f44336"
android:text="No network detected!"
android:visibility="invisible"/>
</FrameLayout>
CUSTOM OBJECT
public class Movie implements Parcelable {
public static final Creator<Movie> CREATOR = new Creator<Movie>() {
#Override
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
#Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
private String mTitle;
private String mPosterPath;
public Movie(String title, String posterPath) {
this.mTitle = title;
this.mPosterPath = posterPath;
}
protected Movie(Parcel in) {
mTitle = in.readString();
mPosterPath = in.readString();
}
public String getmTitle() {
return mTitle;
}
public void setmTitle(String mTitle) {
this.mTitle = mTitle;
}
public String getmPosterPath() {
return mPosterPath;
}
public void setmPosterPath(String mPosterPath) {
this.mPosterPath = mPosterPath;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(mTitle);
parcel.writeString(mPosterPath);
}
}
This is a LOG of what gets called when flight mode is on:
Refresh selected with Flight Mode on
TEST......MainActivity onCreateLoader() called
TEST.......MovieLoader loadInBackground() called
TEST.......NetworkUtils getDataFromNetwork() called
TEST.......NetworkUtils createUrl() called
TEST.......NetworkUtils makeHttpRequest() called
TEST.......MovieJsonUtils parseJson() called
TEST......MainActivity onLoadFinished() called
TEST......MainActivity showMovieData() called
I am using a recyclerView to show a grid of movie posters. The posters are contained in a List<> along with their respective title and so on.
I implemented a searchView widget and I can successuflly get a List of matching results. But I can't hide the other ones.
As you understand I don't want to delete the irrelevant movies from the adapter or the user would not be able to see them again.
This is the code:
public class SearchUtils {
public static List<String> search(List<Show> list, String keyword){
List<String> results = new ArrayList<>();
for (Show curVal : list){
String curTitle = curVal.getTitle().toLowerCase().trim();
if (curTitle.contains(keyword)){
results.add(curTitle);
}else{
results = new ArrayList<>();
}
}
return results;
}
}
ListFragment.java
public class ListFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Show>> {
private static final String LOG_TAG = "ListFragment";
private static final String ARG_SCOPE = "com.dcs.shows.activity_to_launch";
private static final String BASE_URL = "http://api.themoviedb.org/3";
private TextView tv;
private ProgressBar pb;
private int scope;
private RecyclerView mRecyclerView;
private ShowAdapter mShowAdapter;
private SearchView mSearchView;
public static ListFragment newInstance(int target) {
Bundle args = new Bundle();
args.putInt(ARG_SCOPE, target);
ListFragment fragment = new ListFragment();
fragment.setArguments(args);
return fragment;
}
public ListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scope = getArguments().getInt(ARG_SCOPE);
setHasOptionsMenu(true);
Log.i(LOG_TAG, "onCreate#Scope is: " + scope);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list, container, false);
mShowAdapter = new ShowAdapter(new ArrayList<Show>());
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
GridLayoutManager glm = new GridLayoutManager(getActivity(), 4);
mRecyclerView.setLayoutManager(glm);
mRecyclerView.addItemDecoration(new SpacesItemDecoration(8, getActivity()));
mRecyclerView.setAdapter(mShowAdapter);
mRecyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(glm) {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to the bottom of the list
}
});
pb = (ProgressBar)rootView.findViewById(R.id.progress_view);
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// fetch data
getLoaderManager().initLoader(1, null, this);
} else {
// display error
pb.setVisibility(View.GONE);
}
return rootView;
}
List<Show> searchList;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.main, menu);
final MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
mSearchView = (SearchView) myActionMenuItem.getActionView();
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
if(!mSearchView.isIconified()) {
mSearchView.setIconified(true);
}
myActionMenuItem.collapseActionView();
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if(s != null || !s.isEmpty()) {
for(Show movie : mShowAdapter.getList()) {
if(movie.getTitle().toLowerCase().contains(s.toLowerCase())){
mShowAdapter.add(movie);
}
mShowAdapter.notifyDataSetChanged();
}
} else {
mShowAdapter.addItemsToList(searchList, false);
}
return false;
}
});
mSearchView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewDetachedFromWindow(View arg0) {
// search was detached/closed
Log.v(LOG_TAG, "Restoring list: " + searchList + " size: " + searchList.size());
mShowAdapter.addItemsToList(searchList, false);
}
#Override
public void onViewAttachedToWindow(View arg0) {
// search was opened
searchList = mShowAdapter.getList();
}
});
}
private class ShowHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextView;
public ShowHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.grid_item_image);
mTextView = (TextView) itemView.findViewById(R.id.grid_item_title);
}
}
private class ShowAdapter extends RecyclerView.Adapter<ShowHolder> {
private List<Show> mShows;
public ShowAdapter(List<Show> shows) {
mShows = shows;
}
public void add(Show show){
mShows.add(show);
notifyDataSetChanged();
}
public void addItemsToList(List<Show> newShows, boolean append){
if(append){
mShows.addAll(newShows);
}else {
mShows = newShows;
}
notifyDataSetChanged();
}
public void removeItemsFromList(int index){
mShows.remove(index);
notifyItemRemoved(index);
}
public List<Show> getList(){
return mShows;
}
#Override
public ShowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(getActivity());
View rootView = inflater.inflate(R.layout.list_item_row, parent, false);
return new ShowHolder(rootView);
}
#Override
public void onBindViewHolder(ShowHolder holder, int position) {
Show currentShow = mShows.get(position);
holder.mTextView.setText(currentShow.getTitle());
Glide.with(getActivity()).load(currentShow.getImage()).into(holder.mImageView);
}
#Override
public int getItemCount() {
return mShows.size();
}
}
#Override
public Loader<List<Show>> onCreateLoader(int i, Bundle bundle) {
//start the loader with the appropriate uri
//for now it only supports movies+popular
//it will support movies+top, tv+popular, tv+top.
Uri baseUri = Uri.parse(BASE_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendPath("movie");
uriBuilder.appendPath("popular");
uriBuilder.appendQueryParameter("api_key", QueryUtils.API_KEY);
uriBuilder.appendQueryParameter("page", Integer.valueOf(1).toString());
Log.v(LOG_TAG, "onCreateLoader#URL built: " + uriBuilder.toString());
return new ShowLoader(getActivity(), uriBuilder.toString());
}
#Override
public void onLoadFinished(Loader<List<Show>> loader, List<Show> shows) {
// Clear the adapter of previous earthquake data
clearAdapter();
// If there is a valid list of Shows, then add them to the adapter's
// data set. This will trigger the ListView to update.
if (shows != null && !shows.isEmpty()) {
mShowAdapter.addItemsToList(shows, false);
mShowAdapter.notifyDataSetChanged();
}
pb.setVisibility(View.GONE);
}
#Override
public void onLoaderReset(Loader<List<Show>> loader) {
// Loader reset, so we can clear out our existing data.
clearAdapter();
}
private void clearAdapter(){
List<Show> empty = new ArrayList<>();
mShowAdapter.addItemsToList(empty, false);
mShowAdapter.notifyDataSetChanged();
}
Thanks
You can use two lists, one with all the elements (original), and one with just queried elements (this one should use recyclerview adapter). When querying, just select from original list and add them to adapter list, then notify changes. Don't forget to clear adapter list before adding new entries.
Edit: you can try something like this on onQueryTextChange method. Adapt for your own wish.
if(s != null && !s.isEmpty()) {
for(String movie : originalList) {
if(movie.toLowerCase().contains(s.toLowerCase()){
adapter.add(movie);
}
notifyChanges();
}
}
} else { adapter.addAll(originalList); }
Working on android app' and I want to pass value from my textview that is in a row of a listview and put it in a fragment. I hear about convertView.gettag and settag method put I don't know how to deal with.
My code:
public class EvaluationsFragment extends CustomFragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {
private Patient mPatient;
private View myView;
private Context context;
private Button btnAjoutEvaluation;
private ListView evaluations_historic_liste;
private List<Evaluation>mEvaluation;
private EvaluationDto mEvaluationDto;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState){
myView = inflater.inflate(R.layout.fragment_evaluations, container,false);
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
init();
}
private void init(){
evaluations_historic_liste = (ListView)myView.findViewById(R.id.evaluations_historic_liste);
btnAjoutEvaluation = (Button)myView.findViewById(R.id.evaluations_add__btn);
btnAjoutEvaluation.setOnClickListener(this);
TypeEvaluation mNouveauTypeEvaluation;
mPatient =((DossierActivity)mRootActivity).mPatient;
mEvaluationDto = new EvaluationDto(mRootActivity.getApplicationContext());
evaluations_historic_liste.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
EvaluationAdapter.EvaluationItem item = (EvaluationAdapter.EvaluationItem)view.getTag();
openDetailEvaluation(item);
}
});
mEvaluationDto.open();
try{
mEvaluation = mEvaluationDto.getEvaluationsByPatientId(mPatient.getId());
}catch (SQLException e) {
Log.e(Constants.APP_LOG_TAG, e.getMessage());
ACRA.getErrorReporter().handleException(e);
} finally{
mEvaluationDto.close();
}
if(mEvaluation != null && mEvaluation.size() >0){
evaluations_historic_liste.setAdapter(new EvaluationAdapter(mRootActivity,mEvaluation));
}else {
evaluations_historic_liste.setVisibility(View.GONE);
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case (R.id.evaluations_add__btn):
openNewEvaluation();
break;
}
}
public void openNewEvaluation(){
Fragment fragment = new EvaluationNouvelleFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new EvaluationNouvelleFragment());
fragmentTransaction.commit();
}
public void openDetailEvaluation(EvaluationAdapter.EvaluationItem item){
EvaluationAdapter evaluationAdapter = new EvaluationAdapter();
EvaluationDetailHistoriqueFragment detail = new EvaluationDetailHistoriqueFragment();
Bundle args = new Bundle();
args.putString(EvaluationDetailHistoriqueFragment.DATA_RECEIVE, /*HERE I NEED TO PUT item_evaluation_nom.setText()*/ );
detail.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.content_frame, detail).commit();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public class EvaluationAdapter extends BaseAdapter {
private Context mcontext;
private List<EvaluationItem> mItems = new ArrayList<EvaluationItem>();
public EvaluationAdapter(){}
public EvaluationAdapter(Context context, List<Evaluation> values) {
this.mcontext = context;
for (Evaluation e : values) {
mItems.add(new EvaluationItem(e));
}
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public EvaluationItem getItem(int position) {
return mItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
EvaluationItemHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mcontext).inflate(R.layout.list_items_historic_evaluations, parent, false);
holder = new EvaluationItemHolder();
holder.item_evaluation_date = (TextView) convertView.findViewById(R.id.item_evaluation_date);
holder.item_evaluation_nom = (TextView) convertView.findViewById(R.id.item_evaluation_nom);
holder.item_evaluation_personnel = (TextView) convertView.findViewById(R.id.item_evaluation_personnel);
holder.item_evaluation_score = (TextView) convertView.findViewById(R.id.item_evaluation_score);
holder.item_evaluation_date_reevaluation = (TextView) convertView.findViewById(R.id.item_evaluation_date_reevaluation);
convertView.setTag(holder);
}else{
holder = (EvaluationItemHolder)convertView.getTag();
}
final EvaluationItem item = getItem(position);
int score = (item.getScoreTV()).intValue();
holder.item_evaluation_date.setText( + " " + item.getDateTV());
holder.item_evaluation_nom.setText(item.getTypeEvalTV());
if (item.getPersonnelTV() != null) {
holder.item_evaluation_personnel.setText( + " " + item.getPersonnelTV());
}
holder.item_evaluation_score.setText( + String.valueOf(score));
if (item.getDateReevalTV() != null) {
holder.item_evaluation_date_reevaluation.setText( item.getDateReevalTV());
}
// convertView.setTag(1,item.getTypeEvalTV());
return convertView;
}
public class EvaluationItem {
private String dateTV;
private String typeEvalTV;
private String personnelTV;
private Double scoreTV;
private String dateReevalTV;
public String getDateTV() {return dateTV;}
public void setDateTV(String dateTV) {
this.dateTV = dateTV;
}
public String getTypeEvalTV() {
return typeEvalTV;
}
public void setTypeEvalTV(String typeEvalTV) {
this.typeEvalTV = typeEvalTV;
}
public String getPersonnelTV() {
return personnelTV;
}
public void setPersonnelTV(String personnelTV) {
this.personnelTV = personnelTV;
}
public Double getScoreTV() {
return scoreTV;
}
public void setScoreTV(Double scoreTV) {
this.scoreTV = scoreTV;
}
public String getDateReevalTV() {
return dateReevalTV;
}
public void setDateReevalTV(String dateReevalTV) {
this.dateReevalTV = dateReevalTV;
}
public EvaluationItem(Evaluation e){
this.dateTV = e.getDate();
this.typeEvalTV = e.getTypeEvaluation().getLibelle();
this.personnelTV = e.getPersonnelLibelle();
this.scoreTV = e.getScore();
this.dateReevalTV = e.getDateReevaluation();
}
}
}
public static class EvaluationItemHolder{
public TextView item_evaluation_date;
public TextView item_evaluation_nom;
public TextView item_evaluation_personnel;
public TextView item_evaluation_score;
public TextView item_evaluation_date_reevaluation;
}
}
You were doing good, you need a Bundle to do this.
First of all create a String where you can keep the value of
holder.item_evaluation_nom.getText();
Then for example you do this :
String itemEvaluation = holder.item_evaluation_nom.getText();
This is the correct Bundle
EvaluationDetailHistoriqueFragment detail = new EvaluationDetailHistoriqueFragment();
Bundle bundle = new Bundle();
bundle.putString("text", itemEvaluation);
detail.setArguments(bundle);
Then to retrieve this you do this :
Bundle bundle = this.getArguments();
if (bundle != null) {
String itemEvaluation = bundle.getString("text", "");
}
hope it helps.
EDIT
You'll need to add an Adapter to your evaluations_historic_liste list.
You can do this doing :
evaluations_historic_liste.setAdapter(new EvaluationAdapter(getActivity(),mEvaluation));
mEvaluation is the List that you have to put data on it.
Then in your ListView add this :
evaluation_historic_liste.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id){
String itemEvaluation = (String) ((TextView)view.findViewById(R.id.item_evaluation_nom)).getText();
//or
String itemEvaluation=(evaluation_historic_liste.getItemAtPosition(position).toString());
}
}
I can show images in gridview normally. However, I want to use pulltorefresh functionality and I found a library to get the functionality. I am confused how to integrate my images.
Now, the gridview just shows imagelinks in the array. How can I use imageAdapter instead of arrayAdapter to show the Images?
Thanks a lot.
This is the activity class:
public final class PullToRefreshGridActivity extends Activity {
static final int MENU_SET_MODE = 0;
private LinkedList<String> mListItems;
private PullToRefreshGridView mPullRefreshGridView;
private GridView mGridView;
private ArrayAdapter<String> mAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ptr_grid);
mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);
mGridView = mPullRefreshGridView.getRefreshableView();
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshGridView.setOnRefreshListener(new OnRefreshListener2<GridView>() {
#Override
public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
Toast.makeText(PullToRefreshGridActivity.this, "Pull Down!", Toast.LENGTH_SHORT).show();
new GetDataTask().execute();
}
#Override
public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
Toast.makeText(PullToRefreshGridActivity.this, "Pull Up!", Toast.LENGTH_SHORT).show();
new GetDataTask().execute();
}
});
mListItems = new LinkedList<String>();
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER);
tv.setText("Empty View, Pull Down/Up to Add Items");
mPullRefreshGridView.setEmptyView(tv);
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mListItems);
mGridView.setAdapter(mAdapter);
}
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... params) {
// Simulates a background job.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
return mStrings;
}
#Override
protected void onPostExecute(String[] result) {
mListItems.addFirst("Added after refresh...");
mListItems.addAll(Arrays.asList(result));
mAdapter.notifyDataSetChanged();
// Call onRefreshComplete when the list has been refreshed.
mPullRefreshGridView.onRefreshComplete();
super.onPostExecute(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_SET_MODE, 0,
mPullRefreshGridView.getMode() == Mode.BOTH ? "Change to MODE_PULL_DOWN"
: "Change to MODE_PULL_BOTH");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem setModeItem = menu.findItem(MENU_SET_MODE);
setModeItem.setTitle(mPullRefreshGridView.getMode() == Mode.BOTH ? "Change to MODE_PULL_FROM_START"
: "Change to MODE_PULL_BOTH");
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SET_MODE:
mPullRefreshGridView
.setMode(mPullRefreshGridView.getMode() == Mode.BOTH ? Mode.PULL_FROM_START
: Mode.BOTH);
break;
}
return super.onOptionsItemSelected(item);
}
private String[] mStrings = {"https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg",
"https://lh4.googleusercontent.com/--dq8niRp7W4/URquVgmXvgI/AAAAAAAAAbs/-gnuLQfNnBA/s1024/A%252520Song%252520of%252520Ice%252520and%252520Fire.jpg",
"https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s1024/Another%252520Rockaway%252520Sunset.jpg",
"https://lh3.googleusercontent.com/--L0Km39l5J8/URquXHGcdNI/AAAAAAAAAbs/3ZrSJNrSomQ/s1024/Antelope%252520Butte.jpg",
"https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s1024/Antelope%252520Hallway.jpg",
"https://lh4.googleusercontent.com/-WIuWgVcU3Qw/URqubRVcj4I/AAAAAAAAAbs/YvbwgGjwdIQ/s1024/Antelope%252520Walls.jpg",
"https://lh6.googleusercontent.com/-UBmLbPELvoQ/URqucCdv0kI/AAAAAAAAAbs/IdNhr2VQoQs/s1024/Apre%2525CC%252580s%252520la%252520Pluie.jpg",
"https://lh3.googleusercontent.com/-s-AFpvgSeew/URquc6dF-JI/AAAAAAAAAbs/Mt3xNGRUd68/s1024/Backlit%252520Cloud.jpg",
"https://lh5.googleusercontent.com/-bvmif9a9YOQ/URquea3heHI/AAAAAAAAAbs/rcr6wyeQtAo/s1024/Bee%252520and%252520Flower.jpg",
"https://lh5.googleusercontent.com/-n7mdm7I7FGs/URqueT_BT-I/AAAAAAAAAbs/9MYmXlmpSAo/s1024/Bonzai%252520Rock%252520Sunset.jpg",
"https://lh6.googleusercontent.com/-4CN4X4t0M1k/URqufPozWzI/AAAAAAAAAbs/8wK41lg1KPs/s1024/Caterpillar.jpg",
"https://lh3.googleusercontent.com/-rrFnVC8xQEg/URqufdrLBaI/AAAAAAAAAbs/s69WYy_fl1E/s1024/Chess.jpg",
"https://lh5.googleusercontent.com/-WVpRptWH8Yw/URqugh-QmDI/AAAAAAAAAbs/E-MgBgtlUWU/s1024/Chihuly.jpg",};
}
Create a custom Adapter, where you refresh each cell. Create an object which contains a String and Image property, in GetDataTask create an ArrayList of all those new objects and refresh your adapter.
Heres a simple example of the adapter and object
public class CustomStepsAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<CustomObject> details;
private LayoutInflater mInflater;
public CustomStepsAdapter(Context aContext, ArrayList<CustomObject> data) {
this.details = data;
this.mContext = aContext;
mInflater = LayoutInflater.from(aContext);
}
public int getCount() {
return details.size();
}
public CustomObject getItem(int position) {
return details.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView() {
return mInflater.inflate(R.layout.custom_step_options_cell, null);
}
public View getView(int position, View convertView, ViewGroup parent) {
final CustomObject item = getItem(position);
CustomStepCell cell = null;
if (convertView == null) {
convertView = getView();
cell = new CustomStepCell();
cell.itemName = (TextView) convertView.findViewById(R.id.option_name);
cell.image = (ImageView) convertView.findViewById(R.id.green_checkmark);
convertView.setTag(cell);
}
else
{
cell = (CustomStepCell) convertView.getTag();
}
cell.itemName.setText(item.getItemName());
cell.image = item.getImage();
return convertView;
}
public boolean isShowPrices() {
return showPrices;
}
public void setShowPrices(boolean showPrices) {
this.showPrices = showPrices;
}
public static class CustomStepCell
{
public TextView itemName;
public ImageView image;
}
}
public class CustomObject
{
private String itemName;
private ImageView image;
public CustomObject()
{
this.itemName = "";
}
public void setImage(ImageView anImage)
{
this.image = anImage;
}
public void setItemName(String anItemName)
{
this.itemName = anItemName;
}
public ImageView getImage()
{
return this.image;
}
public String getItemName()
{
return this.itemName;
}
}