RecyclerView shows nothing - android

I'm new in this android world. I'm currently working on android project i.e., music player but i got stopped at one point since my recycler view doesn't display anything which is supposed to be a list of songs.
I even checked my logcat but cannot figured out whether the data is binding or not.Any kind of help will be grateful.
SongListAdapter.java
public class SongListAdapter extends RecyclerView.Adapter<SongListAdapter.MyViewHolder> {
ArrayList<SongDetailsJDO> mSongDetailsJDOs;
LayoutInflater mLayoutInflater;
Context mContext;
private static final String TAG = "SongListAdapter";
private boolean mIsSongPlaying = false;
private String mCurrentSongId = "-1";
public SongListAdapter(Context context, ArrayList<SongDetailsJDO> pSongDetailsJDOs) {
mContext = context;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSongDetailsJDOs = pSongDetailsJDOs;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View lView = mLayoutInflater.inflate(R.layout.recycler_view_item, parent, false);
return new MyViewHolder(lView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Uri lUri = null;
if (mSongDetailsJDOs.get(position).getAlbumId() != null && !mSongDetailsJDOs.get(position).getAlbumId().equals("")) {
lUri = ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), Long.parseLong(mSongDetailsJDOs.get(position).getAlbumId()));
Picasso.with(mContext).load(lUri).resize(100, 100).placeholder(R.drawable.placeholder).into(holder.albumImageIV);
} else
holder.albumImageIV.setImageResource(R.drawable.placeholder);
String lTrackName = mSongDetailsJDOs.get(position).getTitle();
if (lTrackName != null)
holder.trackNameTV.setText(lTrackName.trim());
else
holder.trackNameTV.setText("<Unknown>");
String lAlbumName = mSongDetailsJDOs.get(position).getAlbumName();
if (lAlbumName != null)
holder.albumAndArtistDetailsTV.setText(lAlbumName.trim());
else
holder.albumAndArtistDetailsTV.setText("<Unknown>");
if (mSongDetailsJDOs.get(position).getFavouriteStatus() == 1)
holder.favouriteIV.setImageResource(R.drawable.fav);
else
holder.favouriteIV.setImageResource(R.drawable.fav_u);
// TODO: #holder.animationDrawable use it change Visibility and start (Animation)
if (mIsSongPlaying && mSongDetailsJDOs.get(position).getSongId().equals(mCurrentSongId)) {
holder.eqIv.setVisibility(View.VISIBLE);
holder.animationDrawable = (AnimationDrawable) holder.eqIv.getBackground();
holder.animationDrawable.start();
} else {
holder.eqIv.setVisibility(View.INVISIBLE);
}
}
#Override
public int getItemCount() {
if (mSongDetailsJDOs != null)
return mSongDetailsJDOs.size();
else
return 0;
}
/**
* Called when data is being updated in DB
*/
public void favChanged(int pPosition, int pFavStatus) {
mSongDetailsJDOs.get(pPosition).setFavouriteStatus(pFavStatus);
notifyItemChanged(pPosition);
}
/**
* View Holder class for Rec view
*/
class MyViewHolder extends RecyclerView.ViewHolder {
ImageView albumImageIV;
TextView trackNameTV;
TextView albumAndArtistDetailsTV;
ImageView favouriteIV;
ImageView eqIv;
AnimationDrawable animationDrawable;
MyViewHolder(View itemView) {
super(itemView);
albumImageIV = (ImageView) itemView.findViewById(R.id.album_artwork_iv);
trackNameTV = (TextView) itemView.findViewById(R.id.title_name_tv);
albumAndArtistDetailsTV = (TextView) itemView.findViewById(R.id.artist_author_name_tv);
favouriteIV = (ImageView) itemView.findViewById(R.id.fav_iv);
eqIv = (ImageView) itemView.findViewById(R.id.eq_iv);
}
}
/**
* Swap the data with the new JDO list
*
* #param pSongDetailsJDOs
*/
public void swapData(ArrayList<SongDetailsJDO> pSongDetailsJDOs) {
mSongDetailsJDOs = pSongDetailsJDOs;
notifyDataSetChanged();
}
/**
* Returns the list of currently loaded JDO's
* #return
*/
public List<SongDetailsJDO> getData() {
return mSongDetailsJDOs;
}
/**
* Gets the #{#link SongDetailsJDO} object at the specified position
* #param pPosition
* #return the {#link SongDetailsJDO} object
*/
public SongDetailsJDO getItemAtPosition(int pPosition) {
return mSongDetailsJDOs.get(pPosition);
}
/**
* Update Song Play status
* #param pStatus the status weather is playing or not
* #param lSongId the song id the playing song
*/
public void updateSongPlayStatus(boolean pStatus, String lSongId) {
mIsSongPlaying = pStatus;
mCurrentSongId = lSongId;
notifyDataSetChanged();
}
}
SongListActivity.java
public class SongsListActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>, SharedPreferences.OnSharedPreferenceChangeListener {
private RecyclerView mRecyclerView;
private SongListAdapter mAdapter;
private ArrayList<SongDetailsJDO> mSongDetailsJDOs;
private TextView mNoSongTV;
private static final int LOADER_ID = 101;
private int REQUEST_CODE = 102;
private static final String TAG = "SongsListActivity";
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mPrefEditor;
private SharedPreferences.OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener;
private FirebaseAnalytics mFirebaseAnalytics;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.rec_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(SongsListActivity.this));
mNoSongTV = (TextView) findViewById(R.id.no_song_tv);
mSongDetailsJDOs = new ArrayList<>();
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mPrefEditor = mSharedPreferences.edit();
mSharedPreferences.registerOnSharedPreferenceChangeListener(this);
FirebaseApp.initializeApp(this);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
loadData();
}
private void loadData() {
FirebaseCrash.report(new Exception("OMG An Exception"));
boolean lIsAppLoadingFirstTime = mSharedPreferences.getBoolean(getString(R.string.is_app_loading_first_time), true);
if (lIsAppLoadingFirstTime) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
} else {
mPrefEditor.putBoolean(getString(R.string.is_app_loading_first_time), false);
mPrefEditor.apply();
new LoadDataToDbBackground().execute();
// TODO: Create Loader here
}
} else {
loadDataToRecyclerView();
if (mSharedPreferences.getBoolean(getString(R.string.is_song_playing), false)) {
// TODO: Create Loader here
SongDetailsJDO lJDO = getSongJDO(mSharedPreferences.getString(getString(R.string.song_id), ""));
startActivityForResult(new Intent(SongsListActivity.this, PlayerActivity.class)
.putExtra(getString(R.string.song_jdo), lJDO), REQUEST_CODE);
}
}
}
private class LoadDataToDbBackground extends AsyncTask<Void, Integer, Void> {
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(SongsListActivity.this);
mProgressDialog.setMessage("Please Wait");
mProgressDialog.setTitle("Loading");
mProgressDialog.show();
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
mProgressDialog.dismiss();
super.onPostExecute(aVoid);
}
#Override
protected Void doInBackground(Void... params) {
CommonHelper lHelper = new CommonHelper();
lHelper.loadSongToDB(SongsListActivity.this);
runOnUiThread(new Runnable() {
#Override
public void run() {
loadDataToRecyclerView();
}
});
return null;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == 0) {
boolean lGranted = true;
for (int lResult : grantResults) {
if (lResult == PackageManager.PERMISSION_DENIED)
lGranted = false;
}
if (lGranted)
loadData();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
if (data != null && data.getExtras() != null && resultCode == PlayerActivity.RESULT_CODE) {
//if data changed reload the recyclerView
if (data.getBooleanExtra(getString(R.string.is_data_changed), false)) {
mSongDetailsJDOs = new SongDetailTable(this).getAllSongs();
mAdapter.swapData(mSongDetailsJDOs);
}
}
}
// updateCurrentSongIndication();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater lMenuInflater = getMenuInflater();
lMenuInflater.inflate(R.menu.menu_song_list, menu);
SearchManager lSearchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
SearchView lSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
lSearchView.setSearchableInfo(lSearchManager.getSearchableInfo(getComponentName()));
lSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
filterRecView(newText);
return true;
}
});
return true;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.TITLE + " ASC");
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
ArrayList<SongDetailsJDO> lSongDetailsNew = new ArrayList<>();
if (data.moveToFirst()) {
do {
lSongDetailsNew.add(new SongDetailsJDO(data.getString(data.getColumnIndex(MediaStore.Audio.Media.TITLE)),
data.getString(data.getColumnIndex(MediaStore.Audio.Media.ALBUM)),
data.getString(data.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)),
data.getString(data.getColumnIndex(MediaStore.Audio.Media._ID)),
data.getInt(data.getColumnIndex(MediaStore.Audio.Media.DURATION)), 0));
} while (data.moveToNext());
}
compareDataAndMakeChangesToDB(lSongDetailsNew);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
Log.d(TAG, "onWindowFocusChanged: ");
updateCurrentSongIndication();
}
private void updateCurrentSongIndication() {
if (mSharedPreferences.getBoolean(getString(R.string.is_song_playing), false)) {
mAdapter.updateSongPlayStatus(true, mSharedPreferences.getString(getString(R.string.song_id), ""));
mRecyclerView.smoothScrollToPosition(getPositionOfSongId(mSharedPreferences.getString(getString(R.string.song_id), "")));
} else {
if(mAdapter!=null)
mAdapter.updateSongPlayStatus(false, "-1");
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
updateCurrentSongIndication();
}
private void compareDataAndMakeChangesToDB(ArrayList<SongDetailsJDO> pSongDetailsNew) {
Log.d(TAG, "compareDataAndMakeChangesToDB: Called ============");
ArrayList<String> lSongIdsToBeDeleted = new ArrayList<>();
for (SongDetailsJDO lSongDetailsJDO : mSongDetailsJDOs) {
lSongIdsToBeDeleted.add(lSongDetailsJDO.getSongId());
}
ArrayList<SongDetailsJDO> lNewSongsToBeAdded = new ArrayList<>();
for (SongDetailsJDO lSongDetailsJDO : pSongDetailsNew) {
if (lSongIdsToBeDeleted.contains(lSongDetailsJDO.getSongId())) {
lSongIdsToBeDeleted.remove(lSongDetailsJDO.getSongId());
} else
lNewSongsToBeAdded.add(lSongDetailsJDO);
}
if (lSongIdsToBeDeleted.size() > 0 || lNewSongsToBeAdded.size() > 0) {
SongDetailTable lSongDetailTable = new SongDetailTable(this);
lSongDetailTable.removeSongsForIds(lSongIdsToBeDeleted);
lSongDetailTable.insertSongs(lNewSongsToBeAdded);
loadDataToRecyclerView();
//
// SongPlayerService lSongPlayerService = SongPlayerService.getRunningInstance();
// if (lSongPlayerService != null)
// lSongPlayerService.dataChanged();
}
}
public void onFavClick(View pView) {
//Firebase Logging
Bundle lBundle = new Bundle();
lBundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY,"Favourite Clicked");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM,lBundle);
int lPosition = mRecyclerView.getChildLayoutPosition((View) pView.getParent());
SongDetailsJDO lSongDetailsJDO = mAdapter.getItemAtPosition(lPosition);
String lSongId = lSongDetailsJDO.getSongId();
SongDetailTable lSongDetailTable = new SongDetailTable(this);
int lNewFavStatus = lSongDetailsJDO.getFavouriteStatus() == 0 ? 1 : 0;
lSongDetailTable.setFavouriteStatus(lSongId, lNewFavStatus);
mAdapter.favChanged(lPosition, lNewFavStatus);
SongPlayerService mSongPlayerService = SongPlayerService.getRunningInstance();
if (mSongPlayerService != null)
mSongPlayerService.favChanged(lPosition, lNewFavStatus);
}
public void onRowClick(View pView) {
int lPosition = mRecyclerView.getChildLayoutPosition(pView);
SongDetailsJDO lJDO = mAdapter.getItemAtPosition(lPosition);
startActivityForResult(new Intent(SongsListActivity.this, PlayerActivity.class)
.putExtra(getString(R.string.song_jdo), lJDO), REQUEST_CODE);
overridePendingTransition(R.anim.from_right, R.anim.scale_down);
}
private SongDetailsJDO getSongJDO(String pSongId) {
SongDetailsJDO lJDO = null;
for (SongDetailsJDO lSongDetailsJDO : mSongDetailsJDOs) {
if (lSongDetailsJDO.getSongId().equals(pSongId)) {
lJDO = lSongDetailsJDO;
break;
}
}
return lJDO;
}
private void filterRecView(String pText) {
if (pText != null) {
if (pText.equals("")) {
mAdapter.swapData(mSongDetailsJDOs);
toggleVisibilityForNoResult(mSongDetailsJDOs.size(), pText);
} else {
ArrayList<SongDetailsJDO> lSongDetailsJDOs = new ArrayList<>();
pText = pText.toLowerCase();
for (SongDetailsJDO lDetailsJDO : mSongDetailsJDOs) {
if (lDetailsJDO.getTitle().toLowerCase().contains(pText) || lDetailsJDO.getAlbumName() != null && lDetailsJDO.getAlbumName().toLowerCase().contains(pText))
lSongDetailsJDOs.add(lDetailsJDO);
}
toggleVisibilityForNoResult(lSongDetailsJDOs.size(), pText);
mAdapter.swapData(lSongDetailsJDOs);
}
}
}
public void toggleVisibilityForNoResult(int pNumberOfSongs, String query) {
if (pNumberOfSongs == 0) {
mNoSongTV.setVisibility(View.VISIBLE);
mNoSongTV.setText(getString(R.string.nosong) + " " + query);
} else
mNoSongTV.setVisibility(View.INVISIBLE);
}
public void loadDataToRecyclerView() {
//Loading data to RecyclerView
mSongDetailsJDOs = new SongDetailTable(this).getAllSongs();
mAdapter = new SongListAdapter(SongsListActivity.this, mSongDetailsJDOs);
mRecyclerView.setAdapter(mAdapter);
}
public int getPositionOfSongId(String pSongId) {
int lPostion = -1;
for (int i = 0; i < mSongDetailsJDOs.size(); i++) {
if (mSongDetailsJDOs.get(i).getSongId().equals(pSongId)) {
lPostion = i;
break;
}
}
return lPostion;
}
}

