How Can I get item id [duplicate] - java

This question already has answers here:
how to get ID of the items in recyclerview
(2 answers)
Closed 2 years ago.
I have recyclerview on my project . I want get item id . How Can I get item id ? . I used Item touchhelper and I need particular item id . How can I get particular item id .
Activty.java
public class todoactivity extends AppCompatActivity {
TextView title;
Button back;
ImageButton gorevo;
RecyclerView recyclerView;
List<String>Listsx = new ArrayList<>();
TodoActivityAdpter adapterx;
DatabaseHelper4 myDBxxx;
TextView textView;
CheckBox checkBox;
long id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todoactivity);
recyclerView=findViewById(R.id.recyclerviewxx);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapterx=new TodoActivityAdpter(Listsx);
recyclerView.setAdapter(adapterx);
title=findViewById(R.id.titlex);
textView=findViewById(R.id.text_viewx);
gorevo = findViewById(R.id.gorevo);
myDBxxx = new DatabaseHelper4(this);
Cursor datax = myDBxxx.getListContents();
if(datax.getCount() == 0){
}else{
while(datax.moveToNext()){
Listsx.add(datax.getString(1));
ListAdapter listAdapterx = new ArrayAdapter<>(this,R.layout.todoactivity_item,R.id.textitem,Listsx);
adapterx.notifyItemInserted(Listsx.size()-1);
}
}
gorevo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(todoactivity.this);
bottomSheetDialog.setContentView(R.layout.bottomsheetlayout3);
bottomSheetDialog.show();
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
EditText editText = bottomSheetDialog.findViewById(R.id.editx);
Button ekle = bottomSheetDialog.findViewById(R.id.ekle);
ekle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = editText.getText().toString();
Listsx.add(text);
AddDataxxx(text);
adapterx.notifyItemInserted(Listsx.size()-1);
bottomSheetDialog.hide();
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
}
});
}
});
back=findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(todoactivity.this, pomodoroscreen.class);
startActivity(i);
overridePendingTransition(0,0);
}
});
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
int positionx = viewHolder.getAdapterPosition();
Listsx.remove(positionx);
adapterx.notifyItemRemoved(positionx);
myDBxxx.deleteItem(// I want get id in there);
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
}
public void AddDataxxx(String newEntry) {
boolean insertDatax = myDBxxx.addDataxxx(newEntry);
}
}
MyAdapter.java
public class TodoActivityAdpter extends RecyclerView.Adapter<TodoActivityAdpter.Holder> {
List<String>Listsx;
public TodoActivityAdpter(List<String>itemxxx){
this.Listsx = itemxxx;
}
#NonNull
#Override
public TodoActivityAdpter.Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.todoactivity_item,parent,false);
Holder holder = new Holder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull TodoActivityAdpter.Holder holder, int position) {
holder.textView.setText(Listsx.get(position));
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.checkBox.isChecked()) {
holder.textView.setTextColor(view.getResources().getColor(R.color.grey));
} else {
holder.textView.setTextColor(view.getResources().getColor(R.color.Color_black));
}
}
});
}
#Override
public int getItemCount() {
return Listsx.size();
}
public class Holder extends RecyclerView.ViewHolder {
CheckBox checkBox;
TextView textView;
List<String>Listsx;
RecyclerView recyclerView;
Context mContext;
public Holder(View view) {
super(view);
textView=view.findViewById(R.id.text_viewx);
checkBox=view.findViewById(R.id.checkbox);
recyclerView=view.findViewById(R.id.recyclerviewxx);
}
}
}
I want get item id in Activty . How Can I get item id . Can you be fast . My actvity is activity.java . My adapter is MyAdapter.java

int positionx = viewHolder.getAdapterPosition();
int id = recyclerView.getChildAt(position).getId();
Listsx.remove(positionx);
adapterx.notifyItemRemoved(positionx);
myDBxxx.deleteItem(id);
maybe

Related

On Clicking one button, it Triggers another button in recycle view

