Editing a RecyclerView list item with a dialog - java

I'm building an app that manages the tasks. The user can enter the task name, set priority and add that task. What I want to implement is for the user to be able to click an item, launch an alert dialog and edit the details of that item (name, priority) from that dialog, click "Save Edits" and save the edits for that particular list item. However, the alert dialog does not launch when an item is clicked. I'm trying to call a method containing the dialog through onclick:
recyclerView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
addTaskActivity.onClickEditTask(view);
return true;
}
});
And this is the onClickEditText method:
public class AddTaskActivity extends AppCompatActivity {
...
public void onClickEditTask(View view){
String editedInput = ((EditText)findViewById(R.id.edit_task)).getText().toString();
if(editedInput.length() == 0){
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(getLayoutInflater().inflate(R.layout.edit_dialog, null))
.create();
}
...
}
Currently, I want to know how to launch this method per item click and get the details of that item plastered onto the launched dialog. The following are my relevant classes:
AddTaskActivity.java:
public class AddTaskActivity extends AppCompatActivity {
private int mPriority;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_task);
((RadioButton) findViewById(R.id.radButton1)).setChecked(true);
mPriority = 1;
}
public void onClickAddTask(View view) {
String input = ((EditText) findViewById(R.id.editTextTaskDescription)).getText().toString();
if (input.length() == 0) {
return;
}
ContentValues contentValues = new ContentValues();
contentValues.put(TaskContract.TaskEntry.COLUMN_DESCRIPTION, input);
contentValues.put(TaskContract.TaskEntry.COLUMN_PRIORITY, mPriority);
Uri uri = getContentResolver().insert(TaskContract.TaskEntry.CONTENT_URI, contentValues);
if(uri != null) {
Toast.makeText(getBaseContext(), uri.toString(), Toast.LENGTH_LONG).show();
}
finish();
}
public void onClickEditTask(View view){
String editedInput = ((EditText)findViewById(R.id.edit_task)).getText().toString();
if(editedInput.length() == 0){
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(getLayoutInflater().inflate(R.layout.edit_dialog, null))
.create();
}
public void onPrioritySelected(View view) {
if (((RadioButton) findViewById(R.id.radButton1)).isChecked()) {
mPriority = 1;
} else if (((RadioButton) findViewById(R.id.radButton2)).isChecked()) {
mPriority = 2;
} else if (((RadioButton) findViewById(R.id.radButton3)).isChecked()) {
mPriority = 3;
}
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int LOADER_ID = 0;
private CustomCursorAdapter customCursorAdapter;
RecyclerView recyclerView;
private AddTaskActivity addTaskActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewTasks);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
customCursorAdapter = new CustomCursorAdapter(this);
recyclerView.setAdapter(customCursorAdapter);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
int id = (int) viewHolder.itemView.getTag();
String itemId = Integer.toString(id);
Uri uri = TaskContract.TaskEntry.CONTENT_URI;
uri = uri.buildUpon().appendPath(itemId).build();
getContentResolver().delete(uri, null, null);
getSupportLoaderManager().restartLoader(LOADER_ID, null, MainActivity.this);
}
}).attachToRecyclerView(recyclerView);
recyclerView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
addTaskActivity.onClickEditTask(view);
return true;
}
});
FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.fab_btn);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent addTaskIntent = new Intent(MainActivity.this, AddTaskActivity.class);
startActivity(addTaskIntent);
}
});
getSupportLoaderManager().initLoader(LOADER_ID, null, this);
}
#Override
protected void onResume() {
super.onResume();
getSupportLoaderManager().restartLoader(LOADER_ID, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, final Bundle loaderArgs) {
return new AsyncTaskLoader<Cursor>(this) {
Cursor cursor = null;
#Override
protected void onStartLoading() {
if (cursor != null) {
deliverResult(cursor);
} else {
forceLoad();
}
}
#Override
public Cursor loadInBackground() {
try {
return getContentResolver().query(TaskContract.TaskEntry.CONTENT_URI,
null,
null,
null,
TaskContract.TaskEntry.COLUMN_PRIORITY);
} catch (Exception e) {
Log.e(TAG, "Failed to load data.");
e.printStackTrace();
return null;
}
}
public void deliverResult(Cursor data) {
cursor = data;
super.deliverResult(data);
}
};
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
customCursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
customCursorAdapter.swapCursor(null);
}
}
CustomCursorAdapter.java:
public class CustomCursorAdapter extends RecyclerView.Adapter<CustomCursorAdapter.TaskViewHolder> {
private Cursor cursor;
private Context con;
public CustomCursorAdapter(Context context) {
this.con = context;
}
#Override
public TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(con).inflate(R.layout.task_layout, parent, false);
return new TaskViewHolder(view);
}
#Override
public void onBindViewHolder(TaskViewHolder holder, int position) {
int index = cursor.getColumnIndex(TaskContract.TaskEntry._ID);
int descriptionOfIndex = cursor.getColumnIndex(TaskContract.TaskEntry.COLUMN_DESCRIPTION);
int priorityofIndex = cursor.getColumnIndex(TaskContract.TaskEntry.COLUMN_PRIORITY);
cursor.moveToPosition(position);
final int id = cursor.getInt(index);
String description = cursor.getString(descriptionOfIndex);
int priority = cursor.getInt(priorityofIndex);
holder.itemView.setTag(id);
holder.taskDescriptionView.setText(description);
String priorityString = "" + priority;
holder.priorityView.setText(priorityString);
GradientDrawable priorityCircle = (GradientDrawable) holder.priorityView.getBackground();
int priorityColor = getPriorityColor(priority);
priorityCircle.setColor(priorityColor);
}
private int getPriorityColor(int priority) {
int priorityColor = 0;
switch(priority) {
case 1: priorityColor = ContextCompat.getColor(con, R.color.materialRed);
break;
case 2: priorityColor = ContextCompat.getColor(con, R.color.materialOrange);
break;
case 3: priorityColor = ContextCompat.getColor(con, R.color.materialYellow);
break;
default: break;
}
return priorityColor;
}
#Override
public int getItemCount() {
if (cursor == null) {
return 0;
}
return cursor.getCount();
}
public Cursor swapCursor(Cursor c) {
if (cursor == c) {
return null;
}
Cursor temp = cursor;
this.cursor = c;
if (c != null) {
this.notifyDataSetChanged();
}
return temp;
}
class TaskViewHolder extends RecyclerView.ViewHolder {
TextView taskDescriptionView;
TextView priorityView;
public TaskViewHolder(View itemView) {
super(itemView);
taskDescriptionView = (TextView) itemView.findViewById(R.id.taskDescription);
priorityView = (TextView) itemView.findViewById(R.id.priorityTextView);
}
}
}