Looking at your problem its not possible to tell exact cause of an issue.
But still i will give some hint over issue.
Check your code inside
mSongDetailsJDOs.size(); what is size of the list, it should be > 0. If not then check inside your activity how you are passing list.
#Override
public int getItemCount() {
if (mSongDetailsJDOs != null)
return mSongDetailsJDOs.size();
else
return 0;
}
If above list is > 0 then check it inside onBindViewHolder() that you are getting position one by one and try to render one item a time.
let me know if above works for you.

Related

Unable to update view on data change in Epoxy Controller

I am using Epoxy Controller for Recycler View. I am having trouble changing the view after data changed by the user action.
Basically I have a switch button in a view which is used inside a recycler view and I am trying to update the view on switch button state change. I am calling requestModelBuild() in setProductList() function of the epoxy controller but change is not reflected in the view.
public class SellerInventoryListEpoxyController extends EpoxyController {
private List<Product> productList = Collections.emptyList();
private Context context;
private SellerInventoryListEpoxyController.Callbacks callbacks;
public void setProductList(List<Product> productList, Context context, SellerInventoryListEpoxyController.Callbacks callbacks) {
this.productList = productList;
this.context = context;
this.callbacks = callbacks;
requestModelBuild();
}
#Override
protected void buildModels() {
for (int i = 0; i < productList.size(); i++) {
new InventoryProductDetailModel_()
.id(productList.get(i).getId())
.product(productList.get(i))
.position(i)
.listSize(productList.size())
.callbacks(callbacks)
.context(context)
.addTo(this);
}
}
public interface Callbacks {
void onViewComboClick(Product productComboList);
void onProductListingStatusChanged(Boolean newStatus, int productSellerId);
void onRecyclerViewReachEnd();
}
}
public class InventoryProductDetailModel extends EpoxyModelWithHolder<InventoryProductDetailModel.ViewHolder> implements CompoundButton.OnCheckedChangeListener {
#EpoxyAttribute
Product product;
#EpoxyAttribute
int position;
#EpoxyAttribute
int listSize;
#EpoxyAttribute
Context context;
#EpoxyAttribute(EpoxyAttribute.Option.DoNotHash)
SellerInventoryListEpoxyController.Callbacks callbacks;
#Override
protected ViewHolder createNewHolder() {
return new ViewHolder();
}
#Override
protected int getDefaultLayout() {
return R.layout.inventroy_item_layout;
}
private DrawableCrossFadeFactory factory =
new DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build();
#Override
public void bind(#NonNull InventoryProductDetailModel.ViewHolder holder) {
super.bind(holder);
holder.quantity.setText(String.format("Available :%d", product.getTotalStock()));
holder.brand.setText(product.getProduct().getBrandName());
holder.title.setText(product.getProduct().getTitle());
holder.category.setText(product.getProduct().getCategoryName());
holder.sku.setText(String.format("Sku: %s", product.getSku()));
holder.inventoryItemConstrainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ProductDetailActivity.class);
intent.putExtra("product_id", product.getId());
context.startActivity(intent);
}
});
if (product.getProductCombos() != null && product.getProductCombos().size() > 0) {
holder.variationCount.setVisibility(View.GONE);
holder.comboBtn.setVisibility(View.VISIBLE);
holder.comboBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callbacks.onViewComboClick(product);
}
});
}
if (product.getSellerActive()) {
holder.productStatusSwitch.setText("Active");
holder.productStatusSwitch.setOnCheckedChangeListener(null);
holder.productStatusSwitch.setChecked(true);
holder.productStatusSwitch.setOnCheckedChangeListener(this);
holder.productStatusSwitch.setTextColor(context.getResources().getColor(R.color.colorAccent));
} else {
holder.productStatusSwitch.setText("Inactive");
holder.productStatusSwitch.setOnCheckedChangeListener(null);
holder.productStatusSwitch.setChecked(false);
holder.productStatusSwitch.setOnCheckedChangeListener(this);
holder.productStatusSwitch.setTextColor(Color.parseColor("#ff0000"));
}
holder.variationCount.setText(format("Variation(%d)", product.getVariantCount()));
holder.variationCount.setVisibility(View.VISIBLE);
holder.comboBtn.setVisibility(View.GONE);
loadImage(holder.productImage, Utils.getRequiredUrlForThisImage(holder.productImage, product.getProduct().getImage()));
if (position == listSize - 2) {
callbacks.onRecyclerViewReachEnd();
}
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
callbacks.onProductListingStatusChanged(isChecked, product.getId());
}
private void loadImage(ImageView imageView, String url) {
Glide.with(imageView.getContext()).asBitmap()
.load(Utils.getRequiredUrlForThisImage(imageView, url))
.apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.fitCenter())
.transition(withCrossFade(factory))
.placeholder(R.mipmap.product)
.into(imageView);
}
#Override
public void unbind(#NonNull InventoryProductDetailModel.ViewHolder holder) {
super.unbind(holder);
}
public static class ViewHolder extends EpoxyHolder {
TextView quantity, brand, title, category, variationCount, comboBtn;
ImageView productImage, btn_product_detail;
ProgressBar progressBar;
ConstraintLayout inventoryItemConstrainLayout;
private TextView sku;
private Switch productStatusSwitch;
#Override
protected void bindView(#NonNull View itemView) {
productStatusSwitch = itemView.findViewById(R.id.productStatusSwitch);
quantity = itemView.findViewById(R.id.product_qty);
brand = itemView.findViewById(R.id.product_brand);
title = itemView.findViewById(R.id.product_title);
sku = itemView.findViewById(R.id.sku);
category = itemView.findViewById(R.id.product_category);
variationCount = itemView.findViewById(R.id.variantCount);
productImage = itemView.findViewById(R.id.product_image);
btn_product_detail = itemView.findViewById(R.id.btn_product_detail);
inventoryItemConstrainLayout = itemView.findViewById(R.id.inventory_item_constrain_layout);
comboBtn = itemView.findViewById(R.id.combo_btn);
progressBar = itemView.findViewById(R.id.progressbar);
progressBar.setVisibility(View.GONE);
}
}
#Override
public int hashCode() {
super.hashCode();
return product.hashCode();
}
#Override
public boolean equals(Object o) {
return super.equals(o);
}
}
private void addProductListingChangeObserver(final Boolean newStatus, final int productSellerId) {
ProductUpdate productUpdate = new ProductUpdate();
productUpdate.setSellerActive(newStatus);
mInventoryViewModel.updateProductSeller(productSellerId, productUpdate).observe(this, new Observer<Resource<ProductSeller>>() {
#Override
public void onChanged(Resource<ProductSeller> productSellerResource) {
if (productSellerResource.status == Status.ERROR) {
progressBar.setVisibility(View.GONE);
} else if (productSellerResource.status == Status.SUCCESS) {
progressBar.setVisibility(View.GONE);
if (productSellerResource.data != null && productSellerResource.data.isSellerActive() == newStatus) {
for (int i = 0; i < productList.size(); i++) {
if (productList.get(i).getId() == productSellerId) {
productList.get(i).setSellerActive(newStatus);
break;
}
}
sellerInventoryListEpoxyController.setProductList(productList, getContext(), InventoryFragment.this);
}
} else {
progressBar.setVisibility(View.VISIBLE);
}
}
});
}
In addProductListingChangeObserver() function one object of productList is modified and new productList is passed to the EpoxyController and requestModelbuild is called but the view is not modifying as expected.