I'm currently working on a attandance management Android app. In my recyclerview there are list of student detail being populated dynamically from database. When i click the first button in the list, it also change the button colour of the 11th button of the list Like wise to 2nd button click changes the colour of 12th View button
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;`enter code here`
List<StudentDetails> MainImageUploadInfoList;
public RecyclerViewAdapter(Context context, List<StudentDetails> TempList) {
this.MainImageUploadInfoList = TempList;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
StudentDetails studentDetails = MainImageUploadInfoList.get(position);
holder.StudentNameTextView.setText(studentDetails.getName());
holder.StudentNumberTextView.setText(studentDetails.getPhoneNumber());
holder.st.setText(studentDetails.getRollno());
holder.cardView.setCardBackgroundColor(getcolor(position));
}
private int getcolor(int position) {
return Color.parseColor("#" + Integer.toHexString(ContextCompat.getColor(context, R.color.normal)));
}
#Override
public int getItemCount() {
return MainImageUploadInfoList.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView StudentNameTextView;
public TextView StudentNumberTextView;
public TextView st;
DatabaseReference databaseReference;
String se,wh,su,d;
Button b;
CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
StudentNameTextView = (TextView) itemView.findViewById(R.id.ShowStudentNameTextView);
StudentNumberTextView = (TextView) itemView.findViewById(R.id.ShowStudentNumberTextView);
st = (TextView) itemView.findViewById(R.id.studentrollno);
cardView=itemView.findViewById(R.id.cardview1);
se=Teacher.getInstance().getSe();
wh=Teacher.getInstance().getWh();
su=Teacher.getInstance().getSu();
d=Teacher.getInstance().getD();
b=itemView.findViewById(R.id.button3);
itemView.findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view ) {
int position=getAdapterPosition();
String message = String.valueOf(position) ;
databaseReference= FirebaseDatabase.getInstance().getReference("attandance").child(wh).child(se).child(su).child(d).child(message);
databaseReference.setValue("p");
itemView.findViewById(R.id.button3).setBackgroundColor(Color.GREEN);
itemView.findViewById(R.id.button4).setEnabled(false);
itemView.findViewById(R.id.button3).setEnabled(false);
Toast.makeText( context,"position is "+String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
itemView.findViewById(R.id.button4).setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(final View view ) {
int position=getAdapterPosition();
String message = String.valueOf(position) ;
databaseReference= FirebaseDatabase.getInstance().getReference("attandance").child(wh).child(se).child(su).child(d).child(message);
databaseReference.setValue("A");
itemView.findViewById(R.id.button4).setBackgroundColor(Color.RED);
itemView.findViewById(R.id.button3).setEnabled(false);
itemView.findViewById(R.id.button4).setEnabled(false);
}
});
}
#Override
public void onClick(View view) {
// int position=this.getAdapterPosition();
// Intent intent=new Intent(context,mark.class);
// String message = String.valueOf(position);
// intent.putExtra("attan",message);
// context.startActivity(intent);
// Intent intent = new Intent(context,mark.class);
//String message = String.valueOf(position) ;
//intent.putExtra("attan",message);
//context.startActivity(intent);
// Toast.makeText( context,"position is "+String.valueOf(position), Toast.LENGTH_SHORT).show();
}
}
}
}

Transition between 2 recycler views having cards

