I made a question earlier about how to swap from listview to a recyclerview. However I noticed that with my change my update and delete didn't get saved. Which from my understanding has something to do with cursors being needed to update the contents. However currenty I am stuck with the following error
showAdapter = new ShowsAdapter(this, shows); // the error
Error:(68, 50) error: incompatible types: List cannot be converted to Cursor
private List<Show> shows;
private ShowsAdapter showAdapter;
private RecyclerView recyclerView;
private DataSource datasource;
public static final String INTENT_DETAIL_ROW_NUMBER = "Row number";
public static final String INTENT_DETAIL_REMINDER_TEXT = "Reminder text";
public static final int REQUESTCODE = 2;
public static final String EXTRA_SHOW_ID = "extraShowId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
datasource = new DataSource(this);
datasource.open();
recyclerView = (RecyclerView) findViewById(R.id.main_list);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
//recyclerView.setAdapter(showAdapter);
updateUI();
//registerForContextMenu(recyclerView);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.taskView);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(new Intent(MainActivity.this, CreateShowActivity.class), 1);
}
});
}
private void updateUI() {
shows = datasource.getAllShows();
if (showAdapter == null) {
showAdapter = new ShowsAdapter(this, shows); // the error
recyclerView.setAdapter(showAdapter);
} else {
showAdapter.notifyDataSetChanged();
}
}
My Adapter:
private List<Show> mShows;
private Context mContext;
private Cursor mShowsCursor;
public void updateList(List<Show> newlist) {
// Set new updated list
mShows.clear();
mShows.addAll(newlist);
notifyDataSetChanged();
}
public ShowsAdapter(Context mContext, Cursor cursor) {
this.mContext = mContext;
this.mShowsCursor = cursor;
}
#Override
public ShowsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(android.R.layout.simple_list_item_1, null);
// Return a new holder instance
ShowsAdapter.ViewHolder viewHolder = new ShowsAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ShowsAdapter.ViewHolder holder, final int position) {
if (mShowsCursor != null && mShowsCursor.moveToPosition(position)) {
holder.textView.setText(mShowsCursor.getString(mShowsCursor.getColumnIndex(MySQLiteHelper.COLUMN_SHOW)));
}
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, EditShowActivity.class);
intent.putExtra(INTENT_DETAIL_ROW_NUMBER, position);
intent.putExtra(INTENT_DETAIL_REMINDER_TEXT, holder.textView.getText());
((MainActivity) mContext).startActivityForResult(intent, REQUESTCODE);
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
mShows.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,mShows.size());
return true;
}
});
Related
I have an app using tab layout and RecyclerView for getting items. I have 2 different tabs and I wanna use two different fonts on them. I have OneActivity and for tabsi have FirstFragment, SecondFragment.
I can change whole app's font with RecyclerView_Adapter. But i don't wanna change whole app's font. In FirstFragment (First Tab) i wanna use Arial and Text size 20 sp, in SecondFragment i wanna use Comic Sans and Text size 16 sp.
How can i do that, is it possible?
OneActivity.Java
public class OneActivity extends AppCompatActivity {
private static Toolbar toolbar;
private static ViewPager viewPager;
private static TabLayout tabLayout;
private static BottomNavigationView bottomNavigationView;
private ImageButton forwardbtn, backwardbtn, pausebtn, playbtn;
private MediaPlayer mPlayer;
private TextView songName, startTime, songTime;
private SeekBar songPrgs;
private static int oTime =0, sTime =0, eTime =0, fTime = 15000, bTime = 15000;
private Handler hdlr = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
backwardbtn = (ImageButton)findViewById(R.id.btnBackward);
forwardbtn = (ImageButton)findViewById(R.id.btnForward);
playbtn = (ImageButton)findViewById(R.id.btnPlay);
pausebtn = (ImageButton)findViewById(R.id.btnPause);
startTime = (TextView)findViewById(R.id.txtStartTime);
songTime = (TextView)findViewById(R.id.txtSongTime);
mPlayer = MediaPlayer.create(this, R.raw.deneme);
songPrgs = (SeekBar)findViewById(R.id.sBar);
songPrgs.setClickable(false);
pausebtn.setEnabled(false);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);//setting tab over viewpager
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
//Implementing tab selected listener over tablayout
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());//setting current selected item over viewpager
switch (tab.getPosition()) {
case 0:
Log.e("TAG","TAB1");
break;
case 1:
Log.e("TAG","TAB2");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
playbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(OneActivity.this, "One Oynatılıyor", Toast.LENGTH_SHORT).show();
mPlayer.start();
eTime = mPlayer.getDuration();
sTime = mPlayer.getCurrentPosition();
if(oTime == 0){
songPrgs.setMax(eTime);
}
songTime.setText(String.format("%d dk, %d sn", TimeUnit.MILLISECONDS.toMinutes(eTime),
TimeUnit.MILLISECONDS.toSeconds(eTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes(eTime))) );
startTime.setText(String.format("%d dk, %d sn", TimeUnit.MILLISECONDS.toMinutes(sTime),
TimeUnit.MILLISECONDS.toSeconds(sTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes(sTime))) );
songPrgs.setProgress(sTime);
hdlr.postDelayed(UpdateSongTime, 100);
pausebtn.setEnabled(true);
playbtn.setEnabled(false);
}
});
pausebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.pause();
pausebtn.setEnabled(false);
playbtn.setEnabled(true);
Toast.makeText(getApplicationContext(),"One Duraklatıldı", Toast.LENGTH_SHORT).show();
}
});
forwardbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if((sTime + fTime) <= eTime)
{
sTime = sTime + fTime;
mPlayer.seekTo(sTime);
}
else
{
Toast.makeText(getApplicationContext(), "Daha fazla ileri sarılamaz", Toast.LENGTH_SHORT).show();
}
if(!playbtn.isEnabled()){
playbtn.setEnabled(true);
}
}
});
backwardbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if((sTime - bTime) > 0)
{
sTime = sTime - bTime;
mPlayer.seekTo(sTime);
}
else
{
Toast.makeText(getApplicationContext(), "Daha fazla geri sarılamaz", Toast.LENGTH_SHORT).show();
}
if(!playbtn.isEnabled()){
playbtn.setEnabled(true);
}
}
});
}
public Runnable UpdateSongTime = new Runnable() {
#Override
public void run() {
sTime = mPlayer.getCurrentPosition();
startTime.setText(String.format("%d dk, %d sn", TimeUnit.MILLISECONDS.toMinutes(sTime),
TimeUnit.MILLISECONDS.toSeconds(sTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(sTime))) );
songPrgs.setProgress(sTime);
hdlr.postDelayed(this, 100);
songPrgs.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mPlayer != null && fromUser){
mPlayer.seekTo(progress); // clear ' * 1000 '
}
}
});
}
};
public void onBackPressed(){
mPlayer.stop();
finish();
}
//Setting View Pager
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new FirstFragment("Android"), "Android");
adapter.addFrag(new SecondFragment("Ios"), "Ios");
viewPager.setAdapter(adapter);
}
//View Pager fragments setting adapter class
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();//fragment arraylist
private final List<String> mFragmentTitleList = new ArrayList<>();//title arraylist
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
//adding fragments and title method
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
FirstFragment
public class FirstFragment extends Fragment {
private View view;
private String title;//String for tab title
private String ebaka;
// Intent it = getActivity().getIntent();
// String isim = getActivity().getIntent().getStringExtra("FOO");
// Bundle bundle = getActivity().getIntent().getExtras();
// String value = bundle.getString("key1");
private static RecyclerView recyclerView;
public FirstFragment() {
}
#SuppressLint("ValidFragment")
public FirstFragment(String title) {
this.title = title;//Setting tab title
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.dummy_fragment, container, false);
// getActivity().getActionBar().setTitle(title);
setRecyclerView();
return view;
}
//Setting recycler view
private void setRecyclerView() {
recyclerView = (RecyclerView) view
.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView
.setLayoutManager(new LinearLayoutManager(getActivity()));//Linear Items
// String[] eArray=getActivity().getResources().getStringArray(R.array.books);
//
String[] ebaka=getActivity().getResources().getStringArray(R.array.bakara);
ArrayList<String> arrayList = new ArrayList<>();
// arrayList.add("cdscsdc");
for (int i = 0; i < ebaka.length; i++) {
arrayList.add(ebaka[i]);
}
RecyclerView_Adapter adapter = new RecyclerView_Adapter(getActivity(), arrayList);
recyclerView.setAdapter(adapter);// set adapter on recyclerview
}
}
RecyclerView_Adapter
public class RecyclerView_Adapter extends RecyclerView.Adapter<DemoViewHolder> {
private ArrayList<String> arrayList;
private Context context;
public RecyclerView_Adapter(Context context,
ArrayList<String> arrayList) {
this.context = context;
this.arrayList = arrayList;
this.arrayList = arrayList;
}
#Override
public int getItemCount() {
return (null != arrayList ? arrayList.size() : 0);
}
#Override
public void onBindViewHolder(DemoViewHolder holder,
int position) {
Typeface customTypeOne = Typeface.createFromAsset(context.getAssets(), "arial.ttf");
final DemoViewHolder mainHolder = (DemoViewHolder) holder;
//Setting text over textview
mainHolder.title.setText(arrayList.get(position));
mainHolder.title.setTypeface(customTypeOne); // With this code i change font, but it is changing whole apps font. i don't need that.
}
#Override
public DemoViewHolder onCreateViewHolder(
ViewGroup viewGroup, int viewType) {
LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext());
ViewGroup mainGroup = (ViewGroup) mInflater.inflate(
R.layout.item_row, viewGroup, false);
DemoViewHolder mainHolder = new DemoViewHolder(mainGroup) {
#Override
public String toString() {
return super.toString();
}
};
return mainHolder;
}
}
DemoViewHolder
public abstract class DemoViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public DemoViewHolder(View view) {
super(view);
this.title = (TextView) view.findViewById(R.id.cardTitle);
}
}
Update your adapter constructor and onBindViewHolder():
public class RecyclerView_Adapter extends RecyclerView.Adapter<DemoViewHolder> {
private ArrayList<String> arrayList;
private Context context;
//add this
private String comingFrom;
//constructor
public RecyclerView_Adapter(Context context, ArrayList<String> arrayList, String comingFrom) {
this.context = context;
this.arrayList = arrayList;
this.arrayList = arrayList;
this.comingFrom = comingFrom;
}
........
........
#Override
public void onBindViewHolder(DemoViewHolder holder,int position) {
Typeface customTypeOne = Typeface.createFromAsset(context.getAssets(),"arial.ttf");
final DemoViewHolder mainHolder = (DemoViewHolder) holder;
//Setting text over textview
mainHolder.title.setText(arrayList.get(position));
//check in which fragment you are
if(comingFrom.equals("fragment_one")){
//in fragment one set some font
mainHolder.title.setTypeface(........);
}else{
//in fragment two set some other font
mainHolder.title.setTypeface(.........);
}
}
............
}
When initializing adapter from FirstFragment:
.......
.......
RecyclerView_Adapter adapter = new RecyclerView_Adapter(getActivity(), arrayList, "fragment_one");
recyclerView.setAdapter(adapter);// set adapter on recyclerview
........
When initializing adapter from SecondFragment:
.......
.......
RecyclerView_Adapter adapter = new RecyclerView_Adapter(getActivity(), arrayList, "fragment_two");
recyclerView.setAdapter(adapter);// set adapter on recyclerview
........
I want to display number of total items of my recyclerview in a textview. If new item is added or deleted that textview should be update. And also calculate total price of items in a list of Items in a recyclerview and display in a textview below recyclerview list.
Below is my recyclerview adapter:
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder> {
private List<ProductView.Data> productData = Collections.emptyList();
static List<ProductModel> productModelList;
static Context context;
DatabaseHandler mDatabaseHandler;
public CartAdapter(Context context, List<ProductModel> dbList ){
this.productModelList = new ArrayList<ProductModel>();
this.context = context;
this.productModelList = dbList;
mDatabaseHandler = new DatabaseHandler( context );
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View cartListView = inflater.inflate(R.layout.list_item_cart, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(context,cartListView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.tvProductName.setText(productModelList.get(position).getTitle());
holder.tvProductPrice.setText(productModelList.get(position).getPrice());
Glide
.with(context)
.load(productModelList.get(position).getImageUrl())
.into(holder.imgProduct);
// holder.tvProductStatus.setText(productModelList.get(position).getIsAvailable());
holder.tvSize.setText(productModelList.get(position).getSize());
holder.tvProductQuantity.setText(Integer.toString(productModelList.get(position).getQuantity()));
holder.tvColor.setText(productModelList.get(position).getColor());
//holder.tvMaterial.setText(productModelList.get(position).getMaterial());
holder.imgDelete.setClickable(true);
holder.imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String idForDelete = String.valueOf(productModelList.get(position).getVariantId());
mDatabaseHandler.deleteARow(idForDelete);
productModelList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,productModelList.size());
}
});
}
#Override
public int getItemCount() {
return productModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvProductName, tvProductPrice, tvProductQuantity,tvColor,
tvSize;
ImageView imgProduct;
ImageButton imgDelete;
Context context;
public ViewHolder(Context mContext, View itemView) {
super(itemView);
this.tvProductName = (TextView) itemView.findViewById(R.id.tv_cart_product_name);
this.tvProductPrice = (TextView) itemView.findViewById(R.id.tv_cart_product_price);
this.tvProductQuantity = (TextView) itemView.findViewById(R.id.tv_cart_product_Quantity);
this.imgProduct = (ImageView) itemView.findViewById(R.id.img_cart_item_product);
this.tvColor = (TextView)itemView.findViewById(R.id.tv_color);
this.tvSize = (TextView) itemView.findViewById(R.id.tv_size);
this.imgDelete = (ImageButton) itemView.findViewById(R.id.img_cart_delete);
// store the context ///
this.context = mContext;
}
}
and java Class:
public class CartActivity extends AppCompatActivity {
DatabaseHandler helper;
List<ProductModel> dbList;
RecyclerView mRecyclerView;
Toolbar toolbar;
Button btnCheckout, btnContinueShopping;
TextView tvTotalNoOfItems, tvTotalPrice;
String p;
String i;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
p = getIntent().getStringExtra("variant_id");
i = getIntent().getStringExtra("product_id");
Bundle extras = getIntent().getExtras();
if (extras != null) {
p = extras.getString("variant_id");
i= extras.getString("product_id");
}
toolbar = (Toolbar) findViewById(R.id.customToolBar);
setSupportActionBar(toolbar);
setTitle("Check-out");
toolbar.setTitleTextColor(Color.BLACK);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
helper = new DatabaseHandler(this);
dbList= new ArrayList<ProductModel>();
dbList = helper.getDataFromDB();
mRecyclerView = (RecyclerView)findViewById(R.id.rv_cart_item_list);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new CartAdapter(this,dbList);
mRecyclerView.setAdapter(mAdapter);
tvTotalNoOfItems = (TextView)findViewById(R.id.tvTotalCartItems);
tvTotalPrice = (TextView)findViewById(R.id.tvTotalCartItemsPrice);
String totalPrice = "";
for (int i = 0; i<dbList.size(); i++)
{
totalPrice = totalPrice + dbList.get(i).getPrice().toString();
}
tvTotalPrice.setText(totalPrice);
btnContinueShopping = (Button)findViewById(R.id.btnBackToProductActivity);
btnContinueShopping.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCOllectionActivity = new Intent(CartActivity.this, CollectionActivity.class);
startActivity(launchCOllectionActivity);
finish();
}
});
btnCheckout = (Button)findViewById(R.id.btn_checkout);
btnCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCheckoutActivity = new Intent(CartActivity.this,CheckoutActivity.class);
startActivity(launchCheckoutActivity);
}
});
}
}
First, add following getter to your adapter:
public List<ProductModel> getItems(){
return productModelList;
}
Then, you can subscribe on adapter data change and do the following:
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged () {
tvTotalNoOfItems.setText(mAdapter.getItemCount());
String totalPrice = "";
for (int i = 0; i < ((CartAdapter)mAdapter).getItems().size(); i++) {
totalPrice = totalPrice + ((CartAdapter)mAdapter).getItems().get(i).getPrice().toString();
}
tvTotalPrice.setText("" + totalPrice);
}
});
just add this line below the adapter set line
tvTotalNoOfItems.setText(mAdapter.getCount());
and add this into you adapter class where you delete action perform
String totalPrice = "";
((CartActivity)context).tvTotalNoOfItems.setText(getCount());
for (int i = 0; i<productModelList.size(); i++)
{
totalPrice = totalPrice + productModelList.get(i).getPrice().toString();
}
((CartActivity)context).tvTotalPrice.setText(""+totalPrice);
Just public you textview like this
public TextView tvTotalNoOfItems, tvTotalPrice;
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
So I've set up my RecyclerView with SQLite DB and it's populating the list, but every time I click on the list item it should open the new activity and pass data to it via intent extras.
The click gives me NullPointerException:
Process: com.daroioradecic.fxtodo, PID: 6762
java.lang.NullPointerException: Attempt to invoke interface method 'void data.RecAdapter$ItemClickCallback.onItemClick(int)' on a null object reference
at data.RecAdapter$RecHolder.onClick(RecAdapter.java:106)
at android.view.View.performClick(View.java:4856)
at android.view.View$PerformClick.run(View.java:19956)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5389)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
in my Recycler View adapter class which is:
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.RecHolder> {
private int previousPosition = 0;
private List<Todo> listData;
private LayoutInflater inflater;
private ItemClickCallback itemClickCallback;
public interface ItemClickCallback {
void onItemClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback) {
this.itemClickCallback = itemClickCallback;
}
public RecAdapter(List<Todo> listData, Context c) {
this.inflater = LayoutInflater.from(c);
this.listData = listData;
}
#Override
public RecHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.layout_row_za_listu, parent, false);
return new RecHolder(view);
}
#Override
public void onBindViewHolder(RecHolder holder, int position) {
Todo item = listData.get(position);
holder.title.setText(item.getTitle());
if (position > previousPosition) {
AnimationUtil.animate(holder, true);
} else {
AnimationUtil.animate(holder, false);
}
previousPosition = position;
}
#Override
public int getItemCount() {
return listData.size();
}
public void setListData(ArrayList<Todo> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
class RecHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView title;
private View container;
public RecHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.tekstNaListi);
container = itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
}
#Override
public void onClick(View v) {
itemClickCallback.onItemClick(getAdapterPosition());
}
}
}
It gives the error on line itemClickCallback.onItemClick(getAdapterPosition()); which is the last line in the class.
I'm overriding onClick in the class where recycler view is populated like this:
#Override
public void onItemClick(int p) {
Todo item = (Todo) listData.get(p);
Intent i = new Intent(HomeScreen.this, Details.class);
Bundle extras = new Bundle();
extras.putString("naslov", item.getTitle());
extras.putString("datum", item.getRecordDate());
extras.putInt("id", item.getItemId());
startActivity(i);
}
That class implements implements RecAdapter.ItemClickCallback
Any ideas? Thanks!
MAIN ACTIVITY CLASS: (keep in mind that I just transitioned from ListView so I haven't done any cleaning)
public class HomeScreen extends AppCompatActivity implements RecAdapter.ItemClickCallback {
private RecyclerViewUtils.ShowHideToolbarOnScrollingListener showHideToolbarListener;
//SCROLL
private Toolbar tToolbar;
// REC
private RecyclerView recView;
private RecAdapter adapter;
private ArrayList listData;
// ZA SNACKBAR
private CoordinatorLayout coordinatorLayout;
private RelativeLayout relLay;
// NAVIGACIJA
private DrawerLayout mDrawer;
private ActionBarDrawerToggle drawerToggle;
private Toolbar toolbar;
NavigationView nvDrawer;
DrawerLayout dlDrawer;
//----------------------------------------------------------------------------------------------
DatabaseHandler dba;
private ArrayList<Todo> dbTodo = new ArrayList<>();
private TodoAdapter todoAdapter;
private ListView lista;
private Cursor mCursor;
LinearLayout layoutZaUnosTodoa;
EditText editTextZaNazivTodoa;
Button buttonSave;
private CheckBox checkBoxDoneOrNotNaListi;
android.support.design.widget.FloatingActionButton fab;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.activity_home_screen);
tToolbar = (Toolbar) findViewById(R.id.tToolbar);
setSupportActionBar(tToolbar);
tToolbar.setNavigationIcon(R.drawable.ic_nav_menu);
getSupportActionBar().setTitle(R.string.app_name);
// REC
recView = (RecyclerView) findViewById(R.id.rec_list);
recView.setLayoutManager(new LinearLayoutManager(this));
adapter = new RecAdapter(listData, this);
recView.setAdapter(adapter);
adapter.setItemClickCallback(this);
recView.addOnScrollListener(showHideToolbarListener = new RecyclerViewUtils.ShowHideToolbarOnScrollingListener(tToolbar));
if (savedInstanceState != null) {
showHideToolbarListener.onRestoreInstanceState((RecyclerViewUtils.ShowHideToolbarOnScrollingListener.State) savedInstanceState
.getParcelable(RecyclerViewUtils.ShowHideToolbarOnScrollingListener.SHOW_HIDE_TOOLBAR_LISTENER_STATE));
}
layoutZaUnosTodoa = (LinearLayout) findViewById(R.id.layoutZaUnosTodoa);
editTextZaNazivTodoa = (EditText) findViewById(R.id.editTextZaNazivTodoa);
editTextZaNazivTodoa.setSelection(editTextZaNazivTodoa.getText().length());
buttonSave = (Button) findViewById(R.id.buttonSave);
//lista = (ListView) findViewById(R.id.lista);
fab = (android.support.design.widget.FloatingActionButton) findViewById(R.id.fab);
checkBoxDoneOrNotNaListi = (CheckBox) findViewById(R.id.checkBoxDoneOrNotNaListi);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordiantorLayout);
relLay = (RelativeLayout) findViewById(R.id.relLay);
refreshData();
layoutZaUnosTodoa.setVisibility(View.GONE);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layoutZaUnosTodoa.setVisibility(View.VISIBLE);
}
});
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveToDB();
layoutZaUnosTodoa.setVisibility(View.GONE);
}
});
relLay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layoutZaUnosTodoa.setVisibility(View.GONE);
}
});
dlDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
dlDrawer.setDrawerListener((DrawerLayout.DrawerListener) drawerToggle);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
drawerToggle.syncState();
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(RecyclerViewUtils.ShowHideToolbarOnScrollingListener.SHOW_HIDE_TOOLBAR_LISTENER_STATE,
showHideToolbarListener.onSaveInstanceState());
super.onSaveInstanceState(outState);
}
private void saveToDB() {
Todo todo = new Todo();
todo.setTitle(editTextZaNazivTodoa.getText().toString());
dba.addTodo(todo);
adapter.notifyDataSetChanged();
dba.close();
editTextZaNazivTodoa.setText("");
}
public void refreshData() {
dbTodo.clear();
dba = new DatabaseHandler(HomeScreen.this);
ArrayList<Todo> todoFromDB = dba.getTodo();
for (int i = 0; i < todoFromDB.size(); i++) {
String title = todoFromDB.get(i).getTitle();
String dateText = todoFromDB.get(i).getRecordDate();
int mid = todoFromDB.get(i).getItemId();
Todo myTodo = new Todo();
myTodo.setTitle(title);
myTodo.setItemId(mid);
myTodo.setRecordDate(dateText);
dbTodo.add(myTodo);
}
dba.close();
adapter = new RecAdapter(dbTodo, this);
recView.setAdapter(adapter);
// todoAdapter = new TodoAdapter(HomeScreen.this, R.layout.layout_row_za_listu, dbTodo);
//Animation collapseList = AnimationUtils.loadAnimation(HomeScreen.this, R.anim.collapse_search_results);
//lista.startAnimation(collapseList);
//lista.setAdapter(todoAdapter);
// todoAdapter.notifyDataSetChanged();
}
#Override
public void onItemClick(int p) {
Todo item = (Todo) listData.get(p);
Intent i = new Intent(HomeScreen.this, Details.class);
Bundle extras = new Bundle();
extras.putString("naslov", item.getTitle());
extras.putString("datum", item.getRecordDate());
extras.putInt("id", item.getItemId());
startActivity(i);
}
/* #Override
public void onSecondaryItemClick(int p) {
}*/
public class TodoAdapter extends ArrayAdapter<Todo> {
Activity activity;
int layoutResource;
Todo todo;
ArrayList<Todo> mData = new ArrayList<>();
public TodoAdapter(Activity act, int resource, ArrayList<Todo> data) {
super(act, resource, data);
activity = act;
layoutResource = resource;
mData = data;
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Todo getItem(int position) {
return mData.get(position);
}
#Override
public int getPosition(Todo item) {
return super.getPosition(item);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null || (row.getTag() == null)) {
LayoutInflater inflater = LayoutInflater.from(activity);
row = inflater.inflate(layoutResource, null);
holder = new ViewHolder();
holder.mTitle = (TextView) row.findViewById(R.id.tekstNaListi);
holder.checkBox = (CheckBox) row.findViewById(R.id.checkBoxDoneOrNotNaListi);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
holder.myTodo = getItem(position);
holder.mTitle.setText(holder.myTodo.getTitle());
final ViewHolder finalHolder = holder;
holder.mTitle.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
int mid = finalHolder.myTodo.getItemId();
DatabaseHandler dba = new DatabaseHandler(HomeScreen.this);
dba.deleteTodo(mid);
Snackbar snackbar = Snackbar.make(coordinatorLayout, getResources().getString(R.string.snack_bar_tekst), Snackbar.LENGTH_SHORT);
snackbar.show();
todoAdapter.notifyDataSetChanged();
return true;
}
});
/*holder.mTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = finalHolder.myTodo.getTitle().toString();
String dateText = finalHolder.myTodo.getRecordDate().toString();
int mid = finalHolder.myTodo.getItemId();
Intent i = new Intent(HomeScreen.this, Details.class);
i.putExtra("naslov", title);
i.putExtra("datum", dateText);
i.putExtra("id", mid);
startActivity(i);
}
});*/
final View finalRow = row;
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalHolder.mTitle = (TextView) finalRow.findViewById(R.id.tekstNaListi);
if (finalHolder.checkBox.isChecked()) {
finalHolder.mTitle.setPaintFlags(finalHolder.mTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
finalHolder.mTitle.setAlpha(0.5f);
} else if (!finalHolder.checkBox.isChecked()) {
finalHolder.mTitle.setPaintFlags(0);
finalHolder.mTitle.setAlpha(0.8f);
}
}
});
return row;
}
}
class ViewHolder {
Todo myTodo;
TextView mTitle, mContent, mDate;
int mId;
CheckBox checkBox;
}
EDIT:
This error shows up:
java.lang.NullPointerException: Attempt to invoke interface method 'void data.RecAdapter$ItemClickCallback.onItemClick(int)' on a null object reference
at data.RecAdapter$1.onClick(RecAdapter.java:67)
and it refeers to this line in adapter class:
itemClickCallback.onItemClick(position);
1) Check the callback null or not.
#Override
public void onClick(View v) {
if (itemClickCallback!=null){
itemClickCallback.onItemClick(getAdapterPosition());
}
}
2) The activity/class implements the method. This is okay. But, are you set the listener in your onCreate() ?
rectAdapter.setItemClickCallback(this);
3)EDITED Change your adapter like this:
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.RecHolder> {
private int previousPosition = 0;
private List<Todo> listData;
private LayoutInflater inflater;
private ItemClickCallback itemClickCallback;
public interface ItemClickCallback {
void onItemClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback) {
this.itemClickCallback = itemClickCallback;
}
public RecAdapter(List<Todo> listData, Context c) {
this.inflater = LayoutInflater.from(c);
this.listData = listData;
}
#Override
public RecHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.layout_row_za_listu, parent, false);
return new RecHolder(view);
}
#Override
public void onBindViewHolder(RecHolder holder, final int position) {
Todo item = listData.get(position);
holder.title.setText(item.getTitle());
if (position > previousPosition) {
AnimationUtil.animate(holder, true);
} else {
AnimationUtil.animate(holder, false);
}
previousPosition = position;
holder.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickCallback.onItemClick(position);
}
});
}
#Override
public int getItemCount() {
return listData.size();
}
public void setListData(ArrayList<Todo> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
class RecHolder extends RecyclerView.ViewHolder {
private TextView title;
private View container;
public RecHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.tekstNaListi);
container = itemView.findViewById(R.id.cont_item_root);
}
}}
I'm trying to pass an Image/Poster between activities through intent. I have used Picasso library and Recycler Adapter. but I'm unable to set the image in bundle extras after getting intent. after Year and title.
public class ShowMovieDetails extends AppCompatActivity implements OnNetworkCallHandled,RecyclerViewAdapter.OnClickListener {
private RecyclerViewAdapter adapter;
public RecyclerView recyclerView;
private DataWrapper list;
public Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_movie_details);
context=this;
Intent intent = getIntent();
String movieName = intent.getExtras().getString("moviename", "");
if (movieName != null) {
new MovieTask(movieName, this).execute();
}
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public void onNetworkcallSuccess(Object object) {
//json to gson
String result = (String) object;
Gson gson = new Gson();
list = gson.fromJson(result, DataWrapper.class);
adapter = new RecyclerViewAdapter(list.getSearch(),this, this);
recyclerView.setAdapter(adapter);
System.out.print(result);
System.out.println("On success");
}
#Override
public void onNetworkcallFailure(Object object) {
System.out.println("On failure");
}
#Override
public void onClick(View view, int position, long itemId) {
startActivity(position);
System.out.println();
}
private void startActivity(int position) {
Intent intent = new Intent(this, DetailActivity.class);
Bundle extras = new Bundle();
extras.putString("Title", list.getSearch().get(position).getTitle());
extras.putString("Year", list.getSearch().get(position).getYear());
extras.putString("Poster",list.getSearch().get(position).getPoster());
intent.putExtras(extras);
startActivity(intent);
}
}
and the other class where m setting things in extras
public class DetailActivity extends AppCompatActivity {
private TextView Title;
private TextView Year;
private ImageView Image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
Title = (TextView) findViewById(R.id.Title);
Year = (TextView) findViewById(R.id.Year);
Image = (ImageView) findViewById(R.id.iVPoster);
if (intent != null) {
String title = extras.getString("Title");
String year=extras.getString("Year");
String image=extras.getString("Poster");
Title.setText(title);
Year.setText(year);
System.out.println();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
my recyclerAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MovieDetailsHolder> {
private ArrayList<MovieDetails> movieDetails;
private Context context;
private OnClickListener onClick;
RecyclerViewAdapter(ArrayList<MovieDetails> movieDetails, Context context, OnClickListener onClick) {
this.onClick = onClick;
this.movieDetails = movieDetails;
this.context = context;
}
#Override
public MovieDetailsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view, parent, false);
return new MovieDetailsHolder(view);
}
#Override
public void onBindViewHolder(MovieDetailsHolder holder, final int position) {
holder.tVMovieName.setText(movieDetails.get(position).getTitle());
Picasso
.with(context)
.load(movieDetails.get(position).getPoster())
.into(holder.iVPoster);
holder.setOnClickListener(onClick);
}
#Override
public int getItemCount() {
return movieDetails.size();
}
public static class MovieDetailsHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private OnClickListener onClickListener;
CardView cv;
TextView tVMovieName;
ImageView iVPoster;
MovieDetailsHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cardView);
tVMovieName = (TextView) itemView.findViewById(R.id.tVMovieName);
iVPoster = (ImageView) itemView.findViewById(R.id.iVPoster);
itemView.setOnClickListener(this);
}
public void setOnClickListener(OnClickListener onClickListener) {
this.onClickListener = onClickListener;
}
#Override
public void onClick(View v) {
onClickListener.onClick(v, getPosition(), getItemId());
}
}
public interface OnClickListener {
public void onClick(View view, int position, long itemId);
}
}
In your startActivity() function, just as you got Title,Year and Poster; also get the url to the image.
This answer will help you.
I need to chceck if all items on adapter have a boolean value = true
Then based on result i have to change floatingActionButton color.
I have no idea how to do it.
Here is my Adapter:
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference basementReference = db.collection("basement");
private TableAdapter tableAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton basement = findViewById(R.id.button_basement);
basement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
});
setUpRecyclerView();
}
private void setUpRecyclerView(){
final Query query = basementReference.orderBy("tableNumber",Query.Direction.ASCENDING);
FirestoreRecyclerOptions<Table> options = new FirestoreRecyclerOptions.Builder<Table>()
.setQuery(query, Table.class)
.build();
tableAdapter = new TableAdapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(tableAdapter); tableAdapter.setOnItemClickListener(new TableAdapter.OnItemCLickListener() {
#Override
public void onItemClick(final DocumentSnapshot documentSnapshot, int position) {
Table table = documentSnapshot.toObject(Table.class);
if(table.isTableOccupied()){
basementReference.document(documentSnapshot.getId()).update("tableOccupied",false).addOnCompleteListener(new OnCompleteListener<Void>() {
}else {
basementReference.document(documentSnapshot.getId()).update("tableOccupied",true).addOnCompleteListener(new OnCompleteListener<Void>() {
}
#Override
protected void onStart() {
super.onStart();
tableAdapter.startListening();
}
please help. i tthink i need to do it in my adapter class, but if there is other solution i'll be glad to follow :)
tableAdapter class:
class TableAdapter extends FirestoreRecyclerAdapter {
public TableAdapter(#NonNull FirestoreRecyclerOptions<Table> options) {
super(options);
}
private OnItemCLickListener onItemCLickListener;
private int occupiedMarker = 0;
#Override
protected void onBindViewHolder(#NonNull TableHolder holder, int position, #NonNull Table model) {
holder.textViewTableNumber.setText(model.getTableNumber());
holder.textViewTableSeats.setText(model.getTableSeats());
holder.textViewTableOccupied.setText(String.valueOf(model.isTableOccupied()));
}
#NonNull
#Override
public TableHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_table,parent,false);
return new TableHolder(v);
}
class TableHolder extends RecyclerView.ViewHolder{
TextView textViewTableNumber;
TextView textViewTableSeats;
TextView textViewTableOccupied;
public TableHolder(#NonNull View itemView) {
super(itemView);
textViewTableNumber = itemView.findViewById(R.id.text_view_table_number);
textViewTableSeats = itemView.findViewById(R.id.text_view_table_seats);
textViewTableOccupied = itemView.findViewById(R.id.text_view_table_occupied);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && onItemCLickListener!=null){
onItemCLickListener.onItemClick( getSnapshots().getSnapshot(position), position );
}
}
});
}
}
public interface OnItemCLickListener {
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemCLickListener onItemClickListener){
this.onItemCLickListener = onItemClickListener;
}
}