Method used alongside OnCreate() to update an activity? - java

I have an android studio activity that contains a RecyclerView, Adapter, and an invisible button at the bottom of the activity. Each itemView thats inside the RecyclerView also has a CheckBox. Inside my Adapter Class I have my Checkbox initialized and has something like - if checkbox.isChecked - then make public static int num = 1 else num = 2; This static variable is then sent to my Activity_main where my bottom button that I need to become Visible can be visible using an if statement that says - if Adapter.num == 1 then button.MakeVisible(true);
Issue is that it's in my Oncreate which is only called once the activity is made. The static number is sent no problem but the activity doesn't update to actually show this. I have to restart the activity to have the button actually become visible.
Adapter Class
public static int p = 0;
#Override
public void onBindViewHolder(#NonNull final Adapter.CustomViewHolder holder,
final int position) {
addedCars = new ArrayList<>();
holder.car.setText(mCars.get(position).getCarName());
holder.mCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(holder.mCheckBox.isChecked()){
Log.d("tag1", "checked");
addedCars.add(mCars.get(position));
String x = Integer.toString(addedCars.size());
Log.d("tag1", x );
p = 1;
holder.mButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
else {
Log.d("tag1", "unchecked");
addedCars.remove(mCars.get(position));
p = 2;
}
}
});
}
Activity_Main Class
public class MainActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
Adapter mAdapter;
RecyclerView.LayoutManager mLayoutManager;
Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.RecyclerView);
mButton = findViewById(R.id.button);
ArrayList<Car> cars = new ArrayList<>();
cars.add(new Car("Toyota"));
cars.add(new Car("Ford"));
cars.add(new Car("Tesla"));
mAdapter = new Adapter(cars);
mRecyclerView.setAdapter(mAdapter);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setHasFixedSize(true);
if (mAdapter.p == 1){
mButton.setVisibility(View.VISIBLE);
}
}
}