I have 2 recycler views that have cards.They basically look the same have the same number of cards and everthing. The first one is for like viewing and other stuff and the second one is only for deleting cards. OnlongClicking a card in the first recycler view triggers the opening of the second recycler view. I wanted to add transitions in between them like what keep notes has done when a card is long clicked. Both the recycler view use the same adapter. I have set what the adapter should do based on passing context to the adapter. enter image description here this is my 1st layout having the 1st recycler view.enter image description here this is the 2nd layout having the second recycler view.I want like a seamless transition for the tool bar again just like what Google keeps has done.A simple solution would be preferred as I am very new to this stuff.
Here is the java code for the adapter.
public class Task_recycle_view_adapter extends RecyclerView.Adapter<Task_recycle_view_adapter.ViewHolder>{
private List<struct_task> task_list= new ArrayList<>();
private ArrayList<String> isSelected=new ArrayList<String>();
protected Context context1;
protected Context context2;
private String labelName;
private String taskName;
private ConstraintLayout label_menu_avatar;
public Task_recycle_view_adapter(Context context1,Context context2)
{
this.context1=context1;
this.context2=context2;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {//parent is the parent of the recycle view it is taken as an arg to use it to attach the every view to the parent view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_task,parent,false);//to inflate a layout
ViewHolder holder= new ViewHolder(view);
return holder;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.taskname.setText(task_list.get(position).getTask_name());
holder.taskid.setText(String.valueOf(task_list.get(position).getTask_id()));
if(context2==null && context1!=null) {
String taskName=task_list.get(position).getTask_name();
Long taskid=task_list.get(position).getTask_id();
String duedate=task_list.get(position).getDue_date();
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper dataBaseHelper = new DataBaseHelper(context1);
ArrayList<SubTaskModel> subtask_list=(ArrayList<SubTaskModel>) dataBaseHelper.getAllSubTasksFor(labelName, Long.parseLong(holder.taskid.getText().toString()));
Intent intent1 =new Intent(context1,ViewTaskActivity.class);
intent1.putExtra("label_name",labelName);
intent1.putExtra("task_id",taskid);
intent1.putExtra("task_name",taskName);
intent1.putExtra("due_date",duedate);
intent1.putParcelableArrayListExtra("subtask_list", (ArrayList<? extends Parcelable>) subtask_list);
context1.startActivity(intent1);
}
});
holder.parent.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent intent2 = new Intent(context1, Delete_page_Activity.class);
intent2.putParcelableArrayListExtra("task_list", (ArrayList<? extends Parcelable>) task_list);
intent2.putExtra("label_name",labelName);
intent2.putExtra("selected_task",taskName);
Pair[] pairs = new Pair[1];
pairs[0]= new Pair<View,String>(label_menu_avatar,"transition1");
ActivityOptions options= ActivityOptions.makeSceneTransitionAnimation((Activity) context1,pairs);
context1.startActivity(intent2,options.toBundle());
return true;
}
});
}
if(context2!=null && context1==null)
{
if(taskName.equals(task_list.get(position).getTask_name()))
{
holder.active=1;
isSelected.add(holder.taskid.getText().toString());
holder.parent.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card);
}
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.active==0) {
isSelected.add(holder.taskid.getText().toString());
v.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card);
holder.active=1;
}
else {
isSelected.remove(holder.taskid.getText().toString());
v.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card_transparent);
holder.active=0;
}
}
});
}
// subtasks 1 to 5
if(task_list.get(position).getSubtask1()!=null)
holder.subtask1.setText(task_list.get(position).getSubtask1());
else
holder.subtask1.setVisibility(View.GONE);
if(task_list.get(position).getSubtask2()!=null)
holder.subtask2.setText(task_list.get(position).getSubtask2());
else
holder.subtask2.setVisibility(View.GONE);
if(task_list.get(position).getSubtask3()!=null)
holder.subtask3.setText(task_list.get(position).getSubtask3());
else
holder.subtask3.setVisibility(View.GONE);
if(task_list.get(position).getSubtask4()!=null)
holder.subtask4.setText(task_list.get(position).getSubtask4());
else
holder.subtask4.setVisibility(View.GONE);
if(task_list.get(position).getSubtask5()!=null)
holder.subtask5.setText(task_list.get(position).getSubtask5());
else
holder.subtask5.setVisibility(View.GONE);
// due date
if(task_list.get(position).getDue_date()!=null)
holder.duedate.setText(task_list.get(position).getDue_date());
else
holder.duedate.setVisibility(View.GONE);
// progress
holder.progresscircle.setProgress(task_list.get(position).getProgress());
}
#Override
public int getItemCount() {
return task_list.size();
}
public void setTask_list(List<struct_task> task_list) {
this.task_list = task_list;//to refresh the data inside the recycler view
}
#Override
public int getItemViewType(int position) {
return position;
}
public String getLabelName() {
return labelName;
}
public void setLabelName(String labelName) {
this.labelName = labelName;
}
public ArrayList<String> getIsSelected() {
return isSelected;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public void setLabel_menu_avatar(ConstraintLayout label_menu_avatar) {
this.label_menu_avatar = label_menu_avatar;
}
public static class ViewHolder extends RecyclerView.ViewHolder{// holds the view for every item inside the recycle view
private TextView taskname,taskid,duedate,subtask1,subtask2,subtask3,subtask4,subtask5;
private CardView parent;
private ProgressBar progresscircle;
public void setActive(int active) {
this.active = active;
}
private int active;
public ViewHolder(#NonNull View itemView) {
super(itemView);
taskid=itemView.findViewById(R.id.task_id);
taskname = itemView.findViewById(R.id.task_name);
parent = itemView.findViewById(R.id.card_for_every_task);
duedate = itemView.findViewById(R.id.due_date);
progresscircle = itemView.findViewById(R.id.progress_circular);
subtask1 = itemView.findViewById(R.id.subtask_1);
subtask2 = itemView.findViewById(R.id.subtask_2);
subtask3 = itemView.findViewById(R.id.subtask_3);
subtask4 = itemView.findViewById(R.id.subtask_4);
subtask5 = itemView.findViewById(R.id.subtask_5);
active=0;
}
}
}
Here is the code for the 1st activity i.e the 1st image:
public class TaskPageActivity extends AppCompatActivity {
private RecyclerView task_rv;//task recycler view
private FloatingActionButton addTask;
private long tasksNum;
private String labelName;
private DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
private Task_recycle_view_adapter adapter= new Task_recycle_view_adapter(this,null);
private List<struct_task> tasks;
private EditText searchBar;
private ConstraintLayout search_btn;
private ConstraintLayout calendar_btn;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_title);
getWindow().getSharedElementExitTransition();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
search_btn= findViewById(R.id.search_btn);
calendar_btn=findViewById(R.id.calendar_btn);
search_btn.setClickable(true);
search_btn.setFocusable(true);
labelName = getIntent().getExtras().getString("832715");
TextView txtLabelName = findViewById(R.id.Label_name);
txtLabelName.setText(labelName);
task_rv = findViewById(R.id.Recycle_view_task);
addTask = findViewById(R.id.add_task);
searchBar= (SearchBar) findViewById(R.id.search_bar);
tasksNum = getTasksNum(labelName, dataBaseHelper, adapter); //displays all tasks and return number of tasks
ConstraintLayout.LayoutParams params= (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
addTask.setOnClickListener(view -> {
tasksNum = getTasksNum(labelName, dataBaseHelper, adapter);
Intent intent = new Intent(TaskPageActivity.this, AddTaskPageActivity.class);
intent.putExtra("labelName", labelName);
intent.putExtra("taskID", tasksNum);
startActivity(intent);
});
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(searchBar.getVisibility()==View.INVISIBLE) {
search_btn.setAlpha(.5f);
searchBar.setVisibility(View.VISIBLE);
searchBar.requestFocus();
imm.showSoftInput(searchBar,InputMethodManager.SHOW_IMPLICIT);
ConstraintLayout.LayoutParams params= (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
params.verticalBias = .55f;
searchBar.setLayoutParams(params);
searchBar.requestFocus();
}
else {
searchBar.setVisibility(View.INVISIBLE);
search_btn.setAlpha(1.0f);
}
}
});
searchBar.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
if(params.verticalBias==.9f) {
searchBar.requestFocus();
params.verticalBias = .55f;
searchBar.setLayoutParams(params);
}
searchBar.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if((event.getAction()==KeyEvent.ACTION_DOWN) && (keyCode==KeyEvent.KEYCODE_ENTER) && params.verticalBias==.55f)
{
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
searchBar.requestFocus();
params.verticalBias = .9f;
searchBar.setLayoutParams(params);
searchBar.clearFocus();
imm.hideSoftInputFromWindow(searchBar.getWindowToken(),0);
}
return false;
}
});
}
}
});
searchBar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
AlertDialog alertDialog = new AlertDialog.Builder(TaskPageActivity.this).create();
calendar_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(calendar_btn.getAlpha()==1.0f) {
calendar_btn.setAlpha(.5f);
LayoutInflater inflater = getLayoutInflater();
View view1 = inflater.inflate(R.layout.dialog_calendar,null);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
alertDialog.setView(view1);
CalendarView mCalendarView= view1.findViewById(R.id.calendar);
mCalendarView.setMinDate(Calendar.getInstance().getTimeInMillis());
alertDialog.show();
}
}
});
alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if(calendar_btn.getAlpha()==.5f)
calendar_btn.setAlpha(1.0f);
}
});
}
private void filter(String string) {
ArrayList<struct_task> filteredList = new ArrayList<>();
for(struct_task item: tasks)
{
if(item.getTask_name().contains(string) || item.getTask_name().contains(string.toUpperCase()))
{
filteredList.add(item);
}
}
if(filteredList.size()!=0) {
adapter.setTask_list(filteredList);
task_rv.setAdapter(adapter);
}
}
#Override
public void onBackPressed() {
if(searchBar.getText().toString().length()!=0) {
showAllTasks(labelName, dataBaseHelper, adapter);
searchBar.setText(null);
searchBar.setVisibility(View.INVISIBLE);
search_btn.setAlpha(1.0f);
}
else if(searchBar.getText().toString().length()==0)
{
super.onBackPressed();
}
}
#Override
protected void onResume() {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
showAllTasks(labelName, dataBaseHelper, adapter);
if(params.verticalBias==.54f) {
searchBar.requestFocus();
params.verticalBias = .9f;
searchBar.setLayoutParams(params);
searchBar.clearFocus();
}
if(searchBar.getText().toString().length()==0) {
showAllTasks(labelName, dataBaseHelper, adapter);
}
else {
filter(searchBar.getText().toString());
}
super.onResume();
}
private void showAllTasks(String labelName, DataBaseHelper dataBaseHelper, Task_recycle_view_adapter adapter) {
tasks = dataBaseHelper.getAllTasksFor(labelName);
adapter.setLabelName(labelName);
adapter.setTask_list(tasks);
task_rv.setAdapter(adapter);
task_rv.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
}
long getTasksNum(String labelName, DataBaseHelper dataBaseHelper, Task_recycle_view_adapter adapter) {
return dataBaseHelper.getLastTaskID(labelName)+1; //to determine ID of next task
}
#Override
protected void onUserLeaveHint() {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
params.verticalBias=.9f;
searchBar.setLayoutParams(params);
searchBar.setText(null);
searchBar.clearFocus();
super.onUserLeaveHint();
}
}
And finally for the 2nd activity which is triggered by longclicking any card
public class Delete_page_Activity extends AppCompatActivity {
private Task_recycle_view_adapter recycle_view_adapter = new Task_recycle_view_adapter(null,this);
private ArrayList<String> delete_list=new ArrayList<>();
private DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
private String labelName=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_page);
overridePendingTransition(0,0);
Toolbar toolbar=findViewById(R.id.toolbar_bar);
ImageView close_btn=findViewById(R.id.close_btn);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
ArrayList<struct_task> task_list = getIntent().getParcelableArrayListExtra("task_list");
labelName=getIntent().getExtras().getString("label_name");
String task = getIntent().getExtras().getString("selected_task");
Log.e("test",labelName);
RecyclerView recyclerView = findViewById(R.id.delete_Recycler_View);
recycle_view_adapter.setTaskName(task);
recycle_view_adapter.setTask_list(task_list);
recyclerView.setAdapter(recycle_view_adapter);
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
close_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.tool_bar_item1:
delete_list = recycle_view_adapter.getIsSelected();
if(delete_list.size()==0)
{
Toast toast1= new Toast(this);
toast1.setDuration(Toast.LENGTH_SHORT);
LayoutInflater inflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.activity_toast_msg1,null);
view.setBackgroundResource(R.drawable.background_for_calendar);
toast1.setView(view);
toast1.show();
}
else {
for (int task = 0; task < delete_list.size(); task++) {
dataBaseHelper.deleteOneTask(labelName, Long.parseLong(delete_list.get(task)));
}
finish();
}
break;
case R.id.tool_bar_item2:
Boolean flag=dataBaseHelper.deleteAllCompletedTasks(labelName);
if(flag)
finish();
else
{
Toast toast2= new Toast(this);
toast2.setDuration(Toast.LENGTH_SHORT);
LayoutInflater inflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.activity_toast_msg2,null);
view.setBackgroundResource(R.drawable.background_for_calendar);
toast2.setView(view);
toast2.show();
}
break;
}
return true;
}
}
I have added the code related to the scene transititon which is in the adapter.
here is a gif of the problem when i add a scene transition
enter image description here
As u can see there are 2 pauses when going from 1st to 2nd activity 1st pause being longer 2nd one shorter. And also a pause when exiting the 2nd activity which seems to have the same duration as the 2nd pause.