You appear to have omitted showing the alter dialog by coding builder.show();
Additionally may want to setup some buttons (you can use Neutral, Positive and Negative buttons, below is example with just Neutral button).
You probably want to set the title and make the AlertDialog cancelable.
You may also have an issue with the custom layout, so the code below will ignore that and use the default layout.
I believe that the following code will fix this issue:-
public void onClickEditTask(View view){
String editedInput = ((EditText)findViewById(R.id.edit_task)).getText().toString();
if(editedInput.length() == 0){
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Test");
builder.setCancelable(true);
builder.setNeutralButton("TEST", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("TAG","You click the TEST button of the dialog.");
}
});
builder.show();
}
Introducing a custom layout
The following is the above but with an added rudimentary custom view, first the layout, namely test_hi.xml :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/buildertv"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="30dp"
android:layout_marginStart="30dp"
android:layout_marginLeft="30dp"
android:text="TEST"
android:textColor="#ff557799"
android:gravity="center"
>
</TextView>
</LinearLayout>
And the code (i.e. with builder.setView(R.layout.test_hi); added) :-
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(R.layout.test_hi);
builder.setTitle("Test");
builder.setCancelable(true);
builder.setNeutralButton("TEST", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("TAG","You clicked the TEST button of the dialog.");
}
});
builder.show();
Running the above should be something like (*running the previous code will not have the middle *Test**):-
Clicking the bottom (Red) Test will add a line to the log along the lines of:-
....D/TAG: You clicked the TEST button of the dialog.
You would replace Log.d("TAG","You clicked the TEST button of the dialog."); with the code that you want to run when the Neutral Button is clicked. If you wanted other options then you can use the Positive and Negative buttons in a similar way by adding builder.setPositiveButton(.... and builder.setNegativeButton(.... accordingly.

Related

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.

RadioButton checked sate automatically changes on scrolling event of RecyclerView

I am facing problem with my RadioButton in RecyclerView item. According to the 'type' I changes the checked RadioButton. But after all data loaded, then when I click the non checked radio button it's get checked. But after scrolling the checked radio button which I just clicked that goes unchecked. I want the button which I just clicked to be checked. But it is doesn't stays checked. How do I get what I want? Can anyone please help me!!!!!!!
This is my Adapter Class:
public class AttendanceAdapterLocal extends RecyclerView.Adapter<AttendanceAdapterLocal.ViewHolder>{
private ArrayList<StudentAttendance> attendanceArrayList;
private Context context;
public AttendanceAdapterLocal(ArrayList<StudentAttendance> attendanceArrayList) {
this.attendanceArrayList = attendanceArrayList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item_mark_attendance, viewGroup, false);
context = viewGroup.getContext();
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, int i) {
final String type = attendanceArrayList.get(i).getType();
final String id = attendanceArrayList.get(i).getId();
final String name = attendanceArrayList.get(i).getName();
final String roll = attendanceArrayList.get(i).getRoll();
viewHolder.setData(name, roll, type, id);
final DatabaseHelper databaseHelper = new DatabaseHelper(context);
final User user = new AccessStorage(context).getUserDetails();
final String userId = user.getUserId();
viewHolder.radioPresent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (databaseHelper.updateStudentAttendanceData(id, userId, "P", "0") > 0) {
Toast.makeText(context, "Marked successfully.", Toast.LENGTH_LONG).show();
viewHolder.radioPresent.setChecked(true);
} else {
Toast.makeText(context, "Unable to mark attendance.", Toast.LENGTH_LONG).show();
}
}
});
viewHolder.radioAbsent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (databaseHelper.updateStudentAttendanceData(id, userId, "A", "0") > 0) {
Toast.makeText(context, "Marked successfully.", Toast.LENGTH_LONG).show();
viewHolder.radioAbsent.setChecked(true);
} else {
Toast.makeText(context, "Unable to mark attendance.", Toast.LENGTH_LONG).show();
}
}
});
viewHolder.radioNone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (databaseHelper.updateStudentAttendanceData(id, userId, "NA", "0") > 0) {
Toast.makeText(context, "Marked successfully.", Toast.LENGTH_LONG).show();
viewHolder.radioNone.setChecked(true);
} else {
Toast.makeText(context, "Unable to mark attendance.", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public int getItemCount() {
return attendanceArrayList.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// Widgets
private TextView textName;
private RadioGroup radioGroup;
private RadioButton radioPresent, radioAbsent, radioNone;
// Vars
private View view;
public ViewHolder(#NonNull View itemView) {
super(itemView);
view = itemView;
textName = view.findViewById(R.id.textName);
radioGroup = view.findViewById(R.id.radioGroup);
radioPresent = view.findViewById(R.id.radioPresent);
radioAbsent = view.findViewById(R.id.radioAbsent);
radioNone = view.findViewById(R.id.radioNone);
}
private void setData(String name, String roll, final String type, final String id) {
textName.setText(roll + ". " + name);
if (type.equals("P")) {
radioPresent.setChecked(true);
} else if(type.equals("A")) {
radioAbsent.setChecked(true);
}else if(type.equals("NA")) {
radioNone.setChecked(true);
}
}
}
}
Just a small mistake . In your onClick method , while changing the state just notify the adapter .
#Override
public void onClick(View v) {
if (databaseHelper.updateStudentAttendanceData(id, userId, "P", "0") > 0) {
Toast.makeText(context, "Marked successfully.", Toast.LENGTH_LONG).show();
viewHolder.radioPresent.setChecked(true);
//Notify adapter
attendanceArrayList.notify();
} else {
Toast.makeText(context, "Unable to mark attendance.", Toast.LENGTH_LONG).show();
}
}
I can see , everywhere you have done the same thing .Its important to notify the adapter while changing anything in the list . You either use notifyDataSetChanged() or notifyItemChanged(selectedPosition);
If you still face the problem you should create a Model class.
Use Interface on click of the radio buttons, make necessary changes in your original list that you are passing in recycler view(Inside Activity) then use notifiDataSetChanged() method.

clickable string array items inside each recycleview item

I have an API which have data like this:
{"seasons":[
{
"id":"1",
"titles":"1title1;1title2;1title3",
"url":"1url1;1url2;1url3;"
},
{
"id":"2",
"titles":"2title1;2title2;2title3",
"url":"2url1;2url2;2url3;"
}
]}
I parse it well and in parcelable class I did this for titles:
public String getTitles() {
return titles;
}
public StringBuilder getFullTitles() {
StringBuilder builder = new StringBuilder();
String[] titlesArray = getTitles().split(";");
for (String title : titlesArray) {
builder.append(title + "\n");
}
and this for url:
public String getUrlAdaptive() {
return urladaptive;
}
public StringBuilder getFullUrlAdaptiveFinal() {
StringBuilder builder2 = new StringBuilder();
String[] urlArray = getUrlAdaptive().split(";");
for (String details : urlArray) {
builder2.append(details + "\n");
}
return builder2;
}
so in my recycleview adapter I fetch titles data like this in textview:
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.title.setText(String.valueOf(mMoviesItems.get(position).getFullTitles()));
}
and the result that I got in my recycleview app is like this:
1title1
1title2
1title3
2title1
2title2
2title3
now you can see that this group:
1title1
1title2
1title3
refer to the first item of recycleview
and this group:
2title1
2title2
2title3
refer to the second item of recycleview
you can compare it with api to understand what I mean
what I need to do is to make each item of each group is applicable to be clicked
like when I click on 1title1 I got the url that correspond the title which is 1url1 to open it in youtube
and when I click on 1title2 I got the url that correspond the title which is 1url2 to open it in youtube
and when I click on 2title2 I got the url that correspond the title which is 2url2 to open it in youtube
and so on
it's like click items inside each of main item of recycleview
this is the code after try an answer:
#Override
public void onBindViewHolder(final RecyclerViewHolder holder, final int position) {
holder.title.setText(String.valueOf(mMoviesItems.get(position).getFullTitles()));
holder.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vview) {
// here when click on each title I need to get the getFullUrlAdaptiveFinal with it to play it
}
});
}
and this is full code for series_list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#21293B"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#fff"
android:textSize="14sp"
android:visibility="visible" />
<TextView
android:id="#+id/url"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#fff"
android:textSize="14sp"
android:visibility="visible" />
</LinearLayout>
Adapter Code:
public class SeriesAdapter extends RecyclerView.Adapter<SeriesAdapter.RecyclerViewHolder> {
ArrayList<SeriesItem> mMoviesItems;
private Context context;
private SeriesAdapterOnClickHandler mClickHandler;
public interface SeriesAdapterOnClickHandler {
void onClick(SeriesItem movie);
}
public SeriesAdapter(SeriesAdapterOnClickHandler clickHandler) {
mClickHandler = clickHandler;
}
public void setClickListener(SeriesAdapterOnClickHandler callback) {
mClickHandler = callback;
}
class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final TextView SeriesSeasontitle;
public final TextView urlAdaptive;
public RecyclerViewHolder(View view) {
super(view);
SeriesSeasontitle = (TextView)itemView.findViewById(R.id.title);
urlAdaptive = (TextView)itemView.findViewById(R.id.url);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
SeriesItem movie = mMoviesItems.get(adapterPosition);
String text = "already Added To Favorites";
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
mClickHandler.onClick(movie);
}
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
context = viewGroup.getContext();
int layoutIdForListItem = R.layout.series_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
RecyclerViewHolder holder = new RecyclerViewHolder(view);
return new RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(final RecyclerViewHolder holder, final int position) {
holder.SeriesSeasontitle.setText(String.valueOf(mMoviesItems.get(position).getFullTitles()));
holder.SeriesSeasontitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vview) {
String text = "text";
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
if (null == mMoviesItems)
return 0;
else {
return mMoviesItems.size();
}
}
#Override
public int getItemViewType(int position) {
if (null == mMoviesItems)
return 0;
else {
return mMoviesItems.size();
}
}
public void setMovieData(ArrayList<SeriesItem> movieData) {
mMoviesItems = movieData;
notifyDataSetChanged();
}
}
Activity code:
SeriesDetail extends AppCompatActivity implements
SeriesAdapter.SeriesAdapterOnClickHandler {
SeriesAdapter mAdapterTrailer;
RecyclerViewAdapterOthers mAdapterOthers;
#BindView(R.id.rv_videos)
RecyclerView mVideosList;
#BindView(R.id.tv_error_message_display3)
TextView mErrorMessageDisplay3;
#BindView(R.id.rv_videos2)
RecyclerView mTrailersList;
#BindView(R.id.pb_loading_indicator_trailers2)
ProgressBar mLoadingIndicatorTrailers2;
String sortOrder2="seasons/1435";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_series_detail);
ButterKnife.bind(this);
LinearLayoutManager LayoutManager2 = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mTrailersList.setLayoutManager(LayoutManager2);
mTrailersList.setHasFixedSize(true);
mAdapterTrailer = new SeriesAdapter(this);
mTrailersList.setAdapter(mAdapterTrailer);
loadVideosData(String.valueOf(sortOrder2));
}
private void loadVideosData(String movieId) {
showVideoDataView();
new FetchVideosTask().execute(movieId);
}
#Override
public void onClick(SeriesItem video) {
}
private void showTrailerDataView() {
mErrorMessageDisplay3.setVisibility(View.INVISIBLE);
mTrailersList.setVisibility(View.VISIBLE);
}
private void showErrorMessage3() {
mTrailersList.setVisibility(View.INVISIBLE);
mErrorMessageDisplay3.setVisibility(View.VISIBLE);
}
public class FetchVideosTask extends AsyncTask<String, Void, ArrayList<SeriesItem>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mLoadingIndicatorTrailers2.setVisibility(View.VISIBLE);
}
#Override
protected ArrayList<SeriesItem> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
String movieId = params[0];
URL videosRequestUrl = NetworkSeries.buildUrl(movieId);
try {
String jsonVideoResponse = NetworkSeries.getResponseFromHttpUrl(videosRequestUrl);
ArrayList<SeriesItem> simpleJsonVideoData = JsonShashaDetailSeries.getSimpleMovieStringsFromJson(SeriesDetail.this, jsonVideoResponse);
return simpleJsonVideoData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(ArrayList<SeriesItem> videoData) {
mLoadingIndicatorTrailers2.setVisibility(View.INVISIBLE);
if (videoData != null) {
showTrailerDataView();
mAdapterTrailer.setMovieData(videoData);
} else {
showErrorMessage3();
}
}
}
#Override
protected void onStart() {
super.onStart();
}
}
and parcalable class:
public class SeriesItem implements Parcelable {
private String titles;
private String urladaptive;
public SeriesItem(String titles, String urladaptive) {
this.titles = titles;
this.urladaptive = urladaptive;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(titles);
out.writeString(urladaptive);
}
private SeriesItem(Parcel in) {
this.titles = in.readString();
this.urladaptive = in.readString();
}
public SeriesItem() {
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<SeriesItem> CREATOR = new Creator<SeriesItem>() {
#Override
public SeriesItem createFromParcel(Parcel in) {
return new SeriesItem(in);
}
#Override
public SeriesItem[] newArray(int i) {
return new SeriesItem[i];
}
};
public String getTitles() {
return titles;
}
public StringBuilder getFullTitles() {
StringBuilder builder = new StringBuilder();
String[] titlesArray = getTitles().split(";");
for (String details : titlesArray) {
builder.append(details + "\n");
}
return builder;
}
public String getUrlAdaptive() {
return urladaptive;
}
public StringBuilder getFullUrlAdaptiveFinal() {
StringBuilder builder2 = new StringBuilder();
String[] urlArray = getUrlAdaptive().split(";");
for (String details : urlArray) {
builder2.append(details + "\n");
}
return builder2;
}
}
I just try to display a toast message when onclick the above code to test the click of items and it work
but if I would like when I click on title like now so the url of same item start play
how I handle this click? in adapter itself or in activity?
Yes this is possible. Simply use an OnClickListener and set it in your onBindViewHolder().
It would look something like this:
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.title.setText(String.valueOf(mMoviesItems.get(position).getFullTitles()));
holder.title.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// Toast here
}
}
}