If you want to send the num p from RecyclerView Adapter to the activity you need an interface to do so following steps to be followed :
have tested my code in android hope this works for you
creating an interface in the adapter
// create an instance of OnItemChangeListener
public OnItemChangeListener onItemChangeListener;
public interface OnItemChangeListener {
void onItemChanged(int p);
}
//set the instance of onItemChangeListener from the main activity
public void setOnItemChangeListener(OnItemChangeListener onItemChangeListener) {
this.onItemChangeListener = onItemChangeListener;
}
holder.mCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(holder.mCheckBox.isChecked()){
Log.d("tag1", "checked");
addedCars.add(mCars.get(position));
String x = Integer.toString(addedCars.size());
Log.d("tag1", x );
p = 1;
/*
* notify updated value using call back
*/
onItemChangeListener.onItemChanged(p);
holder.mButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
2 finally notify update to the main activity
mAdapter = new Adapter(cars);
mAdapter.setOnItemChangeListener(new /*your adapter name */.OnItemChangeListener() {
#Override
public void onItemChanged(int p) {
// here you will get the latest updated value of p
// now you can update you view accordingly
}
});
mRecyclerView.setAdapter(mAdapter);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setHasFixedSize(true);

Related

How to getItemCount() when using FirestoreRecyclerAdapter because it always return 0?

I'm currently building a booking application for laundry's machine. I need to get the item count and if the count is zero it will show the dialog box which told user that there is no data in the system.
The Activity code:
public class DobbySelection2 extends AppCompatActivity {
String local;
private Dialog dialog;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private DobbyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dobby_selection2);
dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog2);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
dialog.getWindow().setBackgroundDrawable(getDrawable(R.drawable.custom_dialogbackground));
}
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(false); //Optional
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //Setting the animations to dialog
Button Yes = dialog.findViewById(R.id.btn_yes);
Yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(DobbySelection2.this, MainActivity.class );
dialog.dismiss();
startActivity(intent);
}
});
setUpRecyclerView();
}
private void setUpRecyclerView(){
Intent i = getIntent();
local = i.getStringExtra("PLACE");
if (local == null){
local = "Selangor";
}
CollectionReference dobbyRef = db.collection("locality")
.document(local)
.collection("Dobby");
Query query = dobbyRef.orderBy("name", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Dobby> options = new FirestoreRecyclerOptions.Builder<Dobby>()
.setQuery(query, Dobby.class)
.build();
adapter = new DobbyAdapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
//recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setLayoutManager(new CustomLinearLayoutManager(this));
recyclerView.setAdapter(adapter);
if(adapter.getItemCount() == 0){
dialog.show();
}
adapter.setOnItemClickListener(new DobbyAdapter.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
Dobby dobby = documentSnapshot.toObject(Dobby.class);
String id = documentSnapshot.getId();
Toast.makeText(DobbySelection2.this, "ID : " + id, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(DobbySelection2.this, Booking2.class);
intent.putExtra("PLACE", local);
intent.putExtra("ID", id);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Adapter code:
public class DobbyAdapter extends FirestoreRecyclerAdapter<Dobby, DobbyAdapter.DobbyHolder>{
private OnItemClickListener listener;
/**
* Create a new RecyclerView adapter that listens to a Firestore Query. See {#link
* FirestoreRecyclerOptions} for configuration options.
*
* #param options
*/
public DobbyAdapter(#NonNull FirestoreRecyclerOptions<Dobby> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull DobbyHolder holder, int position, #NonNull Dobby model) {
holder.textViewName.setText(model.getName());
holder.textViewAddress.setText(model.getAddress());
holder.textViewDistance.setText(model.getDistance());
}
#NonNull
#Override
public DobbyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemdobby, parent, false);
return new DobbyHolder(v);
}
class DobbyHolder extends RecyclerView.ViewHolder{
TextView textViewName;
TextView textViewAddress;
TextView textViewDistance;
public DobbyHolder(#NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.nameDobby);
textViewAddress = itemView.findViewById(R.id.addressDobby);
textViewDistance = itemView.findViewById(R.id.distanceDobby);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION && listener != null){
listener.onItemClick(getSnapshots().getSnapshot(position), position);
}
}
});
}
}
public interface OnItemClickListener {
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
}
But the dialog box always pop up indicating that the count is zero even though there is data inside of the recycler view. How can I fix this?
My guess is that the dialog you're talking about comes from here:
if(adapter.getItemCount() == 0){
dialog.show();
}
If so, it makes sense that it shows up as this code runs before any data has been loaded.
Data is loaded from Firestore (and most modern cloud APIs) asynchronously, and this changes the order in which code executes. It's easiest to see this if you set breakpoint on the if line above, on adapter.startListening(); and on the first line inside your onBindViewHolder.
If you now run the code in the debugger, you'll see that it:
First hits the if(adapter.getItemCount() == 0){ line
Then adapter.startListening()`
Then gets to onBindViewHolder
So now it hopefully makes sense why your code always show the dialog: no data has been loaded yet at that point.
The solution for this is always the same: you need to make sure that the code that needs the data runs after the data has been loaded. Since you're using the FirestoreRecyclerAdapter from FirebaseUI, you can do this inside its onDataChanged method that signals that a complete snapshot was loaded (regardless of whether there was any data in that snapshot) and is shown in the documentation on data and error events.
So if you move your if check into a onDataChanged method in your DobbyAdapter, it will get called whenever the adapter has loaded a complete snapshot, and it will show the dialog when there are no items.

How To Add Multiple Cards Of The Same CardView To A RecyclerView?

Here is a video of what I trying to do and explanation of the issue that I am having. Go to the following link below.
https://file.re/2021/09/12/2021-09-1210-43-21/
Here is the XML, Java, and Manifest Code Video. Go to the following link below.
https://file.re/2021/09/12/2021-09-1211-32-13/
Answer worked, but now I have two new problems. Here is the video link below.
https://file.re/2021/09/12/2021-09-1212-08-04/
I am creating an app that lists CardView layouts to a RecyclerView.
My app will add the CardView layout to the RecyclerView list, but it only lists one. I want it to add multiples of the same CardView when the user clicks on the button to add the card (basically cloning the CardView layout one under the other).
Here is what I have in my Button Click...
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>();
addFahToCelCard.add(new RecyclerItem());
recyclerView = findViewById(R.id.recycler_item_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
}
}
});
I've tried putting the ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>(); under the MainActivity extends AppCompatActivity class just before the onCreate like this...
public class MainActivity extends AppCompatActivity {
final private ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>();
That didn't work.
If I don't keep ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>(); in the button click listener, and I add a new CardView it will add a new one behind the original one each time the button is clicked, and if I delete the card it keep popping back up until I delete them all off. How do I fix this the way I want it to behave? I hope this all makes sense.
I appreciate the help!
Here is everything in the java class..
public class MainActivity extends AppCompatActivity {
ArrayList<RecyclerItem> addFahToCelCard;
private Animation fromBottom;
private Animation toBottom;
private Boolean clicked = false;
private RecyclerView recyclerView;
private RecyclerItemAdapter recyclerItemAdapter;
private RecyclerView.LayoutManager layoutManager;
public FloatingActionButton mainConverterMenuFloatBtn;
public TextView chooseConverterLabel, ftocConverterLabelBtn, ftokConverterLabelBtn, ctofConverterLabelBtn, ctokConverterLabelBtn, ktofConverterLabelBtn, ktocConverterLabelBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fromBottom = AnimationUtils.loadAnimation(MainActivity.this, R.anim.from_bottom_animation);
toBottom = AnimationUtils.loadAnimation(MainActivity.this, R.anim.to_bottom_animation);
mainConverterMenuFloatBtn = findViewById(R.id.add_temp_converter_float_btn);
chooseConverterLabel = findViewById(R.id.choose_converter_label);
ftocConverterLabelBtn = findViewById(R.id.add_f_to_c_converter_label_btn);
ftokConverterLabelBtn = findViewById(R.id.add_f_to_k_converter_label_btn);
ctofConverterLabelBtn = findViewById(R.id.add_c_to_f_converter_label_btn);
ctokConverterLabelBtn = findViewById(R.id.add_c_to_k_converter_label_btn);
ktofConverterLabelBtn = findViewById(R.id.add_k_to_f_converter_label_btn);
ktocConverterLabelBtn = findViewById(R.id.add_k_to_c_converter_label_btn);
addFahToCelCard = new ArrayList<>();
recyclerView = findViewById(R.id.recycler_item_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
mainConverterMenuFloatBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mainConverterMenu();
}
});
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
addFahToCelCard.add(new RecyclerItem());
recyclerItemAdapter.notifyDataSetChanged();
closeActionButton();
}
}
});
ftokConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ctofConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ctokConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ktofConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ktocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
}
private void addFahToCelCard() {
}
private void mainConverterMenu() {
setVisibility(clicked);
setClickable(clicked);
setAnimation(clicked);
clicked = !clicked;
}
private void setVisibility(Boolean clicked) {
if (!clicked) {
chooseConverterLabel.setVisibility(View.VISIBLE);
ftocConverterLabelBtn.setVisibility(View.VISIBLE);
ftokConverterLabelBtn.setVisibility(View.VISIBLE);
ctofConverterLabelBtn.setVisibility(View.VISIBLE);
ctokConverterLabelBtn.setVisibility(View.VISIBLE);
ktofConverterLabelBtn.setVisibility(View.VISIBLE);
ktocConverterLabelBtn.setVisibility(View.VISIBLE);
} else {
chooseConverterLabel.setVisibility(View.GONE);
ftocConverterLabelBtn.setVisibility(View.GONE);
ftokConverterLabelBtn.setVisibility(View.GONE);
ctofConverterLabelBtn.setVisibility(View.GONE);
ctokConverterLabelBtn.setVisibility(View.GONE);
ktofConverterLabelBtn.setVisibility(View.GONE);
ktocConverterLabelBtn.setVisibility(View.GONE);
}
}
private void setClickable(Boolean clicked) {
if (!clicked) {
chooseConverterLabel.setClickable(true);
ftocConverterLabelBtn.setClickable(true);
ftokConverterLabelBtn.setClickable(true);
ctofConverterLabelBtn.setClickable(true);
ctokConverterLabelBtn.setClickable(true);
ktofConverterLabelBtn.setClickable(true);
ktocConverterLabelBtn.setClickable(true);
} else {
chooseConverterLabel.setClickable(false);
ftocConverterLabelBtn.setClickable(false);
ftokConverterLabelBtn.setClickable(false);
ctofConverterLabelBtn.setClickable(false);
ctokConverterLabelBtn.setClickable(false);
ktofConverterLabelBtn.setClickable(false);
ktocConverterLabelBtn.setClickable(false);
}
}
private void setAnimation(Boolean clicked) {
if (!clicked) {
chooseConverterLabel.startAnimation(fromBottom);
ftocConverterLabelBtn.startAnimation(fromBottom);
ftokConverterLabelBtn.startAnimation(fromBottom);
ctofConverterLabelBtn.startAnimation(fromBottom);
ctokConverterLabelBtn.startAnimation(fromBottom);
ktofConverterLabelBtn.startAnimation(fromBottom);
ktocConverterLabelBtn.startAnimation(fromBottom);
} else {
chooseConverterLabel.startAnimation(toBottom);
ftocConverterLabelBtn.startAnimation(toBottom);
ftokConverterLabelBtn.startAnimation(toBottom);
ctofConverterLabelBtn.startAnimation(toBottom);
ctokConverterLabelBtn.startAnimation(toBottom);
ktofConverterLabelBtn.startAnimation(toBottom);
ktocConverterLabelBtn.startAnimation(toBottom);
}
}
private void closeActionButton() {
setVisibility(clicked);
setClickable(clicked);
setAnimation(clicked);
clicked = !clicked;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.app_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.show_hide_float_convert_btn) {
if (mainConverterMenuFloatBtn.isShown()) {
mainConverterMenuFloatBtn.setVisibility(View.GONE);
item.setIcon(R.drawable.ic_baseline_visibility_off_32);
} else if (!mainConverterMenuFloatBtn.isShown()) {
mainConverterMenuFloatBtn.setVisibility(View.VISIBLE);
item.setIcon(R.drawable.ic_baseline_visibility_32);
}
} else if (id == R.id.app_help) {
} else if (id == R.id.tip_developer) {
} else if (id == R.id.premium_features) {
} else if (id == R.id.about_app) {
} else if (id == R.id.exit_app) {
}
return super.onOptionsItemSelected(item);
}
public static class RecyclerItemAdapter extends RecyclerView.Adapter<RecyclerItemAdapter.RecyclerViewHolder> {
public ArrayList<RecyclerItem> recyclerItemList;
public AdapterView.OnItemClickListener recyclerItemListener;
public interface OnItemClickListener {
void onItemClick (int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
recyclerItemListener = (AdapterView.OnItemClickListener) listener;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
EditText inputFahValueET;
TextView fahtoCelResult;
ImageView tempIconAndConvertBtn;
ImageView deleteCardBtn;
String shortResult, longResult;
public RecyclerViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
inputFahValueET = itemView.findViewById(R.id.input_fahrenheit_value_to_convert);
fahtoCelResult = itemView.findViewById(R.id.output_result_ftc);
tempIconAndConvertBtn = itemView.findViewById(R.id.temp_icon_convert_btn);
deleteCardBtn = itemView.findViewById(R.id.remove_card);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
public RecyclerItemAdapter(ArrayList<RecyclerItem> rList) {
recyclerItemList = rList;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fahrenheit_to_celsius_converter_layout, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v, (OnItemClickListener) recyclerItemListener);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
RecyclerItem currentItem = recyclerItemList.get(position);
final String[] result = new String[1];
holder.tempIconAndConvertBtn.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View view) {
String getIputFahValue = holder.inputFahValueET.getText().toString();
NumberFormat nf = new DecimalFormat("0.000");
if(!getIputFahValue.isEmpty()) {
double d = Double.parseDouble(getIputFahValue);
double dd = d - 32;
double ddd = dd * 5;
double dddd = ddd / 9;
result[0] = Double.toString(dddd);
holder.fahtoCelResult.setText(nf.format(dddd) + "°C");
holder.fahtoCelResult.setVisibility(View.VISIBLE);
holder.shortResult = nf.format(dddd) + "°C";
holder.longResult = getIputFahValue + "°F is " + nf.format(dddd) + "°C";
if (result[0].contains(".0")) {
result[0] = result[0].replace(".0", "");
holder.fahtoCelResult.setText(result[0] + "°C");
holder.fahtoCelResult.setVisibility(View.VISIBLE);
holder.shortResult = result[0] + "°C";
holder.longResult = getIputFahValue + "°F is " + result[0] + "°C";
}else if (result[0].contains(".000")) {
result[0] = result[0].replace(".000", "");
holder.fahtoCelResult.setText(result[0] + "°C");
holder.fahtoCelResult.setVisibility(View.VISIBLE);
holder.shortResult = result[0] + "°C";
holder.longResult = getIputFahValue + "°F is " + result[0] + "°C";
}
}else {
Toast.makeText(view.getContext(), "Fahrenheit Value Field Cannot Be Blank!", Toast.LENGTH_LONG).show();
}
}
});
holder.fahtoCelResult.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder adb = new AlertDialog.Builder(view.getContext());
adb.setIcon(R.drawable.ic_baseline_file_copy_32);
adb.setTitle("Copy Result");
adb.setMessage("You can copy the result to your clipboard if you would like. Choose if you want the short or long result copied to your clipboard.\n\nExample of Short and Long Result:\nShort Result: 32°C\nLong Result: 0°F is 32°C");
adb.setPositiveButton("Short", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ClipboardManager cbm = (ClipboardManager) view.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copy", holder.shortResult);
cbm.setPrimaryClip(clip);
Toast.makeText(view.getContext(), "Result Copied!", Toast.LENGTH_SHORT).show();
}
});
adb.setNegativeButton("Long", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ClipboardManager cbm = (ClipboardManager) view.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copy", holder.longResult);
cbm.setPrimaryClip(clip);
Toast.makeText(view.getContext(), "Result Copied!", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {}});
adb.create();
adb.show();
return false;
}
});
holder.deleteCardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recyclerItemList.remove(position);
notifyItemRemoved(position);
}
});
}
#Override
public int getItemCount() {
return recyclerItemList.size();
}
}
public class RecyclerItem {
public RecyclerItem() {
}
}
}
The recyclerView should be listing the CardViews and also allowing duplicates.
Well, I think you are just using the RecyclerView the wrong way.
In your code snippet, you are initializing the RecyclerView as well as the adapter and all other components every time the user clicks the button.
First of all you will have to create the insert method in the RecyclerItemAdapter class.
RecyclerItemAdapter.java
class RecyclerItemAdapter extends RecyclerView.Adapter<YourViewHolder> {
private ArrayList<RecyclerItem> items;
RecyclerItemAdapter(ArrayList<RecyclerItem> recyclerItems) {
this.items = recyclerItems;
}
//...
public void addItem(RecyclerItem item) {
items.add(item);
notifyDataSetChanged();
}
}
Then, you have ton initialize the RecyclerView only once. The best place to do that is in the onCreate method.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<RecyclerItem> addFahToCelCard;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addFahToCelCard = new ArrayList<>();
setupRecyclerView();
setupClickListener();
}
private void setupRecyclerView() {
recyclerView = findViewById(R.id.recycler_item_view);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(recyclerItemAdapter);
}
}
Now add your onClickListener which will only add the card to the list.
private void setupClickListener() {
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recyclerItemAdapter.addItem(new RecyclerItem());
}
});
}
What is your xml layout for this cardview ? It looks like this cardview is in another layout that has match parent as width and height.
If thats the case items are too big to show.
Okay so try making first reletive layout height = 100dp to match the card view in fahrenheit_to_celsius_converter_layout.xml
well I didn't understand the problem very well but from what I understood here's what you should do :
first you shouldn't be creating a new recycler view on every button click, instead you should put the code that initializes the recycler view in onCreate method that exist in the activity class and just keep a reference to the arraylist that holds the data and the adapter as global variables.
whenever the user clicks the button you should add a new item to the arraylist of data and use adapter.notifyDataItemSetChanged to tell the recycle view to check if there's any change happened to the recycle view and take action if necessary
here's a part of code that explains what I'm saying and I hope you that even if that doesn't answer your question, you catch a glimpse of how to deal with recyclerview :
first as I said you should keep a reference to the arraylist that holds the data and the adapter as global variables so put those outside any method in the activity
RecyclerItemAdapter recyclerItemAdapter ;
ArrayList <RecyclerItem>addFahToCelCard ;
and then put this code instead of the button code
addFahToCelCard = new ArrayList<>();
recyclerView = findViewById(R.id.recycler_item_view);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addFahToCelCard.add(new RecyclerItem());
recyclerItemAdapter.notifyDataSetChanged();
}
}
});
that way whenever you want to edit the recyclerView data anytime you can add/remove items from the global arraylist and notify the adapter just like the code inside the button OnClickListener
update to the last video posted about the exception
this problem raises when you delete some items, try to use holder.getAbsoluteAdapterPosition(), instead of getAdapterPosition or the old final position value.
whenever you use a value inside a listener I guess it takes the value that exists right now and hold it as final, so if you have 5 items and deleted the first 3, the last two will still have their position stored as 4 and 5 instead of 1 and 2, thats why you should call the holder.getAbsoluteAdapterPosition() to get the current position instead of the final stored one, that way he stores the holder as final instead of storing a const int value.

How do I get the input of an activity into the recyclerview of another activity?

Updated Problem: My text of the SecondAcitivity is displayed in the recycling view of my MainActivity. However, the text in the Recyclerview will be overwritten.
How do I get it that the text in my recycling view is not overwritten, but is displayed in a further field one below the other?
I would like to have a button in my main activity that opens Activity 2. A text should then be entered there, which should then be displayed by clicking a button in the Recyclerview of the main activity.
I have already inserted a recylerview adapter, but the text is not output. Where is the problem?
On my XML i got 2 Buttons (one in the MainActivity (floatingActionButton) and one in the Second (sendNewTask))
My MainActivity:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton floatingActionButton;
TaskManager taskManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
taskManager = new TaskManager(this);
initViews();
initClickListener();
receiveIntent();
setRecyclerView();
}
protected void initViews(){
floatingActionButton = findViewById(R.id.floating_button);
recyclerView = findViewById(R.id.recyclerview);
}
protected void initClickListener(){
floatingActionButton.setOnClickListener(view -> onOpenButtonClicked());
}
protected void setRecyclerView(){
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new TaskListAdapter(taskManager));
recyclerView.getAdapter().notifyItemInserted(taskManager.getTaskListCount() - 1);
}
protected void onOpenButtonClicked(){
Intent i = new Intent(this, TaskActivity.class);
startActivity(i);
}
protected void receiveIntent(){
String inputTask = getIntent().getStringExtra("EXTRA_SESSION_TASK");
Task task = new Task();
task.setName(inputTask);
taskManager.addTask(task);
}
}
My SecondActivity:
public class TaskActivity extends AppCompatActivity {
EditText etAddTask;
ImageView sendNewTask;
TaskManager taskManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_task);
taskManager = new TaskManager(this);
initViews();
initClickListener();
}
protected void initViews(){
etAddTask = findViewById(R.id.et_new_task);
sendNewTask = findViewById(R.id.send_new_task);
}
protected void initClickListener(){
sendNewTask.setOnClickListener(view -> onSendButtonClicked());
}
protected void onSendButtonClicked(){
String newTaskName = etAddTask.getText().toString();
Task task = new Task();
task.setName(newTaskName);
taskManager.addTask(task);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
And my RecyclerAdapter & TaskViewHolder:
public class TaskListAdapter extends RecyclerView.Adapter<TaskViewHolder> {
TaskManager taskManager;
public TaskListAdapter(TaskManager taskManager){
this.taskManager = taskManager;
}
#NonNull
#Override
public TaskViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new TaskViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.task_row, parent, false));
}
#Override
public void onBindViewHolder(#NonNull TaskViewHolder holder, int position) {
Task task = taskManager.getTaskList().get(position);
holder.newTask.setText(task.getName());
}
#Override
public int getItemCount() {
return taskManager.getTaskListCount();
}
}
public class TaskViewHolder extends RecyclerView.ViewHolder {
TextView newTask;
public TaskViewHolder(#NonNull View itemView) {
super(itemView);
newTask = itemView.findViewById(R.id.tv_new_task);
}
}
TaskManager:
public class TaskManager {
ArrayList<Task> taskList = new ArrayList<>();
public TaskManager(Context context){
Hawk.init(context).build();
loadTaskList();
}
public void addTask(Task task){
taskList.add(task);
saveTaskList();
}
public void removeTask(Task task){
taskList.remove(task);
saveTaskList();
}
public ArrayList<Task> getTaskList(){
return taskList;
}
public int getTaskListCount(){
return taskList.size();
}
protected void saveTaskList(){
Hawk.put("taskList", taskList);
}
protected void loadTaskList(){
Hawk.get("taskList", new ArrayList<>());
}
}
Adding a task using a AlertDialog
If you don't need a whole new activity to just add a new task, you can use an AlertDialog.
public class MainActivity extends AppCompatActivity {
// ...
protected void onOpenButtonClicked(){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Here you can set the View you want, even a LinearLayout. In this
// case, I'm adding a text field so user can type the task name
final EditText edittext = new EditText(this);
builder.setTitle("Enter the task name");
builder.setView(edittext);
alert.setPositiveButton("ADD", (dialog, which) -> {
// When the user clicks the add button of the dialog, here will
// be the task name the user has typed, so just add it to the
// task manager of this activity
final String newTaskName = edittext.getText().toString();
});
alert.setNegativeButton("CANCEL", (dialog, which) -> {
// When the user clicks the cancel button of the dialog, just
// dismiss it without doing any action
dialog.dismiss();
});
alert.create().show();
}
// ...
}
Keeping the previous tasks passing a StringArrayList
If you do need a new activity, you can keep the previous tasks by using a ArrayList and passing this around.
Requesting a new task:
public class MainActivity extends AppCompatActivity {
// ...
protected void onOpenButtonClicked(){
final Intent i = new Intent(this, TaskActivity.class);
// Transform the task list to a string list
final List<String> taskNames = taskManager.getTaskList().stream()
.map(task -> task.name).collect(Collesctions.toList());
// Put it into the intent and start a new activity
i.putStringArrayListExtra("TASK_NAME_LIST", new ArrayList<>(taskNames));
startActivity(i);
}
// ...
}
Fetching a new task name:
public class TaskActivity extends AppCompatActivity {
// ...
ArrayList<String> taskNames;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
// ...
final Intent i = getIntent();
// Receive the current task names
taskNames = getIntent().getStringArrayListExtra("TASK_NAME_LIST");
}
protected void onOpenButtonClicked() {
final String newTaskName = etAddTask.getText().toString();
// Add the new task name to the task names
taskNames.add(newTaskName);
// Send it back to the MainActivity
final Intent i = new Intent(this, MainActivity.class);
i.putStringArrayListExtra("TASK_NAME_LIST", taskNames);
startActivity(i);
finish();
}
// ...
}
Creating a new task:
public class MainActivity extends AppCompatActivity {
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
taskManager = new TaskManager(this);
final Intent i = getIntent();
if (i != null) {
// Receive the new task names
final List<String> taskNames = getIntent().getStringArrayListExtra("TASK_NAME_LIST");
for (String taskName : taskNames) {
final Task task = new Task();
task.setName(taskName);
taskManager.addTask(task);
}
}
}
// ...
}
NOTE: Even though in the previous example there are two separate MainActivity methods, you should include both.

How can I hide some content from showing to recyclerview

I am working on code which I copied from somewhere as a learner. The app displays data in recyclerview, this data is coming from firebase database. All is working well, the data is displaying nicely in recyclerview.
My worry now is: i have added another recyclerview in the same activity. So now I have two recyclerviews with these IDs: recyclerview and recyclerview2. They are in one activity but in different layouts, and only one layout is visible at a time, and by clicking the button it hides one layout and shows another. For now the recyclerviews are showing same data.
What i want now is this: In these recyclerviews I have a TextView which changes text time by time. It sometimes shows this text 'CLOSED'. So i want all the data which has a textview which shows 'CLOSED' to be shown on recyclerview2 and will be unavailable on the first recyclerview.
So my issue is to make the data not to display on recyclerview (first one) if the textview is showing 'CLOSED' and i want the recyclerview2 to show only data which has a textview showing this text 'CLOSED'
I do not know where to start from. Below is my MainActivity.java where i want the code to be added.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView, recyclerView2;
private DatabaseReference mDatabase, vDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
TextView rtrratio, rtrratiopercentage, tppipss, slpipss, commenting, entry, tp, sl, tv1, tv2, tv3;
RelativeLayout rSignals, rCalendar, rLessons, rServices, rContact;
ImageButton imsignals, imcalendar, imlessons, imservices, imcontact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
//defining main buttons (Image buttons)
imsignals = (ImageButton) findViewById(R.id.im_signals_id);
imcalendar = (ImageButton) findViewById(R.id.im_calendar_id);
imlessons = (ImageButton) findViewById(R.id.im_lessons_id);
imservices = (ImageButton) findViewById(R.id.im_services_id);
imcontact = (ImageButton) findViewById(R.id.im_contact_id);
//defining textviews
entry = (TextView) findViewById(R.id.entry);
tppipss = (TextView) findViewById(R.id.tpp);
slpipss = (TextView) findViewById(R.id.slp);
rtrratio = (TextView) findViewById(R.id.riskreward);
rtrratiopercentage = (TextView) findViewById(R.id.rrewardp);
commenting = (TextView) findViewById(R.id.comment);
tp = (TextView) findViewById(R.id.tp);
sl = (TextView) findViewById(R.id.sl);
//bottom navigation
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
//button definitions
Button btnRunning = (Button) findViewById(R.id.sRunning);
Button btnPending = (Button) findViewById(R.id.sPending);
Button btnClosed = (Button) findViewById(R.id.sClosed);
//layouts definitions for bottom navigation
rSignals = (RelativeLayout) findViewById(R.id.rlsignals);
rCalendar = (RelativeLayout) findViewById(R.id.rlcalendar);
rLessons = (RelativeLayout) findViewById(R.id.rllessons);
rServices = (RelativeLayout) findViewById(R.id.rlservices);
rContact = (RelativeLayout) findViewById(R.id.rlcontact);
//layouts definitions for signals layout
final RelativeLayout rRunning = (RelativeLayout) findViewById(R.id.rlRunning);
final LinearLayout rPending = (LinearLayout) findViewById(R.id.rlHistory);
final LinearLayout rClosed = (LinearLayout) findViewById(R.id.rlRating);
//initialize recyclerview and FIrebase objects
//for running signals
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
//for closed signals
recyclerView2 = (RecyclerView) findViewById(R.id.recyclerview2);
recyclerView2.setLayoutManager(new LinearLayoutManager(this));
recyclerView2.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
//for running signals
recyclerView.setLayoutManager(linearLayoutManager);
//for closed signals
recyclerView.setLayoutManager(linearLayoutManager);
//for signals get child as Blogzone
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blogzone");
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (mAuth.getCurrentUser() == null) {
Intent loginIntent = new Intent(MainActivity.this, RegisterActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
}
}
};
/////////////////////////////////////////////////////////////////////////////////////////////
//signals
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder> FBRA = new FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder>(
Blogzone.class,
R.layout.card_items,
BlogzoneViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(BlogzoneViewHolder viewHolder, Blogzone model, int position) {
final String post_key = getRef(position).getKey().toString();
viewHolder.setPair(model.getPair());
viewHolder.setBuySell(model.getBuysell());
viewHolder.setOpenPrice(model.getOpenprice());
viewHolder.setTakeProfit(model.getTakeprofit());
viewHolder.setStopLoss(model.getStoploss());
viewHolder.setProfitPips(model.getProfitpips());
viewHolder.setLossPips(model.getLosspips());
viewHolder.setComment(model.getComment());
viewHolder.setResult(model.getResult());
viewHolder.setRewarding(model.getRewarding());
viewHolder.setRewardingP(model.getRewardingP());
//viewHolder.setImageUrl(getApplicationContext(), model.getImageUrl());
//viewHolder.setUserName(model.getUsername());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Intent singleActivity = new Intent(MainActivity.this, SinglePostActivity.class);
// singleActivity.putExtra("PostID", post_key);
// startActivity(singleActivity);
}
});
}
};
//running signals
recyclerView.setAdapter(FBRA);
//closed signals
recyclerView2.setAdapter(FBRA);
}
public static class BlogzoneViewHolder extends RecyclerView.ViewHolder {
View mView;
public BlogzoneViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setPair(String pair) {
TextView post_pair = mView.findViewById(R.id.quote);
post_pair.setText(pair);
}
public void setBuySell(String buySell) {
TextView post_buysell = mView.findViewById(R.id.type);
post_buysell.setText(buySell);
}
public void setOpenPrice(String openPrice) {
TextView post_openprice = mView.findViewById(R.id.entry);
post_openprice.setText(openPrice);
}
public void setTakeProfit(String takeProfit) {
TextView post_takeprofit = mView.findViewById(R.id.tp);
post_takeprofit.setText("Tp: " + takeProfit);
}
public void setStopLoss(String stopLoss) {
TextView post_stoploss = mView.findViewById(R.id.sl);
post_stoploss.setText("Sl: " + stopLoss);
}
public void setProfitPips(String profitPips) {
//nothing
}
public void setLossPips(String lossPips) {
//nothing
}
public void setRewardingP(String comment) {
//nothing
}
public void setComment(String comment) {
//nothing
}
public void setRewarding(String rewarding) {
//nothing
}
public void setResult(String result) {
TextView post_result = mView.findViewById(R.id.status);
post_result.setText("result");
if (!post_result.getText().toString().trim().matches("Take Profit Hit")) {
post_result.setTextColor(Color.parseColor("#ffcc0000"));
} else if (!post_result.getText().toString().trim().matches("Stop Loss Hit")) {
post_result.setTextColor(Color.parseColor("#ff669900"));
} else if (!post_result.getText().toString().trim().matches("Pending...")) {
post_result.setTextColor(Color.parseColor("#000"));
} else {
post_result.setTextColor(Color.parseColor("#ffffff"));
}
}
}}
Help I am stack!
List<Blogzone> openedZones = new ArrayList<>();
List<Blogzone> closedZones = new ArrayList<>();
openedZones.addAll(mDatabase.stream().filter(zone -> zone.isOpened()).collect(Collectors.toList()));
closedZones.addAll(mDatabase.stream().filter(zone -> zone.isClosed()).collect(Collectors.toList()));
FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder> FBRAopened = new FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder>(
Blogzone.class,
R.layout.card_items,
BlogzoneViewHolder.class,
openedZones
) {
...
}
FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder> FBRAclosed = new FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder>(
Blogzone.class,
R.layout.card_items,
BlogzoneViewHolder.class,
closedZones
) {
...
}
//running signals
recyclerView.setAdapter(FBRAopened);
//closed signals
recyclerView2.setAdapter(FBRAclosed);

add next, prev buttons in image slider made by recyclerView

I've made Image slider with the help of recyclerView and SnapHelper. I have also added next, prev imageView under the recyclerView.
I want to implement them to work as next,prev. Their id are next, prev respectively.
This is activity where imageSlider is shown:
public class RajeshDaiActivity extends AppCompatActivity implements RajeshDaiAdapter.OnNoteListener {
public RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rajesh_dai);
recyclerView = findViewById(R.id.rv_image);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(layoutManager);
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
List<Word> wordList = new ArrayList<>();
wordList.add(new Word(R.drawable.oq, null));
wordList.add(new Word(R.drawable.oqqqq, null));
wordList.add(new Word(R.drawable.opt3, null));
RajeshDaiAdapter adapter = new RajeshDaiAdapter(this);
recyclerView.setAdapter(adapter);
adapter.addItems(wordList);
}
#Override
public void onNoteClick(int position) {
}
}
add this in your main class
int CurrenePosition = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
NextItemImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CurrenePosition < recyclerView.getAdapter().getItemCount()-1)
recyclerView.scrollToPosition(CurrenePosition + 1);
}
});
PreviousItemImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CurrenePosition > 0)
recyclerView.scrollToPosition(CurrenePosition - 1);
}
});

Categories