How to set up custom input dialog for saving data in Firebase when user clicks any textview widget in cardview?

In MainActivity I have NavigationDrawer. For each menu item, I have a fragment class with a corresponding layout. One of them is MyCardFragment.java. In this fragment, I am showing CardView through RecyclerView.
My CardView contains some TextViews and an ImageView. What I wanted is when a user clicks a widget it will open a custom input dialog (contains a TextView, an EditText, a positive button, and a negative button) for updating data in Firebase Real-time database. I created a dialog fragment class, but don't know how to implement it in my adapter class.
This is my main activity which holds RecyclerView and CardView:
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth=FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
if (currentUser != null){
myRef = FirebaseDatabase.getInstance().getReference().child("user").child(currentUser.getUid());
}
mContext = MainActivity.this;
mDrawerLayout = findViewById(R.id.drawer_layout);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.ic_action_name);
NavigationView navigationView = findViewById(R.id.nav_view);
//navigationView.inflateHeaderView(R.layout.nav_header);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// set item as selected to persist highlight
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
switch (menuItem.getItemId()) {
case R.id.nav_myCards:
menuItem.setChecked(true);
getSupportActionBar().setTitle("MY Cards");
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,new MyCardFragment())
.commit();
break;
return true;
}
});
mDrawerLayout.addDrawerListener(
new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Respond when the drawer's position changes
}
#Override
public void onDrawerOpened(View drawerView) {
// Respond when the drawer is opened
}
#Override
public void onDrawerClosed(View drawerView) {
// Respond when the drawer is closed
}
#Override
public void onDrawerStateChanged(int newState) {
// Respond when the drawer motion state changes
}
}
);
navigationView.getMenu().getItem(0).setChecked(true);
//Highlighted
//onNavigationItemSelected(navigationView.getMenu().getItem(0));
setupFirebaseAuth();
if (currentUser != null){
//updateNavHeader();
}
}
Custom Dialog Fragment:
DialogCompanyAddress.java:
public class DialogCompanyAddress extends DialogFragment {
public DialogCompanyAddress() {
// Required empty public constructor
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.fragment_dialog_company_address,null));
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//save data to the firebase
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Do
}
});
return builder.create();
}
}
finally the adapter:
RecyclerviewAdapter.java:
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyHolder> {
// ... constructor and member variables
// Usually involves inflating a layout from XML and returning the holder
Context mContext;
List<Template> listdata;
public RecyclerviewAdapter(Context context,List<Template> listdata) {
this.mContext = context;
this.listdata = listdata;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
/*// Inflate the custom layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview,parent,false);
// Return a new holder instance
MyHolder myHolder = new MyHolder(view);
return myHolder;*/
View view = LayoutInflater.from(mContext).inflate(R.layout.cardview,parent,false);
return new MyHolder(view);
}
public void onBindViewHolder(MyHolder holder, int position) {
holder.pname.setText(listdata.get(position).getP_name());
holder.pdesignation.setText(listdata.get(position).getP_designation());
holder.pemail.setText(listdata.get(position).getP_email());
holder.pphone.setText(listdata.get(position).getP_phone());
holder.cname.setText(listdata.get(position).getC_name());
holder.caddress.setText(listdata.get(position).getC_address());
//holder.tempID.setText(listdata.get(position).getTempID());
Glide.with(mContext).load(listdata.get(position).getC_logo()).into(holder.logo_image);
}
#Override
public int getItemCount() {
//return listdata.size();
int arr = 0;
try{
if(listdata.size()==0) {
arr = 0;
} else {
arr=listdata.size();
}
} catch (Exception e){
e.printStackTrace();
}
return arr;
}
class MyHolder extends RecyclerView.ViewHolder{
// Your holder should contain a member variable
// for any view that will be set as you render a row
TextView pname,caddress,pemail,pdesignation,pphone,cname,tempID;
ImageView logo_image;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
public MyHolder(final View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
pname = (TextView) itemView.findViewById(R.id.txt_personName);
caddress = (TextView) itemView.findViewById(R.id.txt_address);
pemail = (TextView) itemView.findViewById(R.id.txt_email);
pdesignation = (TextView) itemView.findViewById(R.id.txt_designation);
pphone = (TextView) itemView.findViewById(R.id.txt_phone);
cname = (TextView) itemView.findViewById(R.id.txt_companyName);
logo_image = itemView.findViewById(R.id.imageView);
tempID = itemView.findViewById(R.id.tempID);
caddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(mContext,"Clicked on Address",Toast.LENGTH_SHORT).show();
DialogCompanyAddress address = new DialogCompanyAddress();
//address.show(getSupportFragmentManager);--->This line give me error
}
});
}
}
use a interface in your adapter like below
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyHolder> {
public interface ClickListner {
void IconClick(Template template);
}
Context mContext;
List<Template> listdata;
private final ClickListner listner;
public RecyclerviewAdapter(Context context, List<Template> listdata, ClickListner listner) {
this.mContext = context;
this.listdata = listdata;
this.listner = listner;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.cardview, parent, false);
return new MyHolder(view);
}
public void onBindViewHolder(MyHolder holder, int position) {
holder.pname.setText(listdata.get(position).getP_name());
holder.pdesignation.setText(listdata.get(position).getP_designation());
holder.pemail.setText(listdata.get(position).getP_email());
holder.pphone.setText(listdata.get(position).getP_phone());
holder.cname.setText(listdata.get(position).getC_name());
holder.caddress.setText(listdata.get(position).getC_address());
//holder.tempID.setText(listdata.get(position).getTempID());
Glide.with(mContext).load(listdata.get(position).getC_logo()).into(holder.logo_image);
holder.bind(listdata.get(position), listner);
}
#Override
public int getItemCount() {
//return listdata.size();
int arr = 0;
try {
if (listdata.size() == 0) {
arr = 0;
} else {
arr = listdata.size();
}
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
class MyHolder extends RecyclerView.ViewHolder {
TextView pname, caddress, pemail, pdesignation, pphone, cname, tempID;
ImageView logo_image;
public MyHolder(final View itemView) {
super(itemView);
pname = (TextView) itemView.findViewById(R.id.txt_personName);
caddress = (TextView) itemView.findViewById(R.id.txt_address);
pemail = (TextView) itemView.findViewById(R.id.txt_email);
pdesignation = (TextView) itemView.findViewById(R.id.txt_designation);
pphone = (TextView) itemView.findViewById(R.id.txt_phone);
cname = (TextView) itemView.findViewById(R.id.txt_companyName);
logo_image = itemView.findViewById(R.id.imageView);
tempID = itemView.findViewById(R.id.tempID);
// caddress.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// //Toast.makeText(mContext,"Clicked on
Address",Toast.LENGTH_SHORT).show();
// DialogCompanyAddress address = new DialogCompanyAddress();
// //address.show(getSupportFragmentManager);--->This line give me
error
//
// }
// });
}
public void bind(final Template template, final ClickListner Listner) {
// DeleteIcon.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// delListner.onDeleteIconClick(card, position);
// }
// });
caddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Listner.IconClick(template);
}
});
}
}
and in your fragment you need to initialize the adapter. when initialize you can override the ClickListner interface.