Why do I have to restart my app for my RecyclerView to display data from SQLite?

EDIT 1: I used debugging statements and it turns out that when I add an item to the database it is successful. However, the updateUI() method is not called because what I am launching is a DialogFragment() so my ListActivity does not enter a paused state. But, if I exit the app and launch again the adapter gets updated. So now the question becomes how do I update the adapter after exiting the dialog fragment?
I'm building a simple list app and added SQLite database to store task object. I am successfully adding items to the database, but they do not show up immediately in the RecyclerView I am using to show all tasks. It is only when I completely exit from the app and reload that tasks items show up in the RecyclerView.
ListFragment.java this will create the RecyclerView
public class ListFragment extends Fragment {
private static final String DEBUG_LOG = "debug_message";
private static final String ADD_DIALOG = "add_dialog";
private static final int REQUEST_TITLE = 0;
private RecyclerView mRecyclerView;
private TaskAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_list, container, false);
mRecyclerView = view.findViewById(R.id.the_task_list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(linearLayoutManager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mRecyclerView.getContext(), linearLayoutManager.getOrientation());
mRecyclerView.addItemDecoration(dividerItemDecoration);
updateUI();
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK && requestCode == ListFragment.REQUEST_TITLE) {
UUID taskId = (UUID) data.getSerializableExtra(EditTaskFragment.EXTRA_TASK_ID);
String newTaskName = data.getStringExtra(EditTaskFragment.EXTRA_TASK_TITLE);
if(newTaskName != null) {
Task task = TaskLab.get(getActivity()).getTask(taskId);
task.setTitle(newTaskName);
TaskLab.get(getActivity()).updateTask(task);
}
updateUI();
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_list_item, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.add_new_task:
FragmentManager manager = getFragmentManager();
AddTaskFragment dialog = new AddTaskFragment();
dialog.show(manager, ADD_DIALOG);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
public void updateUI() {
// Retrieves ArrayList<Task>
List<Task> taskList = TaskLab.get(getActivity()).getTaskList();
if(mAdapter == null) {
mAdapter = new TaskAdapter(taskList);
mRecyclerView.setAdapter(mAdapter);
}else {
mAdapter.setCrimes(taskList);
mAdapter.notifyDataSetChanged();
}
}
private class TaskAdapter extends RecyclerView.Adapter<TaskHolder>{
private List<Task> mTaskList;
public TaskAdapter(List<Task> taskList) {
mTaskList = taskList;
}
#Override
public TaskHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.task_list_layout, parent, false);
return new TaskHolder(view);
}
#Override
public void onBindViewHolder(TaskHolder holder, int position) {
final Task currentTask = mTaskList.get(position);
holder.bindData(currentTask);
final TextView taskTitle = holder.mTaskTitle;
holder.mSolved.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked) {
taskTitle.setPaintFlags(taskTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
currentTask.setSolved(true);
}else {
taskTitle.setPaintFlags(taskTitle.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
}
}
});
}
#Override
public int getItemCount() {
return mTaskList.size();
}
public void setCrimes(List<Task> taskList) {
mTaskList = taskList;
}
}
private class TaskHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private Task mTask;
private TextView mTaskTitle;
private CheckBox mSolved;
private static final String EDIT_DIALOG = "edit_dialog";
public TaskHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mTaskTitle = itemView.findViewById(R.id.task_title);
mSolved = itemView.findViewById(R.id.task_solved);
}
public void bindData(Task task) {
mTask = task;
mTaskTitle.setText(mTask.getTitle());
mSolved.setChecked(mTask.isSolved());
}
#Override
public void onClick(View view) {
if(!mSolved.isChecked()) {
FragmentManager manager = getFragmentManager();
EditTaskFragment dialog = EditTaskFragment.newInstance(mTask.getId());
dialog.setTargetFragment(ListFragment.this, REQUEST_TITLE);
dialog.show(manager, EDIT_DIALOG);
}
}
}
AddTaskFragment.java this will allow the user to add a task item to the RecyclerView
public class AddTaskFragment extends DialogFragment {
private EditText mTaskTitle;
private void addTask() {
if(!mTaskTitle.getText().toString().equals("")) {
Task task = new Task();
task.setTitle(mTaskTitle.getText().toString());
TaskLab.get(getActivity()).addTask(task);
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//return super.onCreateDialog(savedInstanceState);
View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_task_dialog,null);
mTaskTitle = view.findViewById(R.id.task_title);
return new AlertDialog.Builder(getActivity())
.setView(view)
.setTitle(R.string.add_new_task_dialog_title)
.setPositiveButton(R.string.add_new_task_dialog_positive, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
addTask();
}
})
.create();
}
}
TaskLab.java this is a singleton class
public class TaskLab {
private static TaskLab sTaskLab;
private Context mContext;
private SQLiteDatabase mDatabase;
private TaskLab(Context context){
mContext = context.getApplicationContext();
mDatabase = new TaskBaseHelper(mContext).getWritableDatabase();
}
public static TaskLab get(Context context) {
if(sTaskLab == null) {
sTaskLab = new TaskLab(context);
}
return sTaskLab;
}
public List<Task> getTaskList(){
List<Task> taskList = new ArrayList<Task>();
TaskCursorWrapper cursor = queryTasks(null, null);
// If there is something in the table query it
try {
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
Task task = cursor.getTask();
taskList.add(task);
cursor.moveToNext();
}
} finally {
cursor.close();
}
return taskList;
}
public void addTask(Task task) {
ContentValues values = getContentValues(task);
mDatabase.insert(TaskTable.NAME, null, values);
}
public void updateTask(Task task) {
ContentValues values = getContentValues(task);
String uuidString = task.getId().toString();
mDatabase.update(TaskTable.NAME,values, TaskTable.Cols.UUID + " = ?", new String[] {uuidString});
}
public Task getTask(UUID id){
TaskCursorWrapper cursor = queryTasks(TaskTable.Cols.UUID + " = ?",
new String[] {id.toString()});
try {
if(cursor.getCount() == 0) {
return null;
}
cursor.moveToFirst();
return cursor.getTask();
} finally {
cursor.close();
}
}
private static ContentValues getContentValues(Task task) {
ContentValues values = new ContentValues();
values.put(TaskTable.Cols.UUID, task.getId().toString());
values.put(TaskTable.Cols.TITLE, task.getTitle());
values.put(TaskTable.Cols.SOLVED, task.isSolved());
return values;
}
private TaskCursorWrapper queryTasks(String whereClause, String[] whereArgs) {
Cursor cursor = mDatabase.query(TaskTable.NAME,
null,
whereClause,
whereArgs,
null,
null,
null);
return new TaskCursorWrapper(cursor);
}
}
It must be reCreate your adapter in updateUI every time from the beginning
Try it like this and see. In your onCreateView() of fragment before updateUI() add below line of code.
Note: Create taskList as global variable.
mRecyclerView = view.findViewById(R.id.the_task_list);
mAdapter = new TaskAdapter(taskList);
mRecyclerView.setAdapter(mAdapter);
updateUI();
After that create your updateUI() method as below
public void updateUI() {
taskList.clear;
taskList = TaskLab.get(getActivity()).getTaskList();
mAdapter.notifyDataSetChanged();
}
Update:
As per your updated question, declare one global variable in ListFragment as
public static ListFragment listFragment;
In your onCreate method of ListFragment after inflating view add below line of code.
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_list, container, false);
listFragment = this;
Then change your addTask method in AddTaskFragment as below.
private void addTask() {
if(!mTaskTitle.getText().toString().equals("")) {
Task task = new Task();
task.setTitle(mTaskTitle.getText().toString());
TaskLab.get(getActivity()).addTask(task);
//import listfragment from your ListFragment
listFragment.updateUI();
}
}

