My MainActivity has a recyclerview that will receive the products. In the floatActionButton of MainActivity and I call AddActivity which has the fields to add the product, including a recycler where I insert inputs to compose the price. the problem is exactly in the AddActivity recyclerView
I have a simple recyclerView and the adapter below where I do the CRUD before saving to the database, and everything works except the update, where I update the item through the adapter but the view in the list does not update the data. If you click on the same item to edit it again it shows the values that have already been updated and not those shown in the list.
Below my adapter:
public class InsumoAdapter extends RecyclerView.Adapter<InsumoAdapter.InsumoViewHolder>{
private final Context context;
private List<Insumo> insumos;
public InsumoAdapter(Context context, List<Insumo> insumos) {
this.context = context;
this.insumos = insumos;
}
#Override
public InsumoAdapter.InsumoViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.card_teste, viewGroup, false);
InsumoAdapter.InsumoViewHolder holder = new InsumoAdapter.InsumoViewHolder(view);
return holder;
}
public static class InsumoViewHolder extends RecyclerView.ViewHolder{
public TextView tNome, tVlrCusto;
ImageButton btnDelete;
CardView cardView;
public InsumoViewHolder(View view){
super(view);
tNome = (TextView) view.findViewById(R.id.txtNomeProd);
tVlrCusto = (TextView) view.findViewById(R.id.txtValorProd);
btnDelete = (ImageButton) view.findViewById(R.id.imgBtnDel);
cardView = (CardView) view.findViewById(R.id.cardProduto);
}
}
#Override
public void onBindViewHolder(final InsumoViewHolder holder, final int position) {
if(insumos.size() != 0){
final Insumo p = insumos.get(position);
holder.tNome.setText(p.getNomeInsumo());
holder.tVlrCusto.setText(p.getValor().toString());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Clicou no Card para Editar na posição "+position,Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
//bundle.putString("nome", p.getNomeInsumo());
//bundle.putDouble("valor", p.getValor());
bundle.putInt("position", position);
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtras(bundle);
context.startActivity(intent);
//update(p, position);
}
});
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Clicou no Card para Excluir na posição "+position,Toast.LENGTH_SHORT).show();
delete(position);
}
});
}
}
#Override
public int getItemCount() {
return this.insumos != null ? this.insumos.size() : 0;
}
private void excluirInsumo(Context context, final int i){
String titulo = "Excluir";
String msg = "Deseja excluir este item?";
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(titulo);
alertDialog.setMessage(msg);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Sim",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//deleta("Pproduto",produtos.get(i).get_id());
AddActivity addActivity = new AddActivity();
//addActivity.deleta(i);
dialog.dismiss();
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Não",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void delete(int position){
insumos.remove(position);
notifyItemRemoved(position);
}
public void update(Insumo insumo, int position){
insumos.set(position, insumo);
//notifyItemChanged(position);
notifyDataSetChanged();
}
public void insere(Insumo insumo){
insumos.add(insumo);
notifyDataSetChanged();
}
It's like not going back to onBindViewHolder to update the data. Could someone give me a light? If you need something, but you can't find any way.
Editing-----
AddActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
edtNome = (TextInputEditText) findViewById(R.id.edtNome);
valorCusto = (TextView) findViewById(R.id.txtValorCustoAdd);
valorVenda = (TextView) findViewById(R.id.txtValorVendaAdd);
valorPerc = (TextView) findViewById(R.id.txtValorPercAdd);
addItem = (FloatingActionButton) findViewById(R.id.fltBtnAddItem);
addFoto = (FloatingActionButton) findViewById(R.id.fltBtnAddFoto);
salvar = (FloatingActionButton) findViewById(R.id.fltBtnSalvar);
imgFoto = (ImageView) findViewById(R.id.imgFoto);
recyclerView = (RecyclerView) findViewById(R.id.recy);
edtNome.setTextIsSelectable(true);
valorCusto.setText(valor.toString());
valorPerc.setText("0");
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
InsumoAdapter insumoAdapter = new InsumoAdapter(getApplicationContext(), insumos);
recyclerView.setAdapter(insumoAdapter);
insumoAdapter.notifyDataSetChanged();
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplication(), InsertActivity.class);
startActivity(intent);
}
});
salvar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Produto produto = new Produto();
produto.setpNome(edtNome.getText().toString());
produto.setpValorCusto(somaValor(insumos));
if(foto == 0){
produto.setPfoto(R.drawable.noimage);
}else{
produto.setPfoto(foto);
}
}
});
}
Activity of insumo's insert
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
insumo = new Insumo();
insumo.setNomeInsumo(nome.getText().toString());
Log.d(TAG, getClass()+" insumo.getNome = "+insumo.getNomeInsumo());
insumo.setValor(Double.parseDouble(valor.getText().toString()));
Log.d(TAG, getClass()+" insumo.getValor = "+insumo.getValor());
AddActivity addActivity = new AddActivity();
//addActivity.update(insumo, pos);
InsumoAdapter insumoAdapter = new InsumoAdapter(getBaseContext(), addActivity.lista());
insumoAdapter.update(insumo, pos);
insumoAdapter.notifyDataSetChanged();
finish();
}
});
MainAcitvity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerTeste);
FloatingActionButton btn = (FloatingActionButton) findViewById(R.id.fltBtnAdd);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
ProdutoAdapter produtoAdapter = new ProdutoAdapter(getBaseContext(), produtos);
recyclerView.setAdapter(produtoAdapter);
produtoAdapter.notifyDataSetChanged();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
The problem is; you're creating a new instance of adapter instead of using the adapter attached to your recyclerView. Please use the same instance of adapter that's attached to your recyclerView.
In your Activity where your recyclerView is instantiated, use a member reference to contain your reference. i.e. mInsumoAdapter
Then when you create your first adapter instance and attach it to your recyclerView, assign it to mInsumoAdapter.
Finally use the same reference to call your update method.
mInsumoAdapter.update(insumo, pos);
For sharing references between activities and services, you can create a common sharing class like this:
public class ReferenceUtil {
private static InsumoAdapter insumoAdapter;
public static InsumoAdapter getMainAdapter(){
return insumoAdapter;
}
public static void setMainAdapter(InsumoAdapter adapter) {
insumoAdapter = adapter;
}
}
Then use ReferenceUtil.setMainAdapter(adapter); when you click on your FAB, and on your next activity use ReferenceUtil.getMainAdapter(); to obtain your attached reference and update that for your recyclerView to get updated on runtime.
Remember to set the static insumoAdapter in ReferenceUtil to null when you return back to your previous activity because it could lead to a memory leak in your application.
Instead of creating a new Adapter, just use the current adapter instance and use it for update and notifyDataSetChanged.
public InsumoAdapter insumoAdapter;
// Inside onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
....
insumoAdapter = new InsumoAdapter(getApplicationContext(), insumos);
....
}
// Inside Update onClick
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
....
insumoAdapter.update(insumo, pos)
insumoAdapter.notifyDataSetChanged()
}
Try with using notifyDataSetChnaged() in the activity from where you are passing the list to the adapter or you could do it after updating it. something like this,
RecyclerView.setAdapter(this,list);
notifyDataSetChanged();
or
InsumoAdapter.update(list,pos);
notifyDataSetChanged();
You could try use this way for all the CRUD operations.
Related
Listener in Android Studio RecyclerView custom adapter is returning null.
This is the Interface
private OnItemClickListener mlistener;
public interface OnItemClickListener{
void onItemClick(int position, Boolean paid);
}
public void setOnItemClickListener(OnItemClickListener listener){
mlistener = listener;
}
And this is the View Holder with the Listener. This is intended to pass a Boolean to the main activity.
public CartViewHolder(View itemView, ArrayList<Shift> shifts, OnItemClickListener listener) {
super(itemView);
paid = itemView.findViewById(R.id.due_back_paid);
containerView = itemView.findViewById(R.id.container);
paid.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onItemClick(position, isChecked);
}
}
}
});
containerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Shift current = (Shift)containerView.getTag();
Intent intent = new Intent(v.getContext(), ViewShiftActivity.class);
intent.putExtra("thisShift", current);
intent.putExtra("shifts", shifts);
v.getContext().startActivity(intent);
}
});
}
}
public LoadAdapter(ArrayList<Shift> shifts){
shiftList = shifts;
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.shift_row, parent, false);
CartViewHolder mvh = new CartViewHolder(view, shiftList, mlistener);
return mvh;
}
I have used this code in other projects and it works. I have can't seem to figure out what I am missing.
I've been asked to include the activity. The following is this code.
I have not added any code to the onItemClick here yet. waiting for the listener to work.
public class EditShiftActivity extends AppCompatActivity implements LoadAdapter.OnItemClickListener{
private ArrayList<Shift> shifts;
private RecyclerView lRecyclerView;
private LoadAdapter lAdapter;
private RecyclerView.LayoutManager lLayoutManager;
private View view;
private FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_shift);
Intent intent = getIntent();
shifts = intent.getParcelableArrayListExtra("shifts");
fab = findViewById(R.id.add_shift_edit);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(EditShiftActivity.this, AddShiftActivity.class);
intent1.putExtra("shifts", shifts);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
v.getContext().startActivity(intent1);
}
});
lRecyclerView = findViewById(R.id.shift_recycler);
lLayoutManager = new LinearLayoutManager(this);
lAdapter = new LoadAdapter(shifts);
lRecyclerView.setLayoutManager(lLayoutManager);
lRecyclerView.setAdapter(lAdapter);
}
#Override
public void onItemClick(int position, Boolean paid) {
}
}
Add below line in your code -
lAdapter = new LoadAdapter(shifts);
lAdapter.setOnItemClickListener(this);
You are retrieving the ArrayList<Shifts> from Intent. Check the size of shifts arraylist before sending to the Adapter. There is a chance that if the arraylist passed is empty then the adapter will return null and hence lRecyclerView will not be displayed.
Add this condition before passing data to adapter
//condition to check whether the arraylist is empty or not
if(!shifts.isEmpty()) {
lAdapter = new LoadAdapter(shifts);
//initialising the adapter
lRecyclerView.setAdapter(lAdapter);
}
public class MainActivity extends Activity implements
GetDataContract.View,RecyclerItemClickListener {
private Presenter mPresenter;
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
CountryAdapter countryAdapter;
EditText etEnterName;
Button btAddItem;
List<CountryRes> allCountriesEditValue;
List<CountryRes> allCountriesData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getView();
}
private void getView() {
/*presentator */
mPresenter = new Presenter(this);
/*initiliaze of id*/
recyclerView = (RecyclerView) findViewById(R.id.recycler);
etEnterName = (EditText) findViewById(R.id.etEnterName);
btAddItem = (Button) findViewById(R.id.btAddItem);
linearLayoutManager = new LinearLayoutManager(this);
/*initiliaze the arraylist*/
allCountriesData=new ArrayList<>();
recyclerView.setLayoutManager(linearLayoutManager);
btAddItem.setOnClickListener(new AddButtonClick());
}
#Override
public void onGetDataFailure(String message) {
Log.d("Status", message);
}
#Override
public void onGetDataSuccess(String message, List<CountryRes>
allCountriesData) {
/*add the value mannulay*/
CountryRes countryRes = new CountryRes();
countryRes.setName(etEnterName.getText().toString());
allCountriesData.add(countryRes);
countryAdapter = new CountryAdapter(getApplicationContext(),
allCountriesData, (RecyclerItemClickListener) this);
recyclerView.setAdapter(countryAdapter);
/*set the data in the room*/
AppDataBase database = AppDataBase.getAppDatabase(this);
DataGenerator.with(database).generateCats(allCountriesData);
Logger.displayCatsInLog(database.catDao().loadAll());
countryAdapter.notifyDataSetChanged();
}
/*on item click*/
#Override
public void onDashBoardItemClick(String pos) {
Bundle bundle = new Bundle();
bundle.putString("TABVALUE", pos);
Intent intent = new Intent(getApplicationContext(),
DynamicTabsActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
private class AddButtonClick implements View.OnClickListener {
#Override
public void onClick(View view) {
mPresenter.getDataFromURL(getApplicationContext(), "");
}
}
}
class adapter
public class CountryAdapter extends
RecyclerView.Adapter<CountryAdapter.MyViewHolder> {
private Context context;
private List<CountryRes> list = new ArrayList<>();
private List<CountryRes> list_edit = new ArrayList<>();
private RecyclerItemClickListener onRecyclerItemClickListener;
public CountryAdapter(Context context, List<CountryRes> list,
RecyclerItemClickListener onRecyclerItemClickListener) {
this.context = context;
this.list = list;
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
}
#Override
public CountryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View layoutView;
layoutView =
LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent,
false);
return new FooterViewHolder(layoutView,
onRecyclerItemClickListener);
}
#Override
public void onBindViewHolder(CountryAdapter.MyViewHolder holder, int
position) {
holder.tvCountryName.setText(list.get(position).getName());
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvCountryName;
LinearLayout llListItem;
public MyViewHolder(View itemView) {
super(itemView);
tvCountryName = (TextView)
itemView.findViewById(R.id.tv_country_name);
llListItem = (LinearLayout)
itemView.findViewById(R.id.llListItem);
}
}
private class FooterViewHolder extends MyViewHolder {
public FooterViewHolder(View layoutView, final
RecyclerItemClickListener onRecyclerItemClickListener) {
super(layoutView);
llListItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onRecyclerItemClickListener != null) {
onRecyclerItemClickListener.onDashBoardItemClick(tvCountryName.getText().toS
tring());
}
}
});
}
}
}
Interface
public interface RecyclerItemClickListener {
void onDashBoardItemClick(String pos);
}
Case 1: Inside ViewHolder if you need to understand exactly position of clicked item you could call getAdapterPosition().
Case 2: You just need to receive all items of adapter. It is simple, make getter method which will return the items.
Case 3: Send info to activity, first make some specific event listener of your view inside ViewHolder, then event triggers (user clicks or other) and you call your interface method which you passed inside adapter, that was implemented in activity.
Tell me if you need an example, i will do it.
Try this one,
Button button= (Button) findViewById(R.id.your_button_id);
button.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
//create new ArrayList.
//ArrayList<CountryRes> showList=new ArrayList<>;
//now, put all stored data of a list in this arraylist.
showList.addAll(allCountriesData);
}
});
I have this method in my activity (CreatePhotostoryActivity):
#Override
public void showEditField(Moment oldMoment, final int index){
listRecycler.setVisibility(View.GONE);
editCaption.setVisibility(View.VISIBLE);
saveCancelNavbar.setVisibility(View.VISIBLE);
momentView.setVisibility(View.GONE);
photoStoryNavbar.setVisibility(View.GONE);
header.setVisibility(View.GONE);
Picasso.with(getApplicationContext()).load(oldMoment.photoUri).into(displayPhoto);
imageCaption.setText("");
imageCaption.setText(oldMoment.caption);
backIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeEditMoment();
}
});
saveText.setText("Save Moment");
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateMoment(imageCaption.getText().toString(), index);
Intent i = new Intent(CreatePhotostoryActivity.this, RVAdapter.class);
i.putExtra("isSaved", true);
startActivity(i);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeEditMoment();
Intent i = new Intent(CreatePhotostoryActivity.this, RVAdapter.class);
i.putExtra("isSaved", false);
startActivity(i);
}
});
}
In my RecyclerView adapter, showEditField is called using an interface, and it does work except that I am unable to detect whether saveButton or cancelButton was clicked. This is how it's called in the onBindViewHolder method of my RecyclerView adapter (RVAdapter):
((RecyclerView.ViewHolder) momentViewHolder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mAdapterCallback.showEditField(moments.get(position), position);
Intent intent = ((CreatePhotostoryActivity) mContext).getIntent();
Boolean isSaved = intent.getExtras().getBoolean("isSaved");
if (isSaved) {
holder.momentCaption.setText(moments.get(position).caption);
holder.momentPlaceholder.setVisibility(View.GONE);
holder.momentCaption.setVisibility(View.VISIBLE);
} else {
holder.momentPlaceholder.setVisibility(View.VISIBLE);
holder.momentCaption.setVisibility(View.GONE);
}
notifyDataSetChanged();
});
Do note my attempt of using an intent to find out which button was clicked. It doesn't work. momentCaption remains gone and momentPlaceHolder remains visible even though saveButton was clicked. The app also crashes afterwards.
Edit: I think calling this mAdapterCallback.showEditField(moments.get(position), position); before setting the values of momentCaption and momentPlaceholder is problematic, since showEditField calls other methods (e.g. closeEditMoment() before the intent is retrieved from the adapter.
Create an interface with two methods like saveBtnClick() and cancelBtnClick().
Implement the interface in your Activity.
Implement Click listener for both the buttons in the ViewHolder of your RecyclerView and call the Appropriate methods using Inteface's Object.
//Interface
public interface ManageButtonClicks
{
void saveBtnClick();
}
//Activity
public class MainActivity extends AppCompactActivity implements ManageButtonClicks
{
ManageButtonClicks manageButtonClicks=this;
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
//Do the operations
adapter = new MyAdapter(this,adapterList,manageButtonClicks);
recyclerView.setAdapter(adapter);
}
void saveBtnClick()
{
Toast.makeText(this,"Clicked",Toast.LENGTH_SHORT).show();
}
}
//Adapter Class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
{
ManageButtonClicks manageButtonClicks;
public MyAdapter(Context context, List< ModelClass > data, ManageButtonClicks manageButtonClicks)
{
inflater = LayoutInflater.from(context);
this.mDataList = data;
this.ctx = context;
util = new Util(ctx);
this.manageButtonClicks = manageButtonClicks;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
ViewGroup nonPrimeRow = (ViewGroup) inflater.inflate(R.layout.rowlayout, parent, false);
MyViewHolder_NON_PRIME holderNonPrime = new MyViewHolder_NON_PRIME(nonPrimeRow);
return holderNonPrime;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position)
{
ModelClass current = mDataList.get(position);
MyViewHolder_NON_PRIME holder_not_prime = (MyViewHolder_NON_PRIME) holder;
holder_not_prime.setdata(current);
}
class MyViewHolder extends RecyclerView.ViewHolder
{
public MyViewHolder(View itemView)
{
super(itemView);
}
}
public class MyViewHolder_NON_PRIME extends MyViewHolder
{
private Button btnSave;
public MyViewHolder_NON_PRIME(View view)
{
super(view);
btnSave = (MonteButton) view.findViewById(R.id.btnSave);
}
public void setdata(final ModelClass current)
{
btnSave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
manageButtonClicks.saveBtnClick();
}
});
}
}
You have a global variable inside recyclerView adapter:
RecyclerViewAdapter {
private boolean isSaveButtonClicked = false;
private boolean isCancelButtonClicked = false;
public void saveButtonClicked(){
isSaveButtonClicked = true;
}}
public void cancelButtonClicked(){
isCancelButtonClicked = true;
}}
When your activity call onclickListeners , you will notice your adapter.
CreatePhotostoryActivity(){
private RecyclerView adapter;
onSaveButtonClicked(){
adapter.saveButtonClicked();
}
onCancelButtonClicked(){
adapter.cancelButtonClicked();
}
}
I have TextView and Button in RecyclerView I put text on Button as number when I clicked the button I want that number increase by 1 when I try recursive setonclicklistener the application doesn't work
I have two activities each of them call the same adapter
the code of adapter
public class AzkaarAdapter extends RecyclerView.Adapter<AzkaarAdapter.AzkaarViewHolder> {
ArrayList<AzkarForm> azkarForms=new ArrayList<AzkarForm>();
Context ctx;
private static ItemClickCallback itemClickCallback;
public interface ItemClickCallback {
void onItemClick(int p);
void onSecondaryIconClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback) {
this.itemClickCallback = itemClickCallback;
}
public AzkaarAdapter (ArrayList<AzkarForm> azkarForms,Context ctx){
this.azkarForms=azkarForms;
this.ctx=ctx;
}
#Override
public AzkaarViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
AzkaarViewHolder azkaarViewHolder;
if(ctx instanceof MainActivity){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_layout,parent,false);
azkaarViewHolder=new AzkaarViewHolder(view,ctx,azkarForms);
}
else {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_details,parent,false);
azkaarViewHolder=new AzkaarViewHolder(view,ctx,azkarForms);
}
return azkaarViewHolder;
}
#Override
public void onBindViewHolder(AzkaarViewHolder holder, int position) {
AzkarForm azkarForm=azkarForms.get(position);
if(ctx instanceof MainActivity) {
holder.sample.setText(azkarForm.getComplete_morning());
holder.number.setText(String.valueOf(azkarForm.getNumber()));
}else {
holder.sample.setText(azkarForm.getComplete_morning());
holder.tally_count.setText(getTextNumber(azkarForm.getNumber()));
}
}
public String getTextNumber(int number){
String numberText="";
switch (number){
case 1:
numberText="مرة واحدة";
break;
case 3:
numberText="ثلاث مرات";
break;
case 4:
numberText="أربع مرات";
break;
case 7:
numberText="سبع مرات";
break;
case 10:
numberText="عشر مرات";
break;
case 100:
numberText="مائة مرة";
break;
}
return numberText;
}
#Override
public int getItemCount() {
return azkarForms.size();
}
public static class AzkaarViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView sample, number;
View container;
Context ctx;
ArrayList<AzkarForm> azkarForms = new ArrayList<AzkarForm>();
Button tally_count,press,next;
public AzkaarViewHolder(View itemView, Context ctx, ArrayList<AzkarForm> azkarForms) {
super(itemView);
this.ctx = ctx;
//itemView.setOnClickListener(this);
this.azkarForms = azkarForms;
if(this.ctx instanceof MainActivity) {
sample = (TextView) itemView.findViewById(R.id.sample);
number = (TextView) itemView.findViewById(R.id.number);
container = itemView.findViewById(R.id.container);
container.setOnClickListener(this);
}else {
sample = (TextView) itemView.findViewById(R.id.sample);
tally_count=(Button)itemView.findViewById(R.id.count);
press=(Button)itemView.findViewById(R.id.press);
press.setOnClickListener(this);
next=(Button)itemView.findViewById(R.id.next);
}
//container.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.container){
itemClickCallback.onItemClick(getAdapterPosition());
} else {
itemClickCallback.onSecondaryIconClick(getAdapterPosition());
}
/*if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.LOLLIPOP){
Pair<View, String> p1 = Pair.create((View)sample, "qoute");
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(this, p1);
}*/
}
}
}
First Activity
recyclerView =(RecyclerView) findViewById(R.id.recyclerviewcard);
layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter=new AzkaarAdapter(AzkaarData.getArrayListData(),this);
recyclerView.setAdapter(adapter);
adapter.setItemClickCallback(this);
toolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public void onItemClick(int p) {
//int position=getAdapterPosition();
AzkarForm azkarForm= list.get(p);
Intent intent=new Intent(this,DetailsActivity.class);
intent.putExtra("numbers",azkarForm.getNumber());
intent.putExtra("sample",azkarForm.getSample());
intent.putExtra("complete",azkarForm.getComplete_morning());
intent.putExtra("position",p);
this.startActivity(intent);
}
#Override
public void onSecondaryIconClick(int p) {
}
Second Activity
recyclerView =(RecyclerView) findViewById(R.id.recyclerviewcard);
layoutManager=new LinearLayoutManager(DetailsActivity.this,LinearLayoutManager.HORIZONTAL,false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.scrollToPosition(pos);
adapter=new AzkaarAdapter(AzkaarData.getArrayListData(),this);
recyclerView.setAdapter(adapter);
SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
toolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public void onItemClick(int p) {
}
#Override
public void onSecondaryIconClick(int p) {
AzkarForm azkarForm= list.get(p);
press=(Button) findViewById(R.id.press);
int currentNum=Integer.parseInt(press.getText().toString());
int num=azkarForm.getNumber();
if(currentNum<num){
currentNum++;
onSecondaryIconClick(p);
}
press.setText(String.valueOf(currentNum));
}
Okay so, first off there is no need for your SecondaryIconClick callback, all because you want it to do something else doesn't mean you need two of them, you can just set the same ItemCallback interface for both activities and then call a switch statement to know which widget was clicked from the layouts. It's easier for me to show you with the code you have provided, I haven't tested any of this code.
From what I can see the First Activity, works fine (I assume this isn't causing the issues in question). Except for readability I would suggest initializing a global instance of the Context (private Context context = this) for that activity and then instead of new Intent(this, DetailsActivity.class) you should have new Intent(context, DetailsActivity.class) because sometimes 'this' can point to the ClickListener rather than the Activity.
For the Second Activity the logic for the counter and setText for the button seems fine except you have already initialized your Button in the ViewHolder, so you don't need to initialize it again in the click listener. All you have to do is pass the view to the listener. (see my edit for the Adapter and ViewHolder code) also, I don't know why you're calling a new instance of the click event if the currentNum < num.
Do you want the clicks to be automatic up until a certain number or just everytime they click up until a certain number?
Anyway, let's solve this problem for you. I'm writing this code with the assumption you want the counter to go up everytime the user clicks R.id.press.
FirstActivity
So as I suggest above change the context reference.
#Override
public void onItemClick(View v, int position) {
switch (v.getId()) {
case R.id.container:
AzkarForm azkarForm= list.get(position);
Intent intent=new Intent(context, DetailsActivity.class);
intent.putExtra("numbers",azkarForm.getNumber());
intent.putExtra("sample",azkarForm.getSample());
intent.putExtra("complete",azkarForm.getComplete_morning());
intent.putExtra("position", position);
context.startActivity(intent);
break;
}
SecondActivity
recyclerView =(RecyclerView) findViewById(R.id.recyclerviewcard);
layoutManager=new LinearLayoutManager(DetailsActivity.this,LinearLayoutManager.HORIZONTAL,false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.scrollToPosition(pos);
adapter=new AzkaarAdapter(AzkaarData.getArrayListData(),this);
recyclerView.setAdapter(adapter);
SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
toolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public void onItemClick(View v, int position) {
switch(v.getId()) {
case R.id.press:
AzkarForm azkarForm= list.get(position);
int currentNum=Integer.parseInt(press.getText().toString());
int num = azkarForm.getNumber();
if(currentNum < num){
currentNum++;
}
v.setText(String.valueOf(currentNum));
break;
}
RecyclerViewAdapter
Your new interface callbacks should be:
public interface ItemClickCallback {
void onItemClick(View v, int position);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback) {
this.itemClickCallback = itemClickCallback;
}
ViewHolder
Your new click listener should look like:
#Override
public void onClick(View v) {
if (itemClickCallback != null) {
itemClickCallback.onItemClick(v, getAdapterPosition());
/*if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.LOLLIPOP){
Pair<View, String> p1 = Pair.create((View)sample, "qoute");
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(this, p1);
}*/
}
}
}
Now you have a clean framework for your listeners and you're passing the correct views and calling the correct context, you're able to apply the logic accordingly without confusion between callbacks.
Hope this helps.
final Button counter = (Button) findViewById(R.id.counter_button);
counter.setText("1");
counter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currNum = Integer.parseInt(counter.getText().toString());
counter.setText("" + currNum + 1);
}
});
Replace button id as per your layout.
now i have new problem ..... i don't know how initialize dialogfragment in recyclerview and recyclerview in fragment , so who know haw to make it ?
Fragment code:
public View onCreateView( LayoutInflater inflater, ViewGroup container3,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v =inflater.inflate(R.layout.fragment_one_day_tasks,container3,false);
final View vd =inflater.inflate(R.layout.dialogod,null);
TextView textView= (TextView) v.findViewById(R.id.ActiveMenu);
TextView textView1= (TextView) v.findViewById(R.id.Alert);
database = new Database(v.getContext());
mId = database.getLastIdOD();
if(mId>=1) {
oneDayList = database.getOneDayList(1);
}
database.close();
//dlg1 = new DialogFragment();
//GridView gridView = (GridView) v.findViewById(R.id.gridViewActiveOd);
RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.gridResc);
if(0<mId){
recyclerView.setLayoutManager(new GridAutofitLayoutManager(v.getContext(),350));
recyclerView.setAdapter(new adapterRecylcerViewGridODN(v.getContext(),oneDayList,inflater));
/* gridView.setAdapter(new GridOdAdapter(v.getContext(),oneDayList));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
tapOnAlert(vd,position);
}
});*/
}else{
textView1.setText("You Haven't got any Active Tasks !");
}
FloatingActionButton fab = (FloatingActionButton) v.findViewById(R.id.fabCreateOd);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().finish();
Intent intent = new Intent(getActivity().getApplicationContext(),CreateOneDayNotif.class);
intent.putExtra("mId",1 + database.getLastIdOD());
startActivity(intent);
Snackbar.make(view, "New Task", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
return v;
}
RecyclerView Adapter code:
public void onBindViewHolder(SimpleViewHolder holder, final int position) {
holder.title.setText(mItems.get(position).getTitle());
datecount = new Datecount(mItems.get(position).getDateAndTime());
long minute = datecount.getMinuteInt();
long hour=datecount.getHourInt();
long day=datecount.getDayInt();
long year=datecount.getYearInt();
long month=datecount.getMonthInt();
holder.dataAtime.setText("On date: " + day+"/"+month+"/"+year+ " On time: "+hour+":"+minute);
int iconResId = mContext.getResources().getIdentifier(mItems.get(position).getIcon(), "drawable", mContext.getPackageName());
holder.image.setImageResource(iconResId);
GradientDrawable bgShape = (GradientDrawable) holder.circle.getDrawable();
bgShape.setColor(Color.parseColor(mItems.get(position).getColour()));
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//I want to put here dialog.show
//I want to put here dialog.show
}
});
And DialogFragment code:
public class DialogFragmentOd extends DialogFragment {
boolean isFabOpen;
Animation fab_open,fab_close,rotate_forward,rotate_backward;
List<OneDayTD> oneDayList;
int position;
Database database;
public static DialogFragmentOd getInstance() {
DialogFragmentOd dialog = new DialogFragmentOd();
//Bundle arguments = new Bundle();
//arguments.putParcelable(Person.class.getName(), person);
//dialog.setArguments(arguments);
return dialog;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View vd = inflater.inflate(R.layout.dialogod, null);
.........
getDialog().setContentView(layout);
return vd;
}
}
So what i need to do ???
Here is an alternative way to handle all clicks in your Activity or Fragment where we have the Context.
Add a custom click listener interface in your Adapter.
public interface OnDataClickListener {
void onDataClick();
}
Create a variable in you Adapter to hold the custom click listener
public MyAdapter {
private OnDataClickListener mOnDataClickListener;
public MyAdapter(OnDataClickListener listener) {
mOnDataClickListener = listener;
}
}
Call the click method of the custom interface when a button is clicked in your ViewHolder
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mOnDataClickListener.onDataClick();
}
}
Implement View.OnClickListener in your Fragment
MyFragment implement View.OnClickListener {
#Override
public void onClick(View view) {
// Call/Create your dialog fragment show from here.
}
}
Pass the Fragment instance when initialising the Adapter
MyAdapter adapter = new MyAdapter(this);
That's all.