Problem with display RecyclerView using BottomSheetDialog

I am not able to bind recyclerview with adapter using BottomSheetDialog
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
BottomAppBar bottomAppBar;
FloatingActionButton floatingActionButton;
ImageView emptyView;
private RecyclerView recyclerView;
private List<AppModel> appModelResult = new ArrayList<>();
private AppAdapter appAdapter;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emptyView = findViewById(R.id.empty_view);
bottomAppBar = findViewById(R.id.bottom_app_bar);
setSupportActionBar(bottomAppBar);
floatingActionButton =findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddAppDialog addAppDialog = new AddAppDialog();
addAppDialog.show(getSupportFragmentManager(),"AddBottomSheet");
}
});
bottomAppBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomSheetDialog bottomSheet = new BottomSheetDialog();
bottomSheet.show(getSupportFragmentManager(), "BottomSheet");
}
});
//RecyclerView Binding
recyclerView = findViewById(R.id.app_list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
appAdapter = new AppAdapter(appModelResult);
recyclerView.setAdapter(appAdapter);
appAdapter.setItems(appModelResult);
if(appAdapter.getItemCount() == 0){
recyclerView.setVisibility(View.GONE);
emptyView.setVisibility(View.VISIBLE);
}else{
recyclerView.setVisibility(View.VISIBLE);
emptyView.setVisibility(View.GONE);
}
}}
And here is my BottomSheetDialog, where i input 2 EditText and a Spinner.Taping on Save Button should display written data on the main screen, however there is nothing on a display.
public class AddAppDialog extends BottomSheetDialog implements AdapterView.OnItemSelectedListener {
static TextInputEditText appUrl;
TextInputEditText appDesc;
MaterialButton saveButton;
Spinner spinnerCategory;
AppModel appModel = new AppModel();
List<AppModel> appModelResult = new ArrayList<>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_bottomsheet_add,container,false);
appUrl = v.findViewById(R.id.app_url);
appDesc = v.findViewById(R.id.app_desc);
saveButton = v.findViewById(R.id.save_button);
spinnerCategory = v.findViewById(R.id.spinner_category);
List<String> categories = new ArrayList<String>();
categories.add(0,"Choose category");
categories.add("Education");
categories.add("Entertainment");
categories.add("Games");
categories.add("Health");
categories.add("Personalization");
categories.add("Social");
categories.add("Tools");
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(getActivity().getApplicationContext(),android.R.layout.simple_spinner_item,categories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategory.setAdapter(adapter);
spinnerCategory.setOnItemSelectedListener(this);
appUrl.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
#Override
public void afterTextChanged(Editable s) {
new Parse().execute();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(appUrl.getText().toString().trim().length() != 0) {
appModel.setAppDesc(appDesc.getText().toString());
appModelResult.add(0,new AppModel(Parse.eImage,Parse.eName,appModel.getAppCategory(),appModel.getAppDesc()));
System.out.println(appModelResult.get(0).getImage());
System.out.println(appModelResult.get(0).getAppText());
System.out.println(appModelResult.get(0).getAppCategory());
System.out.println(appModelResult.get(0).getAppDesc());
dismiss();
}else{
appUrl.setError("URL is required :)");
}
}
});
return v;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getItemAtPosition(position).equals("Choose category")){
}else{
String selectedCategory = parent.getItemAtPosition(position).toString();
appModel.setAppCategory(selectedCategory);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}}
Finally, my Adapter for RecyclerView looks like that:
public class AppAdapter extends RecyclerView.Adapter<AppAdapter.AppViewHolder> {
private List<AppModel> mAppModelList;
public AppAdapter(List<AppModel> appModelList) {
mAppModelList = appModelList;
}
public static class AppViewHolder extends RecyclerView.ViewHolder{
public ImageView appImage;
public TextView appText,appCategory,appDesc;
public AppViewHolder(#NonNull View itemView) {
super(itemView);
appImage = itemView.findViewById(R.id.app_image_list);
appText = itemView.findViewById(R.id.app_text_list);
appCategory = itemView.findViewById(R.id.app_category_list);
appDesc = itemView.findViewById(R.id.app_desc_list);
}
}
public void setItems(List<AppModel> items){
mAppModelList.addAll(items);
notifyDataSetChanged();
}
public void clearItems(){
mAppModelList.clear();
notifyDataSetChanged();
}
#NonNull
#Override
public AppViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_list,parent,false);
AppViewHolder appViewHolder = new AppViewHolder(v);
return appViewHolder;
}
#Override
public void onBindViewHolder(#NonNull AppViewHolder holder, int position) {
AppModel appModel = mAppModelList.get(position);
holder.appText.setText(appModel.getAppText());
holder.appCategory.setText(appModel.getAppCategory());
holder.appDesc.setText(appModel.getAppDesc());
Picasso.get().load(appModel.getImage()).into(holder.appImage);
}
#Override
public int getItemCount() {
return mAppModelList.size();
}}
I think that XML files are OK,therefore i have not pasted it here, and the only problem is regarding to binding process.
Solved it adding RecyclerView in Fragment and refreshing list via detach & attach
getActivity().getSupportFragmentManager().beginTransaction().detach(getFragmentManager().findFragmentById(R.id.recycler_fragment)).commitNowAllowingStateLoss();
getActivity().getSupportFragmentManager().beginTransaction().attach(new RecyclerFragment()).commitAllowingStateLoss();
Attention!
In order reload fragment use only dynamic fragments.

Check if all items in RecyclerView have the same value (google Firestore)

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;
}
}

Categories