notifydatasetchanged() not working after onbackpressed()

My recyclerview is not updating correctly after the back button is
pressed.
The recyclerview works fine before the back button is pressed
The data is properly updated (seen in the log) but the recyclerview does not reflect the change
The purpose of the handler is to poll the database for a notification (working fine)
The notification toast is displayed everytime
I am not receiving any errors
If I can provide any other information to help do not hesitate to ask.
Main:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
recView = (RecyclerView) findViewById(R.id.recyclerViewMessages);
linearLayoutManager = new LinearLayoutManager(this) {};
linearLayoutManager.setReverseLayout(true);
recView.setLayoutManager(linearLayoutManager);
listData = (ArrayList) MessagingData.getMessageListData();
adapter = new RecyclerViewAdapterMessaging(listData, this);
recView.setAdapter(adapter);
adapter.setItemClickCallback(this);
final Handler h = new Handler();
final int delay = 2000; //milliseconds
h.postDelayed(new Runnable(){
public void run(){
Notify_Message_Async notify_message_async = new Notify_Message_Async(ctx);
notify_message_async.execute(NOTIFICATION, message_id);
System.out.println(global.getNotification());
if(global.getNotification()==1){
Toast.makeText(ctx, "Notified",
Toast.LENGTH_LONG).show();
try {
refresh_receive();
} catch (ExecutionException e) {
Toast.makeText(ctx, "catch",
Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (InterruptedException e) {
Toast.makeText(ctx, "catch",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
h.postDelayed(this, delay);
}
}, delay);
}
public void refresh_receive() throws ExecutionException, InterruptedException {
String method = "receive_message";
Receive_Live_Message_Async receive_live_message_async = new Receive_Live_Message_Async(this);
receive_live_message_async.execute(method, message_id).get();// Setup the message
adapter.setListData((ArrayList)MessagingData.getMessageListData());
adapter.notifyDataSetChanged();
global.setNotification(0);//reset notification
}
Adapter:
public class RecyclerViewAdapterMessaging extends RecyclerView.Adapter<RecyclerViewAdapterMessaging.Holder> {
private View v;
private List<List_Item_Messaging> listData;
private LayoutInflater inflater;
Global global = new Global();
private ItemClickCallback itemClickCallback;
Context context;
public interface ItemClickCallback {
void onItemClick(View v, int p);
void onSecondaryIconClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback) {
this.itemClickCallback = itemClickCallback;
}
public RecyclerViewAdapterMessaging(List<List_Item_Messaging> listData, Context c) {
inflater = LayoutInflater.from(c);
context = c;
this.listData = listData;
}
#Override
public int getItemViewType(int position) {//0 for self... /1 for Other
List_Item_Messaging item = listData.get(position);
//ENSURE GLOBAL USERNAME NOT NULL
String other_username = item.getMessage_username();
if (other_username == null) {
((Activity) context).finish();
}
if (item.getMessage_username().trim().equals(global.getUserName())) {
System.out.println("The usernames are the same");
return 0;
} else {
System.out.println("The usernames are the NOT same");
return 1;
}
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0:
View view = inflater.inflate(R.layout.chat_thread, parent, false);// Self
v = view;
break;
case 1:
View view2 = inflater.inflate(R.layout.chat_thread_other, parent, false);// Not self
int width2 = global.getScreenWidth();
v = view2;
break;
}
return new Holder(v);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
List_Item_Messaging item = listData.get(position);
holder.conversation.setText(item.getMessage_conversation());
}
public void setListData(ArrayList<List_Item_Messaging> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
#Override
public int getItemCount() {
return listData.size();
}
class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView thumbnail;
//ImageView secondaryIcon;
TextView conversation;
View message_container;
public Holder(View itemView) {
super(itemView);
conversation = (TextView) itemView.findViewById(R.id.conversation_textview);
message_container = itemView.findViewById(R.id.message_container);
message_container.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.message_container) {
itemClickCallback.onItemClick(v, getAdapterPosition());
} else {
itemClickCallback.onSecondaryIconClick(getAdapterPosition());
}
}
}
public void clearItems() {
listData.clear();
this.notifyDataSetChanged();
}
}
I have referenced the following to no solution:
notifyDataSetChanged not working on RecyclerView
smoothScrollToPosition after notifyDataSetChanged not working in android
adapter.notifyDataSetChange() not working after called from onResume()
change a little in your code
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
recView = (RecyclerView) findViewById(R.id.recyclerViewMessages);
linearLayoutManager = new LinearLayoutManager(this) {};
linearLayoutManager.setReverseLayout(true);
recView.setLayoutManager(linearLayoutManager);
// change here
if (listData != null)
listData.clear();
else listData = new <> ArrayList();
listData.addAdd((ArrayList)MessagingData.getMessageListData());
adapter = new RecyclerViewAdapterMessaging(listData, this);
recView.setAdapter(adapter);
adapter.setItemClickCallback(this);
final Handler h = new Handler();
final int delay = 2000; //milliseconds
then make a small change here
public void refresh_receive() throws ExecutionException, InterruptedException {
String method = "receive_message";
Receive_Live_Message_Async receive_live_message_async = new Receive_Live_Message_Async(this);
receive_live_message_async.execute(method, message_id).get();// Setup the message
// changing here
dataList.clear();
dataList.addAdd((ArrayList)MessagingData.getMessageListData())
adapter.setListData(dataList);
adapter.notifyDataSetChanged();
global.setNotification(0);//reset notification
}
another problem in your code, you are using receive_live_message_async AsyncTask
put your update code in onPostExecute
public class receive_live_message_async extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Object o) {
// call your refresh_receive(); here
super.onPostExecute(o);
}
}
similarly when you are call receive_live_message_async.execute(); update your recyclerView in onPostExecute
#Override
protected void onPostExecute(Object o) {
dataList.clear();
dataList.addAll((ArrayList)MessagingData.getMessageListData());
adapter.notifyDataSetChanged();
super.onPostExecute(o);
}

Categories