I've been trying to implement a SearchView in my actionBar that filters a recyclerview that gets its data from an Async task for days now and I cant seem to get it to work.
On all the answers I've seen here gets The adapter for the recycler class is on the same class as the SearchView. but on my app the adapter is in the Async class while the Searchview is in a fragment. I made an Async class because I dont want my UI thread slowing down or crashing when my app is trying to load the items on the RecyclerView. Bellow are my codes, any help would be lovely.
and lastly for my fragment, I have a few codes so ill just cut most of them out and leave whats relevant to the question. Thanks.
for MyAsync.java
public class MyAsync extends AsyncTask<Void,RafTask,Void>{
private RecyclerView recyclerView;
private ProgressBar progressBar;
private Context context;
private static ClientRecycler recycler;
private SearchView searchView;
private ArrayList<RafTask> newLists = new ArrayList<>();
String am;
private static ArrayList<RafTask> raftask = new ArrayList<>();
private static final String TAG = "ListDataActivity";
public MyAsync(RecyclerView recyclerView, ProgressBar progressBar,Context context, ArrayList<RafTask> newList){
this.recyclerView = recyclerView;
this.progressBar = progressBar;
this.context = context;
this.newLists = newList;
}
#Override
protected void onPreExecute() {
recycler = new ClientRecycler(raftask);
recyclerView.setAdapter(recycler);
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... voids) {
MyHelper mHelper = new MyHelper(context,null,null,1);
SQLiteDatabase database = mDatabaseHelper.getReadableDatabase();
String Name;
int count = 0;
Cursor c = mHelper.getRafData();
while(c.moveToNext()){
//Database codes
publishProgress(new RafTask(Name,"","",String.valueOf(count),"",""));
return null;
}
#Override
protected void onProgressUpdate(RafTask... value) {
raftask.add(value[0]);
recycler.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Void aVoid) {
progressBar.setVisibility(View.GONE);
Log.d(TAG, "fragment text pass: " + am);
}
public static void setFilter(ArrayList<RafTask> newList){
// newList = newLists;
raftask = new ArrayList<>();
raftask.addAll(newList);
recycler.notifyDataSetChanged();
}
}
And for the Rafadapter.java
public class RafRecycler extends RecyclerView.Adapter<RafRecycler.MyViewHolder> {
private static ArrayList<RafTask> rafTasks = new ArrayList<>();
public RafRecycler(ArrayList<RafTask> rafTasks){
this.rafasks = rafTasks;
}
#Override
public RafRecycler.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.raw_rafs,parent,false);
return new RafRecycler.MyViewHolder(view);
}
#Override
public void onBindViewHolder(ClientRecycler.MyViewHolder holder, int position) {
holder.name.setText(rafTasks.get(position).get_raftaskname());
holder.id.setText(String.valueOf(rafTasks.get(position).get_raftaskid())+".");
// holder.id.setText(String.valueOf("->"));
holder.m = rafTasks.get(position).get_raftaskid();
}
#Override
public int getItemCount() {
return clientTasks.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView id,name;
String m;
public MyViewHolder(View itemView) {
super(itemView);
id = itemView.findViewById(R.id.txt_id);
name = itemView.findViewById(R.id.txt_name);
m=itemView.toString();
final MyDatabaseHelper mDatabaseHelper = new MyDatabaseHelper(itemView.getContext(),null,null,1);
final boolean clicked = false;
name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String names = name.getText().toString();
Cursor c = mHelper.getClientItemID(names);
int itemID = -1;
String email = "";
String address = "";
String shipaddress = "";
String number = "";
while (c.moveToNext()){
//Chech here for the codes to edit all plus numbers
//
//
itemID = c.getInt(0);
address =c.getString(4);
number =c.getString(2);
shipaddress =c.getString(5);
email =c.getString(3);
}
if(itemID >-1){
Log.d(TAG, "onItemClick: The id is: " + itemID);
Log.d(TAG, "onItemClick: The desc is: " + address);
Log.d(TAG, "onItemClick: The price is: " + shipaddress);
Intent editScreenIntent = new Intent(v.getContext(), EditClientActivity.class);
editScreenIntent.putExtra("id", itemID);
editScreenIntent.putExtra("name", names);
editScreenIntent.putExtra("number", number);
editScreenIntent.putExtra("address", address);
editScreenIntent.putExtra("email", email);
editScreenIntent.putExtra("shipaddress", shipaddress);
v.getContext().startActivity(editScreenIntent);
((MainActivity) v.getContext()).overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left);
}else{
Toast.makeText(v.getContext(),"No idd clicked", Toast.LENGTH_SHORT).show();
}
}
});
}
}
public void setFilter(ArrayList<ClientTask> newList){
clientTasks = new ArrayList<>();
clientTasks.addAll(newList);
notifyDataSetChanged();
}
}
And lastly my fragment.java
public class ClientFragment extends Fragment implements SearchView.OnQueryTextListener {
private static final String TAG = "ListDataActivity";
MyDatabaseHelper mDatabaseHelper;
private ProgressBar progressBar;
private RecyclerView recyclerView;
public static SearchView searchView;
static String am;
private MenuItem menua;
public static ArrayList<ClientTask> newList;
RecyclerView.LayoutManager layoutManager;
public BackgroundAsync backgroundAsync;
private ArrayList<ClientTask> clienttask = new ArrayList<>();
ClientRecycler recycler;
private ListView mListView;
Button opencon;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public ClientFragment() {
// Required empty public constructor
}
public static ClientFragment newInstance(String param1, String param2) {
ClientFragment fragment = new ClientFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onPrepareOptionsMenu(Menu menu){
am="asdf";
MenuItem menuItem = menu.findItem(R.id.mysearchbtn);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(this);
Log.d(TAG, "onCreateFragment ");
super.onPrepareOptionsMenu(menu);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
if (getArguments() != null) {
setRetainInstance(true);
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_client, container, false);
progressBar = view.findViewById(R.id.progressbar);
recyclerView = view.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recycler = new ClientRecycler(clienttask);
opencon = view.findViewById(R.id.opencon);
opencon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), AddClient.class);
startActivity(intent);
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
// Toast.makeText(context, " Off", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
newText = newText.toLowerCase();
newList = new ArrayList<>();
for (ClientTask clientTask : clienttask) {
String name = clientTask.get_clienttaskname().toLowerCase();
if (name.contains(newText)) {
Log.d(TAG, "u get any: "+ name);
newList.add(clientTask);
}else{
Log.d(TAG, "we aint got shit: "+ name);
}
}
Log.d(TAG, "the usual fail ");
recyclerView.setAdapter(recycler);
return true;
}
void filter(String text){
ArrayList<ClientTask> newList = new ArrayList();
for (ClientTask c : clienttask) {
// String name = clientTask.get_clienttaskname().toLowerCase();
if (c.get_clienttaskname().contains(text)) {
newList.add(c);
}
Log.d(TAG, "the usual fail ");
BackgroundAsync.setFilter(newList);
recyclerView.setAdapter(recycler);
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
#Override
public void onResume() {
super.onResume();
new BackgroundAsync(recyclerView,progressBar,getActivity(),newList).execute();
}
}
Some parts of my code may be quite unecessary to solve my problem, but I've tried so many fixes that didn't work and as a result, I have some weird looking implementations.Sorry for the trouble and again, thanks for thew help.
I managed to solve the problem by Moving the Async task class into the Fragment class So they share the same variables. I cleared all the input in the constructor so it became new BackgroundBsync().execute();. That solved it and I am now able to search all the data with a separate method i made in the Rafadapter class. the codes are below.
public void setFilter(ArrayList<ClientTask> newList){
clientTasks = new ArrayList<>();
clientTasks.addAll(newList);
notifyDataSetChanged();
}
so all i needed to add in my onQueryTextChange was to add a few lines of code
newText = newText.toLowerCase();
ArrayList<ClientTask> newList = new ArrayList();
for (ClientTask c : clienttask) {
String name = c.get_clienttaskname().toLowerCase();
if (name.contains(newText)) {
newList.add(c);
}
Log.d(TAG, "the usual fail ");
}
recycler.setFilter(newList);
return true;
And it solved my problem. Please note that RafAdapter is the same as ClientRecycler.
Related
I'm trying to use OnItemClick to display details in a user profile page and I still have this error:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at fr.ousoft.suiviemedsbox.ScrollingActivity.OnItemClick(**ScrollingActivity.java:102**)
at fr.ousoft.suiviemedsbox.UsersAdapter$AdapterVH$1.onClick(**UsersAdapter.java:115**)
Here is my Activity code
public class ScrollingActivity extends AppCompatActivity implements UsersAdapter.OnItemClickListener {
public static final String EXTRA_CREATOR_NOM = "Nom";
public static final String EXTRA_CREATOR_PRENOM = "Prenom";
public static final String EXTRA_CREATOR_TEL = "Tel";
public static final String EXTRA_CREATOR_EMAIL = "Email";
public static final String EXTRA_CREATOR_ETABLISSEMENT = "Etablissement";
public static final String EXTRA_CREATOR_TYPE = "Type";
public static final String EXTRA_CREATOR_ACTIVE = "Active";
RecyclerView recyclerView;
ApiInterface apiInterface;
UsersAdapter usersAdapter;
ArrayList<User> mListe = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
CollapsingToolbarLayout toolBarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
toolBarLayout.setTitle(getTitle());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ScrollingActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
recyclerView = findViewById(R.id.recyclerViewList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
usersAdapter = new UsersAdapter();
fetchUsers();
}
public void fetchUsers(){
apiInterface = ApiClient.getRetrofitInstance().create(ApiInterface.class);
Call<List<User>> call = apiInterface.getAllUsers();
call.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
if (response.isSuccessful()){
List<User> users = response.body();
usersAdapter.setData(users);
usersAdapter.setOnItemClickListener(ScrollingActivity.this);
recyclerView.setAdapter(usersAdapter);
}
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
Log.e("success", t.getLocalizedMessage());
}
});
}
#Override
public void OnItemClick(int position) {
Intent detailIntent = new Intent(this,DetailActivity.class);
User clickedUser = mListe.get(position);
detailIntent.putExtra(EXTRA_CREATOR_NOM, clickedUser.getNom());
detailIntent.putExtra(EXTRA_CREATOR_PRENOM, clickedUser.getPrenom());
detailIntent.putExtra(EXTRA_CREATOR_TEL, clickedUser.getTel());
detailIntent.putExtra(EXTRA_CREATOR_EMAIL, clickedUser.getEmail());
detailIntent.putExtra(EXTRA_CREATOR_ETABLISSEMENT, clickedUser.getEtablissement());
detailIntent.putExtra(EXTRA_CREATOR_TYPE, clickedUser.getType());
detailIntent.putExtra(EXTRA_CREATOR_ACTIVE, clickedUser.getActive());
startActivity(detailIntent);
}
}
Adapter:
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.AdapterVH>{
private List<User> userList;
private Context context;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void OnItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public UsersAdapter(){
}
public void setData(List<User> userList){
this.userList = userList;
notifyDataSetChanged();
}
#NonNull
#Override
public AdapterVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
return new UsersAdapter.AdapterVH(LayoutInflater.from(context).inflate(R.layout.item_list,parent,false));
}
#SuppressLint("ResourceAsColor")
#Override
public void onBindViewHolder(#NonNull AdapterVH holder, int position) {
User user = userList.get(position);
String nom = user.getNom();
String email = user.getEmail();
String etab = user.getEtablissement();
String active = user.getActive();
String prenom = user.getPrenom();
holder.txtNom.setText(nom);
if (nom == null) {
holder.txtNom.setText("Aucun Nom");
}
holder.txtEmail.setText(email);
if (email == null) {
holder.txtEmail.setText("Aucun Email");
}
holder.txtEttab.setText(etab);
if (etab == null) {
holder.txtEttab.setText("Aucun Etablissement");
}
holder.txtPrenom.setText(prenom);
if (prenom == null) {
holder.txtPrenom.setText("Aucun Prenom");
}
if (active == null) {
holder.ActiveDesactive.setText(R.string.desact);
}else {
holder.ActiveDesactive.setText(R.string.activ);
}
}
#Override
public int getItemCount() {
return userList.size();
}
public class AdapterVH extends RecyclerView.ViewHolder{
TextView txtNom;
TextView txtPrenom;
TextView txtEmail;
TextView txtEttab;
Button ActiveDesactive;
public AdapterVH(#NonNull View itemView) {
super(itemView);
txtNom = itemView.findViewById(R.id.NomUser);
txtPrenom = itemView.findViewById(R.id.PrenomUser);
txtEmail = itemView.findViewById(R.id.EmailUser);
txtEttab = itemView.findViewById(R.id.EtabUser);
ActiveDesactive = itemView.findViewById(R.id.ActiveDesavtive);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null){
int positions = getAdapterPosition();
if (positions != RecyclerView.NO_POSITION){
mListener.OnItemClick(positions);
}
}
}
});
}
}
}
You never fill mListe with any content. If you search for mListe. the only match you get is mListe.get. You have no invocations of mListe.add or mListe.addAll. What you do instead is set a list from a response directly into the adapter:
if (response.isSuccessful()){
// Here is the error
List<User> users = response.body();
usersAdapter.setData(users);
usersAdapter.setOnItemClickListener(ScrollingActivity.this);
recyclerView.setAdapter(usersAdapter);
}
What should be done instead is the following:
Clear mListe from any previous content;
Fill with new content;
Set new data to the adapter.
if (response.isSuccessful()){
mListe.clear();
mListe.addAll(response.body());
usersAdapter.setData(mListe);
}
I have removed a few lines from this if-statement and moved them into the onCreate. They should be called only once, there is no benefit setting the same adapter and click listener if you call fetchUsers() again.
#Override
protected void onCreate(Bundle savedInstanceState) {
...
usersAdapter = new UsersAdapter();
usersAdapter.setOnItemClickListener(this);
recyclerView.setAdapter(usersAdapter);
fetchUsers();
}
you are not adding anything in ArrayList<User> mListe = new ArrayList<>();
you should add values before implementing any action,
try this
if (response.isSuccessful()){
List<User> users = response.body();
mListe.addAll(users);
usersAdapter.setData(users);
usersAdapter.setOnItemClickListener(ScrollingActivity.this);
recyclerView.setAdapter(usersAdapter);
}
This is my adapter for recycle view
CategoryAdapter Class
public class CategoryRAdapter extends RecyclerView.Adapter<CategoryRAdapter.MyViewHolder> {
private Context mcontext;
private List<Food> mData;
RequestOptions option;
public CategoryRAdapter(Context mcontext, List<Food> mData) {
this.mcontext = mcontext;
this.mData = mData;
option = new RequestOptions().centerCrop().placeholder(R.drawable.loading_shape).error(R.drawable.loading_shape);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Food current = mData.get(position);
holder.tv_Name.setText(current.getName());
holder.tv_Rating.setText(current.getRating());
holder.tv_Descip.setText(current.getDescrip());
holder.tv_Category.setText(current.getCateg());
Glide.with(mcontext).load(mData.get(position).getImages()).apply(option).into(holder.img_Thumbnail);
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_Name;
TextView tv_Rating;
TextView tv_Descip;
TextView tv_Category;
ImageView img_Thumbnail;
public MyViewHolder(View itemView) {
super(itemView);
tv_Name = itemView.findViewById(R.id.food_name);
tv_Rating = itemView.findViewById(R.id.rating);
tv_Descip = itemView.findViewById(R.id.desc);
tv_Category = itemView.findViewById(R.id.category);
img_Thumbnail = itemView.findViewById(R.id.thumbnail);
}
}
}
This is my model
Food Class
public class Food {
String Name;
String Images;
String Descrip;
String Rating;
String Categ;
public Food() {
}
public Food(String name, String images, String descrip, String rating, String categ) {
this.Name = name;
this.Images = images;
this.Descrip = descrip;
this.Rating = rating;
this.Categ = categ;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImages() {
return Images;
}
public void setImages(String images) {
Images = images;
}
public String getDescrip() {
return Descrip;
}
public void setDescrip(String descrip) {
Descrip = descrip;
}
public String getRating() {
return Rating;
}
public void setRating(String rating) {
Rating = rating;
}
public String getCateg() {
return Categ;
}
public void setCateg(String categ) {
Categ = categ;
}
}
My mian activity
CategoryActivity Class
public class CategoriaActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<Food> dbObjects;
private RecyclerView.Adapter adapter;
private AlertDialog.Builder dialogBuilder;
private AlertDialog dialog;
TextView l_nombre,l_precio;
Button l_finalizar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categoria);
recyclerView = findViewById(R.id.recycle_id);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
dbObjects = new ArrayList<>();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Category");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objList, ParseException e) {
if (e == null) {
for (ParseObject obj : objList) {
Food food = new Food();
food.setName(obj.getString("Name"));
food.setDescrip(obj.getString("Descrip"));
food.setRating(obj.getString("Rating"));
food.setCateg(obj.getString("Categ"));
food.setImages(obj.getString("Images"));
dbObjects.add(food);
}
} else {
FancyToast.makeText(CategoriaActivity.this, "Error: " + e.getMessage(), FancyToast.LENGTH_SHORT, FancyToast.ERROR, true).show();
}
}
});
adapter = new CategoryRAdapter(this, dbObjects);
recyclerView.setAdapter(adapter);
FloatingActionButton fab = findViewById(R.id.shoppingFlot);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
carritopop();
}
});
}
private void carritopop() {
dialogBuilder = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.pop_cart,null);
l_finalizar = view.findViewById(R.id.l_finalizar);
l_finalizar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pago();
}
});
dialogBuilder.setView(view);
dialog = dialogBuilder.create();
dialog.show();
}
private void pago() {
Intent intent = new Intent(CategoriaActivity.this, PagoActivity.class);
startActivity(intent);
}
}
I dont know whats wrong with the code, the recycle view aint working, it aint showing any items, i would really appreciate if someone could help me out and notice something wrong in my code
Call adapter.notifyDataSetChanged() in your query done callback, this will notify the adapter that the list has changed. This is happening because when you set the adapter, the list was empty as the query was running in background. Once it completes, you have to tell the adapter that new data has been added to list:
if (e == null) {
for (ParseObject obj : objList) {
...
}
adapter.notifyDataSetChanged();
}
Also, create your adapter before you send the query otherwise it may result in NullPointerException in case data is loaded before the next statement executes (highly unlikely but never hurts to be safe).
dbObjects = new ArrayList<>();
adapter = new CategoryRAdapter(this, dbObjects);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Category");
I recommend you to use RxJava2 to user asynchronous methods, it's awesome... And about the problem, maybe your data is not ready when you're already creating the adapter with the ArrayList.
Try to move the recyclerView.setAdapter() to inside the FindCallback after create the Food Objects.
When in SettingsActivity switch on to show only selected with checkbox and my List contains near 30 items, recyclerview scrolls normally, but when I use List with 900 items - recyclerview scrolls with freezes. Where my way to update recyclerview is wrong?
Android Studio log:
E/RecyclerView: No adapter attached; skipping layout
I/Choreographer: Skipped 68 frames! The application may be doing too much work on its main thread.
BikesAdapter:
public class BikesAdapter extends RecyclerView.Adapter<BikesAdapter.BikesViewHolder>{
private static final String PREFS_NAME = "bikes_prefs";
public static List<Categories> categories;
private Context context;
public BikesAdapter(Context context) {
this.context = context;
notifyDataSetChanged();
}
#Override
public BikesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new BikesViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.list_bikes, parent, false));
}
#Override
public void onBindViewHolder(final BikesViewHolder holder, final int position) {
final SharedPreferences setFavoritesCnB = FragmentBikesListXT.context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
boolean isFavoriteChB = setFavoritesCnB.getBoolean(categories.get(position).title, false);
holder.cbStars.setChecked(isFavoriteChB);
holder.cbStars.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = setFavoritesCnB.edit();
editor.putBoolean(categories.get(position).title, holder.cbStars.isChecked());
editor.apply();
if (holder.cbStars.isChecked()) {
openDBHelper.save(position);
Constants.CATEGORIES.add(categories.get(position));
} else {
openDBHelper.delete(position);
Constants.CATEGORIES.remove(categories.get(position));
}
}
});
if (checkSwitch) {
if (!isFavoriteChB) {
holder.cardView.setVisibility(View.GONE);
} else {
holder.textTitle.setText(categories.get(position).title);
}
} else holder.textTitle.setText(categories.get(position).title);
holder.textTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(categories.get(position).link));
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return categories.size();
}
public class BikesViewHolder extends RecyclerView.ViewHolder {
private CardView cardView;
private CheckBox cbStars;
private TextView textTitle;
public BikesViewHolder(View itemView) {
super(itemView);
cardView = (CardView) itemView.findViewById(R.id.cardView);
cbStars = (CheckBox) itemView.findViewById(R.id.cbStars);
textTitle = (TextView) itemView.findViewById(R.id.tv_title_bike);
}
}
}
Fragment with recyclerview:
public class FragmentBikesListXT extends Fragment {
public static RecyclerView rvBikes;
public static ProgressBar pbBikes;
public static Context context;
public static CreateDBHelper dbHelper;
public static OpenDBHelper openDBHelper;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FrameLayout layout = (FrameLayout) inflater.inflate(R.layout.fragment_bikes_list_xt, container, false);
rvBikes = (RecyclerView) layout.findViewById(R.id.rvBikes);
pbBikes = (ProgressBar) layout.findViewById(R.id.pbBikes);
SharedPreferences setSwitch = getActivity().getSharedPreferences(PREFS_LIST, MODE_PRIVATE);
checkSwitch = setSwitch.getBoolean("NameOfThingToSave", false);
context = getContext();
dbHelper = new CreateDBHelper(this.getActivity());
openDBHelper = new OpenDBHelper();
initIO(Constants.URL_FULL_LIST);
return layout;
}
public void initIO(String url) {
ParseXT.initializeData(url);
rvBikes.setHasFixedSize(true);
rvBikes.setLayoutManager(new GridLayoutManager(this.getActivity(), 1));
}
}
SettingsActivity:
public class SettingsActivity extends AppCompatActivity {
private Switch mSwitch;
public static boolean checkSwitch;
public static final String PREFS_LIST = "list_prefs";
public static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mSwitch = (Switch) findViewById(R.id.switch_list);
SharedPreferences setSwitch = getSharedPreferences(PREFS_LIST, MODE_PRIVATE);
mSwitch.setChecked(setSwitch.getBoolean("NameOfThingToSave", false));
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked){
checkSwitch = true;
SharedPreferences.Editor editor = getSharedPreferences(PREFS_LIST, MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", true);
editor.commit();
}else{
checkSwitch = false;
SharedPreferences.Editor editor = getSharedPreferences(PREFS_LIST, MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", false);
editor.commit();
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
return true;
}
finish();
return super.onOptionsItemSelected(item);
}
}
OpenDBHelper:
public class OpenDBHelper implements IDBHelper {
private SQLiteDatabase db;
#Override
public void read() {
db = FragmentBikesListXT.dbHelper.getWritableDatabase();
BikesAdapter.categories.clear();
Cursor c = db.query(Constants.TABLE_BIKE, null, null, null, null, null, null);
if (c.moveToFirst()) {
int titleColIndex = c.getColumnIndex(Constants.FIELD_TITLE);
int linkColIndex = c.getColumnIndex(Constants.FIELD_LINK);
do {
BikesAdapter.categories.add(new Categories(
c.getString(titleColIndex),
c.getString(linkColIndex)));
Log.d("DBHelper", "READ ID = " + c.getString(titleColIndex));
} while (c.moveToNext());
} else
c.close();
}
#Override
public void save(int position) {
ContentValues cv = new ContentValues();
db = FragmentBikesListXT.dbHelper.getWritableDatabase();
cv.put(Constants.FIELD_TITLE, BikesAdapter.categories.get(position).title);
cv.put(Constants.FIELD_LINK, BikesAdapter.categories.get(position).link);
long size = db.insert(Constants.TABLE_BIKE, null, cv);
Log.d("DBHelper", "SAVE row inserted, size " + size + " ID = , " + BikesAdapter.categories.get(position).title);
FragmentBikesListXT.dbHelper.close();
}
#Override
public void delete(int position) {
db = FragmentBikesListXT.dbHelper.getWritableDatabase();
String[] whereArgs = {String.valueOf(BikesAdapter.categories.get(position).title)};
db.delete(Constants.TABLE_BIKE, Constants.FIELD_TITLE + " = ?", whereArgs);
Log.d("DBHelper", "DELETE ID = " + BikesAdapter.categories.get(position).title);
db.close();
}
}
And parser class:
public class ParseXT {
private static Elements titleTxt;
private static Elements linkTxt;
private static ArrayList<String> titleList = new ArrayList<>();
private static ArrayList<String> linkList = new ArrayList<>();
public static BikesAdapter bikesAdapter = new BikesAdapter(FragmentBikesListXT.context);
public static void initializeData(String url) {
new NewTreadParsed(url).execute();
}
public static class NewTreadParsed extends AsyncTask<List<Categories>, Void, List<Categories>> {
private String url;
public NewTreadParsed(String url) {
this.url = url;
}
#Override
protected List<Categories> doInBackground(List<Categories>... params) {
Document doc;
List<Categories> categories = new ArrayList<>();
try {
doc = Jsoup.connect(url).get();
titleTxt = doc.select(".topictitle");
linkTxt = doc.select(".a[href]");
titleList.clear();
linkList.clear();
for (Element contents : titleTxt) {
titleList.add(contents.text());
}
for (Element contents1 : titleTxt) {
Element element = contents1.select("a[href]").first();
linkList.add(element.attr("abs:href"));
}
}
catch (IOException e){
e.printStackTrace();
}
for (int i = 0; i < titleList.size(); i++) {
categories.add(new Categories(titleList.get(i), linkList.get(i)));
}
return categories;
}
#Override
protected void onPostExecute(List<Categories> categories) {
super.onPostExecute(categories);
FragmentBikesListXT.pbBikes.setVisibility(ProgressBar.INVISIBLE);
BikesAdapter.categories = categories;
FragmentBikesListXT.rvBikes.setAdapter(bikesAdapter);
}
}
}
Use notifyDataSetChanged()
If you are writing an adapter it will always be more efficient to use the more specific change events if you can. Rely on notifyDataSetChanged()
I am creating an app where a list of hotels will be shown, all the data is coming from MySQL using JSON and PHP, I created the custom list view by extending the base adapter to a custom one, but I am not able to implement a OnItemClickListener for the listview, as i want to show the Hotel Name of that row in Toast whenever the user clicks on a row of list view. I tried various example available on internet, but i just doesn't work.
Adapter
public class CustomListAdapterHotel extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<WorldsBillionaires> billionairesItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapterHotel(Activity activity, List<WorldsBillionaires> billionairesItems) {
this.activity = activity;
this.billionairesItems = billionairesItems;
}
#Override
public int getCount() {
return billionairesItems.size();
}
#Override
public Object getItem(int location) {
return billionairesItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_hotel, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
//NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
TextView hotel_name = (TextView) convertView.findViewById(R.id.hotel_name);
TextView zone = (TextView) convertView.findViewById(R.id.zone);
TextView contact_person = (TextView) convertView.findViewById(R.id.contact_person);
TextView contact_number = (TextView) convertView.findViewById(R.id.contact_number);
TextView btc_direct = (TextView) convertView.findViewById(R.id.btcdirect);
// getting billionaires data for the row
WorldsBillionaires m = billionairesItems.get(position);
// name
hotel_name.setText(String.valueOf(m.getHotel_Name()));
zone.setText(String.valueOf(m.getHotel_Zone()));
contact_person.setText(String.valueOf(m.getContact_Person()));
contact_number.setText(String.valueOf(m.getContact_Number()));
btc_direct.setText(String.valueOf(m.getBtc_Direct()));
return convertView;
}
}
Model
public class WorldsBillionaires {
private String hotel_name,hotel_zone,contact_person,contact_number,btc_direct;
public WorldsBillionaires(String hotel_name, String hotel_zone, String contact_person, String contact_number, String btc_direct) {
this.hotel_name=hotel_name;
this.hotel_zone=hotel_zone;
this.contact_person=contact_person;
this.contact_number=contact_number;
this.btc_direct=btc_direct;
}
public WorldsBillionaires() {
}
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public String getHotel_Name() {
return hotel_name;
}
public void setHotel_Name(String hotel_name) {
this.hotel_name = hotel_name;
}
public String getHotel_Zone() {
return hotel_zone;
}
public void setHotel_Zone(String hotel_zone) {
this.hotel_zone = hotel_zone;
}
public String getContact_Person() {
return contact_person;
}
public void setContact_Person(String contact_person) {
this.contact_person = contact_person;
}
public String getContact_Number() {
return contact_number;
}
public void setContact_Number(String contact_number) {
this.contact_number = contact_number;
}
public String getBtc_Direct() {
return btc_direct;
}
public void setBtc_Direct(String btc_direct) {
this.btc_direct = btc_direct;
}
}
Main Activity
public class ShowHotel extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
// Billionaires json url
private ProgressDialog pDialog;
private List<WorldsBillionaires> worldsBillionairesList = new ArrayList<WorldsBillionaires>();
private ListView listView;
private CustomListAdapterHotel adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_hotel);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapterHotel(this, worldsBillionairesList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest billionaireReq = new JsonArrayRequest("http://192.168.247.1/AdminBihar/getHotel.php?zone="+methods.zone,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
WorldsBillionaires worldsBillionaires = new WorldsBillionaires();
worldsBillionaires.setHotel_Name(obj.getString("hotel_name"));
worldsBillionaires.setThumbnailUrl(obj.getString("image"));
worldsBillionaires.setHotel_Zone(obj.getString("zone"));
worldsBillionaires.setContact_Person(obj.getString("contact_person"));
worldsBillionaires.setContact_Number(obj.getString("contact_number"));
worldsBillionaires.setBtc_Direct(obj.getString("btc_direct"));
// adding Billionaire to worldsBillionaires array
worldsBillionairesList.add(worldsBillionaires);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(billionaireReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
so after you get json data, in activity that shows your list do something like this:
public class DisplayListView extends AppCompatActivity {
ListView listView;
protected void onCreate(){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_list_view);
listView = (ListView) findViewById(R.id.listview);
hotelAdapter = new CustomListAdapterHotel (this, R.layout.row_layout);
listView.setAdapter(hotelAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Model stuff = (Model) hotelAdapter.getItem(position);
String hotelName = stuff.getHotel_Name();
Toast.makeText(getApplicationContext(), hotelName, Toast.LENGTH_SHORT).show();
}
});
there, this worked for me :)
i am using eclipse.
Basically what i am trying to implement is that , that i have a gridView which is fetching images from mysql database dynamically using JSON.
Now , instead of gridview i want to show them as coverflow view.
I have searched through the internet , but was not able to find any library or example for dynamic images , i only found for static images stored in the app itself and not on external database.
My code are as follows:-
MainActivity.java:-
public class MainActivity extends Activity implements OnClickListener {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://eventassociate.com/wedding/photomania";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private PullToRefreshGridView mPullRefreshGridView;
private GridView gridView;
private CustomListAdapter adapter;
ImageButton blackcapture;
private static int RESULT_LOAD_IMAGE = 1;
String picturePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.gallary_activity_main);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.list);
gridView = mPullRefreshGridView.getRefreshableView();
mPullRefreshGridView.setOnRefreshListener(new OnRefreshListener2<GridView>() {
#Override
public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
adapter.notifyDataSetChanged();
gridView.setAdapter(adapter);
gridView.invalidateViews();
mPullRefreshGridView.onRefreshComplete();
}
adapter = new CustomListAdapter(this, movieList);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Movie m5 = movieList.get(position);
Intent i = new Intent(getApplicationContext(),
FullImageActivity.class);
i.putExtra("movieobject", m5);
startActivity(i);
}
});
Adapter Class:-
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.gallary_list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
// ...............................................
TextView title = (TextView) convertView.findViewById(R.id.title);
// getting movie data for the row
Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
return convertView;
}
Movie.java:-
public class Movie implements Parcelable{
private String title,thumbnailUrl;
public Movie() {
// TODO Auto-generated constructor stub
}
public Movie(String name, String thumbnailUrl
) {
this.title = name;
this.thumbnailUrl = thumbnailUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = "http://eventassociate.com/wedding/"+thumbnailUrl;
}
// Parcelling part
public Movie(Parcel in){
String[] data = new String[2];
in.readStringArray(data);
this.title = data[0];
this.thumbnailUrl = data[1];
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.title,
this.thumbnailUrl,
});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
I successfully implemented this as GridView , but i am facing trouble in implementing this as coverflow design or something like that.
I searched on the net and i find this code , but only for static images:-
public class SimpleExample extends Activity {
// =============================================================================
// Child views
// =============================================================================
private FancyCoverFlow fancyCoverFlow;
// =============================================================================
// Supertype overrides
// =============================================================================
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.fancyCoverFlow = (FancyCoverFlow) this.findViewById(R.id.fancyCoverFlow);
this.fancyCoverFlow.setAdapter(new FancyCoverFlowSampleAdapter());
this.fancyCoverFlow.setUnselectedAlpha(1.0f);
this.fancyCoverFlow.setUnselectedSaturation(0.0f);
this.fancyCoverFlow.setUnselectedScale(0.5f);
this.fancyCoverFlow.setSpacing(50);
this.fancyCoverFlow.setMaxRotation(0);
this.fancyCoverFlow.setScaleDownGravity(0.2f);
this.fancyCoverFlow.setActionDistance(FancyCoverFlow.ACTION_DISTANCE_AUTO);
}
// =============================================================================
// Private classes
// =============================================================================
}
Adapter.java:-
public class FancyCoverFlowSampleAdapter extends FancyCoverFlowAdapter {
// =============================================================================
// Private members
// =============================================================================
private int[] images = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5, R.drawable.image6,};
// =============================================================================
// Supertype overrides
// =============================================================================
#Override
public int getCount() {
return images.length;
}
#Override
public Integer getItem(int i) {
return images[i];
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getCoverFlowItem(int i, View reuseableView, ViewGroup viewGroup) {
ImageView imageView = null;
if (reuseableView != null) {
imageView = (ImageView) reuseableView;
} else {
imageView = new ImageView(viewGroup.getContext());
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setLayoutParams(new FancyCoverFlow.LayoutParams(300, 400));
}
imageView.setImageResource(this.getItem(i));
return imageView;
}
}
Can someone help me , in solving my problem.
Thanks.
My final code with coverflow:-
MainActivity:-
public class MainActivity extends Activity implements OnClickListener {
// Log tag
private static final String TAG = album.MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://eventassociate.com/wedding/androidadminimages";
private ProgressDialog pDialog;
private List<Moviealbum> movieList = new ArrayList<Moviealbum>();
private FancyCoverFlow fancyCoverFlow;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.album_activity_main);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
this.fancyCoverFlow = (FancyCoverFlow) this.findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
this.fancyCoverFlow.setAdapter(new CustomListAdapter(this, movieList));
this.fancyCoverFlow.setUnselectedAlpha(1.0f);
this.fancyCoverFlow.setUnselectedSaturation(0.0f);
this.fancyCoverFlow.setUnselectedScale(0.5f);
this.fancyCoverFlow.setSpacing(50);
this.fancyCoverFlow.setMaxRotation(0);
this.fancyCoverFlow.setScaleDownGravity(0.2f);
this.fancyCoverFlow.setActionDistance(FancyCoverFlow.ACTION_DISTANCE_AUTO);
fancyCoverFlow.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Moviealbum m5 = movieList.get(position);
Intent i = new Intent(getApplicationContext(),album.
FullImageActivity.class);
i.putExtra("movieobject", m5);
startActivity(i);
}
});
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Moviealbum movie = new Moviealbum();
movie.setTitle(obj.getString("no"));
movie.setThumbnailUrl(obj.getString("alinks"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue...................................
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
AdapterClass :-
public class CustomListAdapter extends FancyCoverFlowAdapter {
private Activity activity;
private LayoutInflater inflater;
List<Moviealbum> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Moviealbum> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getCoverFlowItem(int position, View reuseableView, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (reuseableView == null)
reuseableView = inflater.inflate(R.layout.gallary_list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) reuseableView
.findViewById(R.id.thumbnail);
// ...............................................
TextView title = (TextView) reuseableView.findViewById(R.id.title);
// getting movie data for the row
Moviealbum m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
return reuseableView;
}
The app runs fine , but after loading blank screen is shown with no images.
Logcat:-
Your issue isn't with the CoverFlow code, but rather where you're doing your network operation. On app load, begin your network request for your JSON payload, show a spinner to show the app is loading, and populate your Adapter once your images are loaded. I'm assuming you have network code already given your GridView implementation? Let me know if I've missed something. I hope that helps!
EDIT:
Once you've added images to your Adapter make sure you call notifyDataSetChanged() to tell your adapter to reload its views.
EDIT 2:
Look at this line here:
this.fancyCoverFlow.setAdapter(new CustomListAdapter(this, movieList));
You're passing a new CustomListAdapter rather than passing in your adapter variable. Try fixing that and let me know if it works.