Recyclerview - Clicking on results displayed by search opens incorrect item

I'm having a recyclerview to display a list of notes from room database. I've also added search functionality. Currently, I'm having 4 notes in MainActivity (this activity displays notes). On searching, if I get resultant list having more than 2 notes, on clicking them it displays correct notes.But, if resultant has 1 or 2 notes, it always displays the first 2 in list, not the notes filtered by search.
Here's my code:
Model class Note:
#Entity(tableName = TABLE_NAME)
public class Note implements Serializable{
#Nullable
private int Color;
#PrimaryKey(autoGenerate = true)
private long id;
/** Not-null value. */
private String Desc;
private String Time;
// KEEP FIELDS - put your custom fields here
// KEEP FIELDS END
public Note() {
}
public Note(String Desc, String Time) {
this.Desc = Desc;
this.Time = Time;
}
public int getColor() {
return Color;
}
public void setColor(int color) {
Color = color;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
/** Not-null value. */
public String getDesc() {
return Desc;
}
/** Not-null value; ensure this value is available before it is saved to the database. */
public void setDesc(String Desc) {
this.Desc = Desc;
}
public String getTime() {
return Time;
}
public void setTime(String Time) {
this.Time = Time;
}
NotesAdapter:
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.MyViewHolder> {
public List<Note> list;
private Context context;
private List<Note> filteredList = new ArrayList<>();
private ClickListener clickListener;
public List<Note> selectednotes_list = new ArrayList<>();
private String TAG = NotesAdapter.class.getSimpleName();
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mNoteDesc;
public TextView mNoteTime;
public RelativeLayout mcontainer;
public MyViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mNoteTime = itemView.findViewById(R.id.note_time);
mNoteDesc = itemView.findViewById(R.id.note_desc);
mcontainer = itemView.findViewById(R.id.note_container);
}
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: ");
clickListener.onClick(v,this.getLayoutPosition());
}
/*
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: ");
clickListener.onClick(v,getLayoutPosition());
//clickListener.onClick(filteredList.get(getAdapterPosition()));
}
*/
}
public NotesAdapter(List<Note> list, Context context,List<Note> selectednotes_list) {
this.list = list;
this.filteredList = list;
this.context = context;
this.selectednotes_list = selectednotes_list;
this.clickListener = (ClickListener) context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.noteview,null,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.mNoteTime.setText(list.get(position).getTime());
holder.mcontainer.setBackgroundColor(Utils.getRandomMaterialColor(context, "50to300"));
holder.mNoteDesc.setText(list.get(position).getDesc());
// Change background color on select
if (selectednotes_list.size() > 0) {
if (selectednotes_list.contains(list.get(position)))
holder.mcontainer.setBackgroundColor(ContextCompat.getColor(context, R.color.colorSecondary));
}
}
#Override
public int getItemCount() {
return list.size();
}
public void filterList(List<Note> filter) {
this.list = filter;
notifyDataSetChanged();
}
}
MainActivity:
public class MainActivity extends AppCompatActivity implements ClickListener{
private StaggeredGridLayoutManager gridLayoutManager;
private RecyclerView recyclerView;
private List<Note> noteList, multiSelectList;
public NotesAdapter notesAdapter;
private Notedatabase notedatabase;
private String TAG = MainActivity.class.getSimpleName();
private FloatingActionButton maddbtn;
private int position;
private SearchView mSearchView;
private boolean isMultiSelect = false;
private Menu context_menu;
private ActionMode mActionMode;
private CoordinatorLayout mCoordinatorLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
displayList();
/*
notesList.addAll(noteList);
List<Note> notesList = getNotes();
notesAdapter = new NotesAdapter(notesList,MainActivity.this);
recyclerView.setAdapter(notesAdapter);
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
// Searchable config with searchview
SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
mSearchView.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
mSearchView.setMaxWidth(Integer.MAX_VALUE);
// Set Listener
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter when query is submitted
Log.d(TAG, "onQueryTextSubmit: " + query);
notesAdapter.filterList(filter(query,noteList));
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// filter progressively as query changes
Log.d(TAG, "onQueryTextChange: " + newText);
notesAdapter.filterList(filter(newText,noteList));
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_search) {
// search action
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// close searchview
if(!mSearchView.isIconified()) {
mSearchView.setIconified(true);
return;
}
super.onBackPressed();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE) {
if (resultCode == 1) {
Log.d(TAG, "Request code is 1");
noteList.add((Note) data.getSerializableExtra("note"));
notesAdapter.notifyDataSetChanged();
}
else if(resultCode == 2) {
Log.d(TAG, "Request code 2, update return");
noteList.set(position, (Note) data.getSerializableExtra("note"));
notesAdapter.notifyDataSetChanged();
}
else if(resultCode == 3) {
Log.d(TAG, "Request code 3, delete return");
Log.d(TAG, "Deleting this from list:" + (Note) data.getSerializableExtra("note"));
noteList.remove(MainActivity.this.position);
notesAdapter.notifyItemRemoved(MainActivity.this.position);
}
}
}
private void displayList() {
notedatabase = Notedatabase.getInstance(MainActivity.this);
new RetrieveTask(this).execute();
}
private void initViews() {
recyclerView = findViewById(R.id.recyclerview);
gridLayoutManager = new StaggeredGridLayoutManager(2,1);
mCoordinatorLayout = findViewById(R.id.coordinatorLayout);
recyclerView.setLayoutManager(gridLayoutManager);
noteList = new ArrayList<>();
multiSelectList = new ArrayList<>();
notesAdapter = new NotesAdapter(noteList,MainActivity.this,multiSelectList);
recyclerView.setAdapter(notesAdapter);
maddbtn = findViewById(R.id.add_fab);
maddbtn.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this,NoteActivity.class);
startActivityForResult(intent,REQUEST_CODE);
});
}
#Override
public void onClick(View view, int pos) {
/*
Log.d(TAG, "Recylerview item onClick: ");
MainActivity.this.position = pos;
Intent intent = new Intent(MainActivity.this,NoteActivity.class);
intent.putExtra("note",noteList.get(position));
Log.d(TAG, "list.get(position): " + noteList.get(pos).getDesc());
startActivityForResult(intent,REQUEST_CODE);
*/
}
#Override
public void onClick(Note note) {
/*
Log.d(TAG, "onClick with args as note1");
Intent intent = new Intent(MainActivity.this,NoteActivity.class);
intent.putExtra("note",note);
startActivityForResult(intent,REQUEST_CODE);*/
}
#Override
public void onLongClick(View view, int pos) {
/* Log.d(TAG, "onLongClick ");
if(!isMultiSelect) {
multiSelectList = new ArrayList<Note>();
isMultiSelect = true;
if(mActionMode == null) {
mActionMode = startActionMode(mActionModeCallback);
}
}
multi_select(pos);*/
}
private void multi_select(int pos) {
if(mActionMode != null) {
if(multiSelectList.contains(noteList.get(pos))) {
Log.d(TAG, "multi_select removed: " + multiSelectList.contains(noteList.get(pos)));
multiSelectList.remove(noteList.get(pos));
}
else {
Log.d(TAG, "multi_select added: " + multiSelectList.contains(noteList.get(pos)));
multiSelectList.add(noteList.get(pos));
}
if(multiSelectList.size() > 0) mActionMode.setTitle("" + multiSelectList.size() + " selected");
else mActionMode.setTitle("");
refreshAdapter();
}
}
private void refreshAdapter() {
notesAdapter.selectednotes_list = multiSelectList;
notesAdapter.list = noteList;
notesAdapter.notifyDataSetChanged();
}
class RetrieveTask extends AsyncTask<Void,Void,List<Note>>{
private WeakReference<MainActivity> weakReference;
public RetrieveTask(MainActivity mainActivity) {
weakReference = new WeakReference<>(mainActivity);
}
#Override
protected List<Note> doInBackground(Void... voids) {
if(weakReference.get()!=null)
return weakReference.get().notedatabase.getNoteDao().getNotes();
else
return null;
}
#Override
protected void onPostExecute(List<Note> notes) {
if(notes!=null & notes.size()>0) {
weakReference.get().noteList = notes;
//weakReference.get().noteList.addAll(weakReference.get().getNotes());
Log.d(TAG, "Result: " + notes);
weakReference.get().notesAdapter = new NotesAdapter(notes,weakReference.get(),multiSelectList);
/*
// Randomly set note background
for(Note n:notes) {
n.setColor(getRandomMaterialColor(MainActivity.this,"500"));
}
*/ weakReference.get().recyclerView.addOnItemTouchListener(new RecyclerTouchListener(recyclerView, getApplicationContext(), new ClickListener() {
#Override
public void onClick(View view, int pos) {
if (isMultiSelect)
multi_select(pos);
else {
Log.d(TAG, "Recylerview item onClick: ");
MainActivity.this.position = pos;
Intent intent = new Intent(MainActivity.this, NoteActivity.class);
intent.putExtra("note", noteList.get(position));
Log.d(TAG, "list.get(position): " + weakReference.get().noteList.get(position).getDesc());
startActivityForResult(intent, REQUEST_CODE);
}
}
#Override
public void onClick(Note note) {
Log.d(TAG, "onClick with args as note");
Intent intent = new Intent(MainActivity.this, NoteActivity.class);
intent.putExtra("note", note);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
public void onLongClick(View view, int pos) {
Log.d(TAG, "onLongClick ");
if(!isMultiSelect) {
multiSelectList = new ArrayList<Note>();
isMultiSelect = true;
if(mActionMode == null) {
mActionMode = startActionMode(mActionModeCallback);
}
}
multi_select(pos);
}
}));
weakReference.get().recyclerView.setAdapter(weakReference.get().notesAdapter);
weakReference.get().notesAdapter.notifyDataSetChanged();
}
else{
displayErrorMsg();
}
}
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
//Prepare the menu
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_action,menu);
context_menu = menu;
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
//mode.getCustomView().setBackgroundColor(getApplicationContext().getResources().getColor(android.R.color.white));
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
// display alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Delete " + multiSelectList.size() + " notes?");
builder.setCancelable(true);
builder.setPositiveButton(R.string.alert_yes,(dialog, which) -> {
// Deleting notes
for (int i = 0; i < multiSelectList.size(); i++) {
Log.d(TAG, "Deleting: " + multiSelectList.get(i));
notedatabase.getNoteDao().deleteNotes(multiSelectList.get(i));
noteList.remove(multiSelectList.get(i));
}
// Display Snackbar
displaySnackbar(mCoordinatorLayout,R.string.delete_success);
dialog.cancel();
// Refresh adapter
refreshAdapter();
// dismiss the contextual action bar
if(mActionMode!=null) mActionMode.finish();
});
builder.setNegativeButton(R.string.alert_no,(dialog, which) -> {
dialog.cancel();
if(mActionMode!=null) mActionMode.finish();
});
builder.setOnCancelListener(dialog1 -> {
Log.d(TAG, "onCancelListener: ");
if(mActionMode!=null) mActionMode.finish();
});
AlertDialog dialog = builder.create();
dialog.show();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
isMultiSelect = false;
multiSelectList = new ArrayList<Note>();
refreshAdapter();
}
};
#Override
protected void onDestroy() {
notedatabase.cleanUp();
super.onDestroy();
}
private void displayErrorMsg() {
Toast.makeText(MainActivity.this,R.string.failure_display,Toast.LENGTH_SHORT).show();
}
}
Any help is widely appreciated!!
Please! Badly stuck here
Found it out!
I was not storing the result of filter, instead I was directly calling it in filterList.
noteList = filter(newText, noteList);
notesAdapter.filterList(noteList);
The above lines did it for me!

How to transfer data between adapters?

I have these two adapters OperateClassroomAdapter and EditClassRoom adapter
public class OperateClassroomsAdapter extends RecyclerView.Adapter<OperateClassroomsAdapter.ViewHolder> {
private ArrayList<Classroom> classroomList;
private AdapterClickListener adapterClickListener;
public OperateClassroomsAdapter(ArrayList<Classroom> classroomList) {
this.classroomList = classroomList;
}
/**
* Set on item click listener
* #param adapterClickListener AdapterClickListener
*/
public void setAdapterClickListener(AdapterClickListener adapterClickListener) {
this.adapterClickListener = adapterClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.operate_classroom_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
Classroom item = classroomList.get(position);
viewHolder.text.setText(item.getName());
viewHolder.counter.setText(String.valueOf(item.getStudentNumber()));
Log.d("sn",String.valueOf(item.getStudentNumber()));
}
#Override
public int getItemCount()
{
return classroomList == null ? 0 : classroomList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView text;
TextView counter;
public ViewHolder(View itemView)
{
super(itemView);
itemView.setOnClickListener(this);
text = (TextView) itemView.findViewById(R.id.text);
counter = (TextView) itemView.findViewById(R.id.counter);
}
#Override
public void onClick(View v)
{
if (adapterClickListener != null) {
adapterClickListener.OnItemClick(getAdapterPosition());
}
}
}
}
Here in onBindViewHolder Log.d("sn") it shows proper values whereas in the code below
public class EditClassroomsAdapter extends RecyclerView.Adapter<EditClassroomsAdapter.ViewHolder> {
private Context context;
private ArrayList<Classroom> classroomList;
private ListPopupWindow listPopupWindow;
private PopupClickListener popupClickListener;
private AdapterClickListener adapterClickListener;
private DeleteClassBtnClickListener deleteClassBtnClickListener;
private EditClassBtnClickListener editClassBtnClickListener;
private Random mRandom = new Random();
String colorarray[]= new String[]{
"#ffff66",
"#99ff66",
"#ffffff",
"#b3ffff",
"#ff8080",
"#ccdcff",
"#c3c3c3"
};
public EditClassroomsAdapter(Context context, ArrayList<Classroom> classroomList) {
this.context = context;
this.classroomList = classroomList;
listPopupWindow = new ListPopupWindow(context);
}
/**
* Set on item click listener
* #param adapterClickListener AdapterClickListener
*/
public void setAdapterClickListener(AdapterClickListener adapterClickListener) {
this.adapterClickListener = adapterClickListener;
}
/**
* Set on pop-up men item click listener
* #param popupClickListener PopupClickListener
*/
public void setPopupClickListener(PopupClickListener popupClickListener) {
this.popupClickListener = popupClickListener;
}
public void setDeleteClassBtnClickListener(DeleteClassBtnClickListener deleteClassBtnClickListener){
this.deleteClassBtnClickListener=deleteClassBtnClickListener;
}
public void setEditClassBtnClickListener(EditClassBtnClickListener editClassBtnClickListener) {
this.editClassBtnClickListener = editClassBtnClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.edit_classroom_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
Classroom item = classroomList.get(position);
Log.d("sn22",String.valueOf(item.getStudentNumber()));
viewHolder.text.setText(item.getName());
viewHolder.student_count.setText(String.valueOf(item.getStudentNumber()));
viewHolder.settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listPopupWindow != null) {
setListPopUpWindow(v, position);
}
}
});
/*
New Delete button added
*/
viewHolder.del_class.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(deleteClassBtnClickListener!=null)
deleteClassBtnClickListener.OnDeleteclassBtnClicked(position);
}
});
/*
edit_class button added
*/
viewHolder.edit_class.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(editClassBtnClickListener!=null)
editClassBtnClickListener.OnEditclassBtnClicked(position);
}
});
Random rand=new Random();
int rgen=rand.nextInt(6)+1;
viewHolder.thumbnail.getLayoutParams().height = getRandomIntInRange(350,200);
viewHolder.thumbnail.setBackgroundColor(Color.parseColor(colorarray[rgen]));
Glide.with(context).load(item.getThumbnail()).into(viewHolder.thumbnail);
// loading album cover using Glide library
// Glide.with(mContext).load(album.getThumbnail()).into(holder.thumbnail);
}
protected int getRandomIntInRange(int max, int min){
return mRandom.nextInt((max-min)+min)+min;
}
#Override
public int getItemCount() {
return classroomList == null ? 0 : classroomList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView text;
ImageButton settings;
ImageView thumbnail;
ImageButton del_class,edit_class;
TextView student_count;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
thumbnail=(ImageView) itemView.findViewById(R.id.cat_image) ;
text = (TextView) itemView.findViewById(R.id.text);
student_count = (TextView) itemView.findViewById(R.id.student_count);
settings = (ImageButton) itemView.findViewById(R.id.settings);
del_class=(ImageButton)itemView.findViewById(R.id.del_class);
edit_class=(ImageButton)itemView.findViewById(R.id.edit_class);
}
#Override
public void onClick(View v) {
if (adapterClickListener != null) {
adapterClickListener.OnItemClick(getAdapterPosition());
}
}
}
/**
* List pop up menu window
* #param anchor View
* #param classroomPosition List item's position
*/
private void setListPopUpWindow(View anchor, final int classroomPosition) {
listPopupWindow.dismiss();
listPopupWindow.setAdapter(new ArrayAdapter(context, android.R.layout.simple_list_item_1,
context.getResources().getStringArray(R.array.edit_classroom)));
listPopupWindow.setAnchorView(anchor);
listPopupWindow.setContentWidth(context.getResources()
.getInteger(R.integer.list_pop_up_width));
listPopupWindow.setDropDownGravity(Gravity.END);
listPopupWindow.setModal(true);
listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int menuItemPosition, long id) {
if (popupClickListener != null) {
popupClickListener.OnPopupClick(classroomPosition, menuItemPosition);
}
listPopupWindow.dismiss();
}
});
listPopupWindow.show();
}
}
The Log.d("sn22") is showing values as 0.Why is this happening ?Or how do i get values from OperateClassroomAdapter here ?
My main point is im passing same arraylist ,still sn22 shows 0 and other shows proper values.Also these are 2 different fragment.
Here is the code for their respective classes where theyre used.
public class EditClassroomFragment extends Fragment {
private Context context;
private static int p=0;
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView list;
private ArrayList<Classroom> arrayList = new ArrayList<>();
private EditClassroomsAdapter adapter;
private RecyclerView.LayoutManager mLayoutManager2 = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
private TextView emptyText; //empty list view text
public EditClassroomFragment() {}
public static EditClassroomFragment newInstance() {
EditClassroomFragment editClassroomFragment = new EditClassroomFragment();
return editClassroomFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retain this fragment
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.refreshable_list, container, false);
context = rootView.getContext();
list = (RecyclerView) rootView.findViewById(R.id.list);
adapter = new EditClassroomsAdapter(context, arrayList);
list.setAdapter(adapter);
list.setLayoutManager(mLayoutManager2);
list.setHasFixedSize(true);
emptyText = (TextView) rootView.findViewById(R.id.emptyText);
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new SelectClassrooms().execute();
}
});
addDeleteClassBtnClickListener();
addAdapterClickListener();
addPopupClickListener();
addEditClassBtnClickListener();
new SelectClassrooms().execute();
return rootView;
}
/**
* Set empty list text
*/
private void setEmptyText() {
if (emptyText != null) {
if (arrayList.isEmpty()) {
emptyText.setVisibility(View.VISIBLE);
} else {
emptyText.setVisibility(View.GONE);
}
}
}
/**
* Check if the given classroom name already exists
* #param classroomName Selected classroom
* #return
*/
private boolean isAlreadyExist(String classroomName) {
boolean isAlreadyExist = false;
for (Classroom classroom : arrayList) {
if (classroom.getName().equals(classroomName)) {
isAlreadyExist = true;
break;
}
}
return isAlreadyExist;
}
/**
* Add new class item
*/
public void addClassroom() {
final PromptDialog promptDialog = new PromptDialog(context);
promptDialog.setPositiveButton(getString(R.string.ok));
promptDialog.setAllCaps();
promptDialog.setAlphanumeric();
promptDialog.setOnPositiveClickListener(new PromptListener() {
#Override
public void OnPrompt(String promptText) {
closeKeyboard();
promptDialog.dismiss();
if (!TextUtils.isEmpty(promptText)) {
if (!isAlreadyExist(promptText)) {
new InsertClassroom().execute(promptText);
} else {
//alert
CustomAlertDialog customAlertDialog = new CustomAlertDialog(context);
customAlertDialog.setMessage(getString(R.string.couldNotInsertClassroom));
customAlertDialog.setPositiveButtonText(getString(R.string.ok));
customAlertDialog.showDialog();
}
}
}
});
promptDialog.show();
}
public void addClassroom2(String st) {
if(st.equals(null)==false) {
if (!isAlreadyExist(st)) {
new InsertClassroom().execute(st);
} else {
//alert
CustomAlertDialog customAlertDialog = new CustomAlertDialog(context);
customAlertDialog.setMessage(getString(R.string.couldNotInsertClassroom));
customAlertDialog.setPositiveButtonText(getString(R.string.ok));
customAlertDialog.showDialog();
}
}
}
/**
* Change the selected class name
* #param classroomId current classroom to be changed
* #param content current name of the classroom
*/
public void editClassroom(final int classroomId, String content) {
final PromptDialog promptDialog = new PromptDialog(context);
promptDialog.setContent(content);
promptDialog.setPositiveButton(getString(R.string.ok));
promptDialog.setAllCaps();
promptDialog.setAlphanumeric();
promptDialog.setOnPositiveClickListener(new PromptListener() {
#Override
public void OnPrompt(String promptText) {
closeKeyboard();
promptDialog.dismiss();
if (!TextUtils.isEmpty(promptText)) {
new UpdateClassroom().execute(String.valueOf(classroomId), promptText);
}
}
});
promptDialog.show();
}
/**
* Delete classroom
* #param classroom Selected classroom
*/
private void deleteClassroom(final Classroom classroom) {
//show alert before deleting
CustomAlertDialog customAlertDialog = new CustomAlertDialog(context);
customAlertDialog.setMessage(classroom.getName()
+ getString(R.string.sureToDelete));
customAlertDialog.setPositiveButtonText(getString(R.string.delete));
customAlertDialog.setNegativeButtonText(getString(R.string.cancel));
customAlertDialog.setOnClickListener(new OnAlertClick() {
#Override
public void OnPositive() {
new DeleteClassroom().execute(classroom.getId());
}
#Override
public void OnNegative() {
//do nothing
}
});
customAlertDialog.showDialog();
}
/**
* Go inside classroom to add, change or delete students
* #param classroom
*/
private void showStudents(Classroom classroom) {
Intent intent = new Intent(context, EditStudentActivity.class);
intent.putExtra("classroom", classroom);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.move_in_from_bottom,
R.anim.stand_still);
}
/**
* List item click event
*/
private void addAdapterClickListener() {
adapter.setAdapterClickListener(new AdapterClickListener() {
#Override
public void OnItemClick(int position) {
if (arrayList != null && arrayList.size() > position) {
showStudents(arrayList.get(position));
Log.d("sn44",String.valueOf(arrayList.get(position).getStudentNumber()));
}
}
});
}
/**
* Pop-up menu item click event
*/
public void addPopupClickListener() {
adapter.setPopupClickListener(new PopupClickListener() {
#Override
public void OnPopupClick(int itemPosition, int menuPosition) {
if (arrayList != null && arrayList.size() > itemPosition) {
Classroom classroom = arrayList.get(itemPosition);
if (menuPosition == ClassroomPopup.CHANGE_NAME.getValue()) {
editClassroom(classroom.getId(), classroom.getName());
} else if (menuPosition == ClassroomPopup.DELETE_CLASSROOM.getValue()) {
deleteClassroom(classroom);
}
}
}
});
}
/*
Edit button and delete button listeners
*/
public void addDeleteClassBtnClickListener()
{
adapter.setDeleteClassBtnClickListener(new DeleteClassBtnClickListener() {
#Override
public void OnDeleteclassBtnClicked(int position) {
if (arrayList != null && arrayList.size() > position) {
Classroom classroom = arrayList.get(position);
deleteClassroom(classroom);
}
}
});
}
public void addEditClassBtnClickListener()
{
adapter.setEditClassBtnClickListener(new EditClassBtnClickListener() {
#Override
public void OnEditclassBtnClicked(int position) {
if (arrayList != null && arrayList.size() > position) {
Classroom classroom = arrayList.get(position);
editClassroom(classroom.getId(), classroom.getName());
}
}
});
}
/**
* Select classrooms from DB
*/
private class SelectClassrooms extends AsyncTask<Void, Void, ArrayList<Classroom>> {
#Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
}
#Override
protected ArrayList<Classroom> doInBackground(Void... params) {
DatabaseManager databaseManager = new DatabaseManager(context);
ArrayList<Classroom> tmpList = databaseManager.selectClassrooms();
return tmpList;
}
#Override
protected void onPostExecute(ArrayList<Classroom> tmpList) {
swipeRefreshLayout.setRefreshing(false);
arrayList.clear();
if (tmpList != null) {
arrayList.addAll(tmpList);
adapter.notifyDataSetChanged();
setEmptyText();
}
}
}
/**
* Insert classroom name into DB
*/
private class InsertClassroom extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
String classroom = params[0];
DatabaseManager databaseManager = new DatabaseManager(context);
boolean isSuccessful = databaseManager.insertClassroom(classroom);
return isSuccessful;
}
#Override
protected void onPostExecute(Boolean isSuccessful) {
if (isSuccessful) {
new SelectClassrooms().execute();
}
}
}
/**
* Update classroom name in the DB
*/
private class UpdateClassroom extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
String classroomId = params[0];
String newName = params[1];
DatabaseManager databaseManager = new DatabaseManager(context);
boolean isSuccessful = databaseManager.updateClassroomName(classroomId, newName);
return isSuccessful;
}
#Override
protected void onPostExecute(Boolean isSuccessful) {
if (isSuccessful) {
new SelectClassrooms().execute();
}
}
}
/**
* Delete a classroom item from DB
*/
private class DeleteClassroom extends AsyncTask<Integer, Void, Boolean> {
#Override
protected Boolean doInBackground(Integer... params) {
int classroomId = params[0];
DatabaseManager databaseManager = new DatabaseManager(context);
boolean isSuccessful = databaseManager.deleteClassroom(classroomId);
return isSuccessful;
}
#Override
protected void onPostExecute(Boolean isSuccessful) {
if (isSuccessful) {
new SelectClassrooms().execute();
}
}
}
/**
* Closes keyboard for disabling interruption
*/
private void closeKeyboard(){
try {
InputMethodManager imm = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception ignored) {}
}
}
public class AttendancesFragment extends Fragment {
private Context context;
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView list;
private ArrayList<Classroom> arrayList = new ArrayList<>();
private OperateClassroomsAdapter adapter;
private TextView emptyText; //empty list view text
public AttendancesFragment() {}
public static AttendancesFragment newInstance() {
AttendancesFragment attendancesFragment = new AttendancesFragment();
return attendancesFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retain this fragment
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.refreshable_list, container, false);
context = rootView.getContext();
list = (RecyclerView) rootView.findViewById(R.id.list);
adapter = new OperateClassroomsAdapter(arrayList);
list.setAdapter(adapter);
list.setLayoutManager(new LinearLayoutManager(context));
list.setHasFixedSize(true);
emptyText = (TextView) rootView.findViewById(R.id.emptyText);
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new SelectClassrooms().execute();
}
});
addAdapterClickListener();
new SelectClassrooms().execute();
return rootView;
}
/**
* Set empty list text
*/
private void setEmptyText() {
if (emptyText != null) {
if (arrayList.isEmpty()) {
emptyText.setVisibility(View.VISIBLE);
} else {
emptyText.setVisibility(View.GONE);
}
}
}
/**
* List item click event
*/
public void addAdapterClickListener() {
adapter.setAdapterClickListener(new AdapterClickListener() {
#Override
public void OnItemClick(int position) {
if (arrayList != null && arrayList.size() > position) {
Intent intent = new Intent(context, TakeAttendanceActivity.class);
intent.putExtra("classroom", arrayList.get(position));
startActivityForResult(intent, 0);
getActivity().overridePendingTransition(R.anim.move_in_from_bottom,
R.anim.stand_still);
}
}
});
}
/**
* Select classrooms from DB
*/
private class SelectClassrooms extends AsyncTask<Void, Void, ArrayList<Classroom>> {
#Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
}
#Override
protected ArrayList<Classroom> doInBackground(Void... params) {
DatabaseManager databaseManager = new DatabaseManager(context);
ArrayList<Classroom> tmpList = databaseManager.selectClassroomsWithStudentNumber();
return tmpList;
}
#Override
protected void onPostExecute(ArrayList<Classroom> tmpList) {
swipeRefreshLayout.setRefreshing(false);
arrayList.clear();
if (tmpList != null) {
arrayList.addAll(tmpList);
adapter.notifyDataSetChanged();
setEmptyText();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
Snackbar.make(list, getString(R.string.saved), Snackbar.LENGTH_LONG).show();
}
}
}
If your problem is how pass from data from adapter to another, you can use SharedPreferences to save and get data from adapter to another.
Hope this help you

Using searchview in actionbar in fragments

I am displaying a userlist and I am using serachview in my actionbar to search. When I am using the searchView in activity, it works fine but when I use it for fragment, searchview doesn't work. It does not search in the listview.
Below is my code.
UserListFragment.java
public class UsersListFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Activity activity;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private static final String TAG = "UsersListFragment";
private OnFragmentInteractionListener mListener;
private ListView listView;
private List<UserData> users;
private CustomAdapter adapter;
SharedPreferences.Editor preferenceEditor;
Timer myTimer;
View view;
ActionBar actionBar;
private static final String PREFRENCES_NAME = "setPreferences";
private ProgressDialog progressBar;
String partnerKeyValue;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment UsersListFragment.
*/
// TODO: Rename and change types and number of parameters
public static UsersListFragment newInstance(String param1, String param2) {
UsersListFragment fragment = new UsersListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressBar = new ProgressDialog(getActivity());
progressBar.setCancelable(false);
progressBar.setMessage("Loading...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
Log.i(TAG, "UsersListFragment onCreate");
users = new ArrayList<>();
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh","userlistview");
preferenceEditor.commit();
FirebaseUtil uts = new FirebaseUtil(getContext());
uts.startListeningNotification(Global.getInstance().ownerId, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
Log.i(TAG, Success);
setHasOptionsMenu(true);
String partnerKey = (String) response.get("key");
if (partnerKey != null) {
Map<String, Object> typeCheck = (Map<String, Object>) response.get("value");
String type = (String) typeCheck.get("type");
if (type.equals("chat")) {
String key1 = Global.getInstance().ownerId;
String key2 = partnerKey;
partnerKeyValue = partnerKey;
if (key2 != null) {
String currentPartner = Global.getInstance().partnerId;
if (currentPartner.length() > 0) {
if (currentPartner.equals(partnerKey)) {
} else {
Global.getInstance().unreadMessageUsers.add(partnerKey);
}
Global.getInstance().unreadMessageUsers.add(partnerKey);
} else {
}
}
}
}
}
});
}
#Override
public void onStart() {
super.onStart();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "UsersListFragment onResume");
}
#Override
public void onPause() {
super.onPause();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onStop() {
super.onStop();
Log.i(TAG, "UsersListFragment onStop");
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
FirebaseUtil util = new FirebaseUtil(getContext());
util.updateUserStatus(Global.getInstance().ownerId, "4");
Log.i(TAG, "UsersListFragment onDestroy");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if(actionBar!=null) {
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setLogo(R.drawable.ic_logo);
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#006EAD"));
actionBar.setBackgroundDrawable(colorDrawable);
}
Toast.makeText(getActivity(), String.valueOf( Global.getInstance().unreadMessageUsers.size()) , Toast.LENGTH_SHORT).show();
int vd = users.size();
view = inflater.inflate(R.layout.fragment_userslist, container, false);
listView = (ListView) view.findViewById(R.id.userdisplay);
adapter = new CustomAdapter(getActivity(),R.layout.program_list, users );
listView.setAdapter(adapter);
if (users.size()==0){
usersList();
}else {
adapter.notifyDataSetChanged();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UserData data = users.get(position);
Global.getInstance().someData = data.getId();
Global.getInstance().partnerId = data.getId();
int i = 0;
for (Iterator<String> iter = Global.getInstance().unreadMessageUsers.iterator(); iter.hasNext(); ) {
String element = iter.next();
if (element.equals(data.getId().toString())) {
iter.remove();
}
}
data.setUnreadMessageCount(0);
users.remove(position);
users.add(position, data);
Toast.makeText(getActivity().getApplicationContext(),String.valueOf(Global.getInstance().unreadMessageUsers.size()),Toast.LENGTH_LONG).show();
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
Bundle args = new Bundle();
args.putString(ChatFragment.DATA_RECEIVE, data.getName());
fragmentOne .setArguments(args);
ft.addToBackStack(null);
ft.replace(R.id.framecontainerMain, fragmentOne).commit();
}
});
// Inflate the layout for this fragment
return view;
}
public void usersList () {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
//get the data from userlist api
final String URL = "url";
String token = preferenceSettings.getString("authToken","");
final String userId = preferenceSettings.getString("userId","");
HashMap<String, String> params = new HashMap<String, String>();
params.put("user_id",userId);
params.put("auth_token",token);
progressBar.show();
JsonObjectRequest myRequest = new JsonObjectRequest(Request.Method.POST, URL,new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "onResponse:" +response);
String success = null;
try {
success = response.getString("success");
} catch (JSONException e) {
e.printStackTrace();
}
if(success == "true") {
JSONArray Array = null;
try {
//get the users
} else {
users.add(data);
}
}
Log.i(TAG, "arraylist");
adapter.notifyDataSetChanged();
onlineUsers();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 5000);
progressBar.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject Obj;
} else {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.dismiss();
VolleyLog.e("Error: ", error.getMessage());
Log.i(TAG, "onErrorResponse:" +error.networkResponse);
}
});
ApplicationController.getInstance().addToRequestQueue(myRequest);
myRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
public void sortingArray(){
if (users.size()>0) {
synchronized (this) {
if (Global.getInstance().unreadMessageUsers.size() > 0) {
System.out.println("\nExample 3 - Count all with Map");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String temp : Global.getInstance().unreadMessageUsers) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
System.out.println("\nSorted Map");
Map<String, Integer> unreadCount = new TreeMap<String, Integer>(map);
for (String key : unreadCount.keySet()) {
int count_unread = unreadCount.get(key);
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setUnreadMessageCount(count_unread);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}
synchronized (this) {
if (Global.getInstance().userStatus.size() > 0) {
try {
for (Object dict : Global.getInstance().userStatus) {
Map<String, Object> val = (Map<String, Object>) dict;
String key = val.keySet().iterator().next();
val.get(key).toString().trim();
int statusValue;
if (val.get(key).toString().equals("")) {
statusValue = 4;
} else {
statusValue = Integer.valueOf(val.get(key).toString());
}
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setOnlineStatus(statusValue);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}catch (ConcurrentModificationException e){
e.printStackTrace();
}
}
}
Log.i(TAG, users.get(0).getName());
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getOnlineStatus() > o2.getOnlineStatus()) {
return 1;
} else if (o1.getOnlineStatus() < o2.getOnlineStatus()) {
return -1;
} else {
return 0;
}
}
});
}
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getUnreadMessageCount() > o2.getUnreadMessageCount()) {
return -1;
} else if (o1.getUnreadMessageCount() < o2.getUnreadMessageCount()) {
return 1;
} else {
return 0;
}
}
});
Global.getInstance().userStatus.clear();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(), "any mesage", Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
});
}
}
}
}
public void TimerMethod() {
synchronized(this) {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences("setPreferences", Context.MODE_PRIVATE);
String checkView = preferenceSettings.getString("refresh", "");
if (checkView.equals("userlistview")) {
if (Global.getInstance().userStatus.size() > 0) {
sortingArray();
}
} else {
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh", "userlistview");
preferenceEditor.commit();
if (Global.getInstance().unreadMessageUsers.size() > 0){
sortingArray();
}
}
}
}
public void onlineUsers (){
String value;
for (UserData data : users) {
value = data.getId();
FirebaseUtil online = new FirebaseUtil(getContext());
online.onlineUsers(value, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
if (response == null) {
} else {
Global.getInstance().userStatus.add(response);
}
}
});
}
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
inflater.inflate(R.menu.menu_userlist,menu);
MenuItem item = menu.findItem(R.id.menuSearch);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
super.onCreateOptionsMenu(menu,inflater);
}
private void logoutUser(){
Intent I = new Intent(getActivity(), LoginActivity.class);
startActivity(I);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuSearch :
return true;
case R.id.menuLogout :
logoutUser();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
String val = "'";
mListener.onFragmentInteraction(val);
}
}
public void initlizeval(Context context) {
mListener = (OnFragmentInteractionListener) context;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
myTimer.cancel();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String val);
}
}
menu_userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/menuSearch"
android:title="#string/search"
android:icon="#drawable/ic_search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always">
</item>
<item android:id="#+id/menuLogout"
android:title="#string/logout"
android:icon="#drawable/ic_logout"
android:tint="#android:color/white"
app:showAsAction="always">
</item>
</menu>
CustomAdapter.java
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class CustomAdapter extends ArrayAdapter<UserData> {
private Activity activity;
private List<UserData> messages;
public CustomAdapter(Activity context, int resource, List<UserData> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
packagename.CustomAdapter.ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
UserData data = getItem(position);
int viewType = getItemViewType(position);
layoutResource = R.layout.program_list;
if (convertView != null) {
holder = (com.your.package.CustomAdapter.ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new com.your.package.CustomAdapter.ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(data.getName());
holder.id = data.geId();
holder.roleMsg.setText(data.getRole());
return convertView;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
private class ViewHolder {
private TextView msg;
private String id;
private TextView roleMsg;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.textView1);
roleMsg = (TextView) v.findViewById(R.id.textView2);
}
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity implements UsersListFragment.OnFragmentInteractionListener {
private UsersListFragment mItemsFragment;
private ChatFragment mFragmentOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
VideoFragment fragmentTwo ;
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
android.support.v4.app.FragmentTransaction fts = getSupportFragmentManager().beginTransaction();
fts.add(R.id.framecontainer, mItemsFragment).commit();
//Instantiate some stuff here like view components
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.framecontainerTab, fragmentOne).commit();
}else{
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
layout2.removeAllViews();
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
setFragment(mItemsFragment);
}
}
public void setFragment(Fragment frag)
{
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
}
public void attemptLogin1() {
String test = "one";
String tested = "fail";
}
#Override
public void onFragmentInteraction(String uri) {
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout)findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
findViewById(R.id.framecontainerVideo);
Toast.makeText(getApplicationContext(), "bullet", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment fragmentOne = new ChatFragment();
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
}
#Override
protected void onStart() {
super.onStart();
getDelegate().onStart();
}
}
I have written setHasOptionsMenu(true); in onCreate of UserFragment.java
The logout functionality works fine but the search isn't working.
I have tried various options given on Stackoverflow as well as from other resource, but nothing worked. :(
Any help is appreciated.
Thanks in advance.
Create Constructor in your fragment. Pass Context object inside fragment constructor.which allows your activity as global access.
Remove this line and it will work
case R.id.menuSearch:
return true;

PullToRefreshAttacher.OnRefreshListener cannot be resolved to a type

am building an open source project, here is its link
http://slidese.github.io/slidese/2013/11/25/update_listview_item.html
I've imported all library projects which it is using into eclipse. All are fine except PullToRefresh library. it is giving me the error "PullToRefreshAttacher.OnRefreshListener cannot be resolved to a type" where fragment implements it
2nd error is at
mPullToRefreshAttacher.addRefreshableView(mListview, this);
it says "The method addRefreshableView(View, ViewDelegate) in the type PullToRefreshAttacher is not applicable for the arguments (ListView, ContentFragment)"
3rd error is at
#Override
public void onRefreshStarted(View view) {
Intent intent = new Intent(getActivity(), DownloaderService.class);
intent.putExtra(DownloaderService.EXTRA_USER_INITIATED, true);
getActivity().startService(intent);
}
It is asking me to remove override annotation. here is complete code of fragment.
public class ContentFragment extends Fragment implements PullToRefreshAttacher.OnRefreshListener {
private final String TAG = "ContentFragment";
public static final String CONTENT_MODE = "content_mode";
public static final int MODE_ADFREE = 0;
public static final int MODE_PREMIUM = 1;
private StartActivity mListener;
private PullToRefreshAttacher mPullToRefreshAttacher;
private UpdaterAsyncTask mUpdater;
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
ListView mListview;
Button mPlayButton;
ContentAdapter mAdapter;
int mMode;
Map<String, UpdateHolder> mUpdates = new HashMap<String, UpdateHolder>();
public ContentFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (StartActivity) activity;
Log.d(TAG, "Attached podcast list fragment");
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must be the StartActivity");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_content, null);
mListview = (ListView) view.findViewById(android.R.id.list);
mListview.setEmptyView(view.findViewById(R.id.empty_list_view));
mListview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListview.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_menu_content, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if (item.getItemId() == R.id.action_delete) {
SparseBooleanArray checked = mListview.getCheckedItemPositions();
Content[] params = new Content[checked.size()];
int index = 0;
int first = mListview.getFirstVisiblePosition();
int last = mListview.getLastVisiblePosition();
for (int i = 0; i < mListview.getCount(); i++) {
if (checked.get(i)) {
params[index++] = (Content)mListview.getItemAtPosition(i);
if (i >= first && i <= last) {
View view = mListview.getChildAt(i-first);
Animation animation = AnimationUtils.loadAnimation(getActivity(), android.R.anim.slide_out_right);
animation.setDuration(200);
//animation.setFillAfter(true);
animation.setStartOffset(100 * (index) );
view.startAnimation(animation);
}
}
}
new AsyncTask<Content, Void, Void>() {
#Override
protected Void doInBackground(Content... params) {
for (Content content : params) {
File file = Utils.getFilepath(content.getFilename());
file.delete();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mAdapter.notifyDataSetChanged();
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
mode.finish();
return true;
}
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
});
mListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
Content content = mAdapter.getItem(position);
mListener.showContentDetails(content);
}
});
mListview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mScrollState = scrollState;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
mPullToRefreshAttacher = ((StartActivity) getActivity()).getPullToRefreshAttacher();
mPullToRefreshAttacher.addRefreshableView(mListview, this);
mMode = getArguments().getInt(CONTENT_MODE);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onPause() {
super.onPause();
if (mUpdater != null)
mUpdater.stop();
}
#Override
public void onResume() {
super.onResume();
updateAdapter();
mUpdater = new UpdaterAsyncTask();
mUpdater.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void)null);
}
public void refresh() {
updateAdapter();
}
public void replaceCurrentlyPlayingContent() {
GlobalContext.INSTANCE.replaceCurrentlyPLayingContent(mAdapter.getObjects(), mListener.getCurrentTrack());
}
private void updateAdapter() {
Log.d(TAG, "updateAdapter");
//new FetchContentAsyncTask(mMode).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
final String mp3 = mListener.getSavedStateMp3();
final boolean isPlaying = mListener.getSavedStateIsPlaying();
final boolean isPaused = mListener.getSavedStateIsPaused();
List<Content> listOfContent = GlobalContext.INSTANCE.getCachedContent(mMode, mp3, isPlaying, isPaused);
mAdapter = new ContentAdapter(getActivity(), R.layout.list_item_card, listOfContent);
mListview.setAdapter(mAdapter);
}
#Override
public void onRefreshStarted(View view) {
Intent intent = new Intent(getActivity(), DownloaderService.class);
intent.putExtra(DownloaderService.EXTRA_USER_INITIATED, true);
getActivity().startService(intent);
}
private class UpdaterAsyncTask extends AsyncTask<Void, Void, Void> {
boolean isRunning = true;
public void stop() {
isRunning = false;
}
#Override
protected Void doInBackground(Void... params) {
while (isRunning) {
/*
Map<String, UpdateHolder> map = gatherMetadata();
publishProgress(map);
*/
updateCurrentAdapterContent();
publishProgress();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... params) {
super.onProgressUpdate();
if (mScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
// http://stackoverflow.com/questions/2123083/android-listview-refresh-single-row
int start = mListview.getFirstVisiblePosition();
for(int i = start, j = mListview.getLastVisiblePosition(); i<=j; i++) {
View view = mListview.getChildAt(i-start);
if (((Content)mListview.getItemAtPosition(i)).dirty) {
Log.v(TAG, "Content is dirty");
mListview.getAdapter().getView(i, view, mListview);
}
}
}
}
}
private void updateCurrentAdapterContent() {
List<Content> listOfContent = mAdapter.getObjects();
Map<String, UpdateHolder> map = new HashMap<String, UpdateHolder>();
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterByStatus(DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
try {
Cursor cursor = ContentDownloadManager.INSTANCE.query(q);
while (cursor.moveToNext()) {
//long id = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
String uri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI));
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
int downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
float progress = (float)downloaded/(float)total;
UpdateHolder holder = new UpdateHolder();
holder.progress = progress;
holder.status = status;
map.put(uri, holder);
}
cursor.close();
final Content currentContent = mListener.getCurrentTrack();
final boolean isPlaying = mListener.isPlaying();
final boolean isPaused = mListener.isPaused();
for (Content content : listOfContent) {
// First update any download progress we might have for this specific content item
UpdateHolder holder = map.get(content.mp3);
if (holder != null) {
if (content.downloadProgress != holder.progress) {
content.downloadProgress = holder.progress;
content.dirty = true;
}
if (content.downloadStatus != holder.status) {
content.downloadStatus = holder.status;
content.dirty = true;
}
}
else {
if (content.downloadProgress != 0f) {
content.downloadProgress = 0f;
content.dirty = true;
}
if (content.downloadStatus != -1) {
content.downloadStatus = -1;
content.dirty = true;
}
}
// Update with elapsed (to be done)
// File exists?
File file = Utils.getFilepath(content.getFilename());
if (content.exists != file.exists()) {
content.exists = file.exists();
content.dirty = true;
}
// Is this the currently playing content
if (currentContent != null && content.mp3.equals(currentContent.mp3)) {
if (content.isPlaying != isPlaying) {
content.isPlaying = isPlaying;
content.dirty = true;
}
if (content.isPaused != isPaused) {
content.isPaused = isPaused;
content.dirty = true;
}
}
else {
if (content.isPlaying != false) {
content.isPlaying = false;
content.dirty = true;
}
if (content.isPaused != false) {
content.isPaused = false;
content.dirty = true;
}
}
if (content.dirty) {
DatabaseManager.getInstance().createOrUpdateContent(content);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class UpdateHolder {
public String mp3;
public int status;
public boolean played;
public float progress;
public boolean exists = false;
public boolean isPlaying = false;
public boolean isPaused = false;
//public int elapsed;
//public int duration;
}
}
I couldn't find the issue in it. I'm stuck here for last 40 hours. Please help. Thank you!
Maybe you are using old version of the library. I found that PullToRefreshAttacher doesn't contain OnRefreshListener. (https://github.com/chrisbanes/ActionBar-PullToRefresh/blob/master/library/src/main/java/uk/co/senab/actionbarpulltorefresh/library/PullToRefreshAttacher.java)
Try to import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener; and use it instead of PullToRefreshAttacher.OnRefreshListener.

Categories

Resources