This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
So I've set up my RecyclerView with SQLite DB and it's populating the list, but every time I click on the list item it should open the new activity and pass data to it via intent extras.
The click gives me NullPointerException:
Process: com.daroioradecic.fxtodo, PID: 6762
java.lang.NullPointerException: Attempt to invoke interface method 'void data.RecAdapter$ItemClickCallback.onItemClick(int)' on a null object reference
at data.RecAdapter$RecHolder.onClick(RecAdapter.java:106)
at android.view.View.performClick(View.java:4856)
at android.view.View$PerformClick.run(View.java:19956)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5389)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
in my Recycler View adapter class which is:
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.RecHolder> {
private int previousPosition = 0;
private List<Todo> listData;
private LayoutInflater inflater;
private ItemClickCallback itemClickCallback;
public interface ItemClickCallback {
void onItemClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback) {
this.itemClickCallback = itemClickCallback;
}
public RecAdapter(List<Todo> listData, Context c) {
this.inflater = LayoutInflater.from(c);
this.listData = listData;
}
#Override
public RecHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.layout_row_za_listu, parent, false);
return new RecHolder(view);
}
#Override
public void onBindViewHolder(RecHolder holder, int position) {
Todo item = listData.get(position);
holder.title.setText(item.getTitle());
if (position > previousPosition) {
AnimationUtil.animate(holder, true);
} else {
AnimationUtil.animate(holder, false);
}
previousPosition = position;
}
#Override
public int getItemCount() {
return listData.size();
}
public void setListData(ArrayList<Todo> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
class RecHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView title;
private View container;
public RecHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.tekstNaListi);
container = itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
}
#Override
public void onClick(View v) {
itemClickCallback.onItemClick(getAdapterPosition());
}
}
}
It gives the error on line itemClickCallback.onItemClick(getAdapterPosition()); which is the last line in the class.
I'm overriding onClick in the class where recycler view is populated like this:
#Override
public void onItemClick(int p) {
Todo item = (Todo) listData.get(p);
Intent i = new Intent(HomeScreen.this, Details.class);
Bundle extras = new Bundle();
extras.putString("naslov", item.getTitle());
extras.putString("datum", item.getRecordDate());
extras.putInt("id", item.getItemId());
startActivity(i);
}
That class implements implements RecAdapter.ItemClickCallback
Any ideas? Thanks!
MAIN ACTIVITY CLASS: (keep in mind that I just transitioned from ListView so I haven't done any cleaning)
public class HomeScreen extends AppCompatActivity implements RecAdapter.ItemClickCallback {
private RecyclerViewUtils.ShowHideToolbarOnScrollingListener showHideToolbarListener;
//SCROLL
private Toolbar tToolbar;
// REC
private RecyclerView recView;
private RecAdapter adapter;
private ArrayList listData;
// ZA SNACKBAR
private CoordinatorLayout coordinatorLayout;
private RelativeLayout relLay;
// NAVIGACIJA
private DrawerLayout mDrawer;
private ActionBarDrawerToggle drawerToggle;
private Toolbar toolbar;
NavigationView nvDrawer;
DrawerLayout dlDrawer;
//----------------------------------------------------------------------------------------------
DatabaseHandler dba;
private ArrayList<Todo> dbTodo = new ArrayList<>();
private TodoAdapter todoAdapter;
private ListView lista;
private Cursor mCursor;
LinearLayout layoutZaUnosTodoa;
EditText editTextZaNazivTodoa;
Button buttonSave;
private CheckBox checkBoxDoneOrNotNaListi;
android.support.design.widget.FloatingActionButton fab;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.activity_home_screen);
tToolbar = (Toolbar) findViewById(R.id.tToolbar);
setSupportActionBar(tToolbar);
tToolbar.setNavigationIcon(R.drawable.ic_nav_menu);
getSupportActionBar().setTitle(R.string.app_name);
// REC
recView = (RecyclerView) findViewById(R.id.rec_list);
recView.setLayoutManager(new LinearLayoutManager(this));
adapter = new RecAdapter(listData, this);
recView.setAdapter(adapter);
adapter.setItemClickCallback(this);
recView.addOnScrollListener(showHideToolbarListener = new RecyclerViewUtils.ShowHideToolbarOnScrollingListener(tToolbar));
if (savedInstanceState != null) {
showHideToolbarListener.onRestoreInstanceState((RecyclerViewUtils.ShowHideToolbarOnScrollingListener.State) savedInstanceState
.getParcelable(RecyclerViewUtils.ShowHideToolbarOnScrollingListener.SHOW_HIDE_TOOLBAR_LISTENER_STATE));
}
layoutZaUnosTodoa = (LinearLayout) findViewById(R.id.layoutZaUnosTodoa);
editTextZaNazivTodoa = (EditText) findViewById(R.id.editTextZaNazivTodoa);
editTextZaNazivTodoa.setSelection(editTextZaNazivTodoa.getText().length());
buttonSave = (Button) findViewById(R.id.buttonSave);
//lista = (ListView) findViewById(R.id.lista);
fab = (android.support.design.widget.FloatingActionButton) findViewById(R.id.fab);
checkBoxDoneOrNotNaListi = (CheckBox) findViewById(R.id.checkBoxDoneOrNotNaListi);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordiantorLayout);
relLay = (RelativeLayout) findViewById(R.id.relLay);
refreshData();
layoutZaUnosTodoa.setVisibility(View.GONE);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layoutZaUnosTodoa.setVisibility(View.VISIBLE);
}
});
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveToDB();
layoutZaUnosTodoa.setVisibility(View.GONE);
}
});
relLay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layoutZaUnosTodoa.setVisibility(View.GONE);
}
});
dlDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
dlDrawer.setDrawerListener((DrawerLayout.DrawerListener) drawerToggle);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
drawerToggle.syncState();
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(RecyclerViewUtils.ShowHideToolbarOnScrollingListener.SHOW_HIDE_TOOLBAR_LISTENER_STATE,
showHideToolbarListener.onSaveInstanceState());
super.onSaveInstanceState(outState);
}
private void saveToDB() {
Todo todo = new Todo();
todo.setTitle(editTextZaNazivTodoa.getText().toString());
dba.addTodo(todo);
adapter.notifyDataSetChanged();
dba.close();
editTextZaNazivTodoa.setText("");
}
public void refreshData() {
dbTodo.clear();
dba = new DatabaseHandler(HomeScreen.this);
ArrayList<Todo> todoFromDB = dba.getTodo();
for (int i = 0; i < todoFromDB.size(); i++) {
String title = todoFromDB.get(i).getTitle();
String dateText = todoFromDB.get(i).getRecordDate();
int mid = todoFromDB.get(i).getItemId();
Todo myTodo = new Todo();
myTodo.setTitle(title);
myTodo.setItemId(mid);
myTodo.setRecordDate(dateText);
dbTodo.add(myTodo);
}
dba.close();
adapter = new RecAdapter(dbTodo, this);
recView.setAdapter(adapter);
// todoAdapter = new TodoAdapter(HomeScreen.this, R.layout.layout_row_za_listu, dbTodo);
//Animation collapseList = AnimationUtils.loadAnimation(HomeScreen.this, R.anim.collapse_search_results);
//lista.startAnimation(collapseList);
//lista.setAdapter(todoAdapter);
// todoAdapter.notifyDataSetChanged();
}
#Override
public void onItemClick(int p) {
Todo item = (Todo) listData.get(p);
Intent i = new Intent(HomeScreen.this, Details.class);
Bundle extras = new Bundle();
extras.putString("naslov", item.getTitle());
extras.putString("datum", item.getRecordDate());
extras.putInt("id", item.getItemId());
startActivity(i);
}
/* #Override
public void onSecondaryItemClick(int p) {
}*/
public class TodoAdapter extends ArrayAdapter<Todo> {
Activity activity;
int layoutResource;
Todo todo;
ArrayList<Todo> mData = new ArrayList<>();
public TodoAdapter(Activity act, int resource, ArrayList<Todo> data) {
super(act, resource, data);
activity = act;
layoutResource = resource;
mData = data;
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Todo getItem(int position) {
return mData.get(position);
}
#Override
public int getPosition(Todo item) {
return super.getPosition(item);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null || (row.getTag() == null)) {
LayoutInflater inflater = LayoutInflater.from(activity);
row = inflater.inflate(layoutResource, null);
holder = new ViewHolder();
holder.mTitle = (TextView) row.findViewById(R.id.tekstNaListi);
holder.checkBox = (CheckBox) row.findViewById(R.id.checkBoxDoneOrNotNaListi);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
holder.myTodo = getItem(position);
holder.mTitle.setText(holder.myTodo.getTitle());
final ViewHolder finalHolder = holder;
holder.mTitle.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
int mid = finalHolder.myTodo.getItemId();
DatabaseHandler dba = new DatabaseHandler(HomeScreen.this);
dba.deleteTodo(mid);
Snackbar snackbar = Snackbar.make(coordinatorLayout, getResources().getString(R.string.snack_bar_tekst), Snackbar.LENGTH_SHORT);
snackbar.show();
todoAdapter.notifyDataSetChanged();
return true;
}
});
/*holder.mTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = finalHolder.myTodo.getTitle().toString();
String dateText = finalHolder.myTodo.getRecordDate().toString();
int mid = finalHolder.myTodo.getItemId();
Intent i = new Intent(HomeScreen.this, Details.class);
i.putExtra("naslov", title);
i.putExtra("datum", dateText);
i.putExtra("id", mid);
startActivity(i);
}
});*/
final View finalRow = row;
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalHolder.mTitle = (TextView) finalRow.findViewById(R.id.tekstNaListi);
if (finalHolder.checkBox.isChecked()) {
finalHolder.mTitle.setPaintFlags(finalHolder.mTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
finalHolder.mTitle.setAlpha(0.5f);
} else if (!finalHolder.checkBox.isChecked()) {
finalHolder.mTitle.setPaintFlags(0);
finalHolder.mTitle.setAlpha(0.8f);
}
}
});
return row;
}
}
class ViewHolder {
Todo myTodo;
TextView mTitle, mContent, mDate;
int mId;
CheckBox checkBox;
}
EDIT:
This error shows up:
java.lang.NullPointerException: Attempt to invoke interface method 'void data.RecAdapter$ItemClickCallback.onItemClick(int)' on a null object reference
at data.RecAdapter$1.onClick(RecAdapter.java:67)
and it refeers to this line in adapter class:
itemClickCallback.onItemClick(position);
1) Check the callback null or not.
#Override
public void onClick(View v) {
if (itemClickCallback!=null){
itemClickCallback.onItemClick(getAdapterPosition());
}
}
2) The activity/class implements the method. This is okay. But, are you set the listener in your onCreate() ?
rectAdapter.setItemClickCallback(this);
3)EDITED Change your adapter like this:
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.RecHolder> {
private int previousPosition = 0;
private List<Todo> listData;
private LayoutInflater inflater;
private ItemClickCallback itemClickCallback;
public interface ItemClickCallback {
void onItemClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback) {
this.itemClickCallback = itemClickCallback;
}
public RecAdapter(List<Todo> listData, Context c) {
this.inflater = LayoutInflater.from(c);
this.listData = listData;
}
#Override
public RecHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.layout_row_za_listu, parent, false);
return new RecHolder(view);
}
#Override
public void onBindViewHolder(RecHolder holder, final int position) {
Todo item = listData.get(position);
holder.title.setText(item.getTitle());
if (position > previousPosition) {
AnimationUtil.animate(holder, true);
} else {
AnimationUtil.animate(holder, false);
}
previousPosition = position;
holder.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickCallback.onItemClick(position);
}
});
}
#Override
public int getItemCount() {
return listData.size();
}
public void setListData(ArrayList<Todo> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
class RecHolder extends RecyclerView.ViewHolder {
private TextView title;
private View container;
public RecHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.tekstNaListi);
container = itemView.findViewById(R.id.cont_item_root);
}
}}
Related
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.
I have an app using tab layout and RecyclerView for getting items. I have 2 different tabs and I wanna use two different fonts on them. I have OneActivity and for tabsi have FirstFragment, SecondFragment.
I can change whole app's font with RecyclerView_Adapter. But i don't wanna change whole app's font. In FirstFragment (First Tab) i wanna use Arial and Text size 20 sp, in SecondFragment i wanna use Comic Sans and Text size 16 sp.
How can i do that, is it possible?
OneActivity.Java
public class OneActivity extends AppCompatActivity {
private static Toolbar toolbar;
private static ViewPager viewPager;
private static TabLayout tabLayout;
private static BottomNavigationView bottomNavigationView;
private ImageButton forwardbtn, backwardbtn, pausebtn, playbtn;
private MediaPlayer mPlayer;
private TextView songName, startTime, songTime;
private SeekBar songPrgs;
private static int oTime =0, sTime =0, eTime =0, fTime = 15000, bTime = 15000;
private Handler hdlr = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
backwardbtn = (ImageButton)findViewById(R.id.btnBackward);
forwardbtn = (ImageButton)findViewById(R.id.btnForward);
playbtn = (ImageButton)findViewById(R.id.btnPlay);
pausebtn = (ImageButton)findViewById(R.id.btnPause);
startTime = (TextView)findViewById(R.id.txtStartTime);
songTime = (TextView)findViewById(R.id.txtSongTime);
mPlayer = MediaPlayer.create(this, R.raw.deneme);
songPrgs = (SeekBar)findViewById(R.id.sBar);
songPrgs.setClickable(false);
pausebtn.setEnabled(false);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);//setting tab over viewpager
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
//Implementing tab selected listener over tablayout
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());//setting current selected item over viewpager
switch (tab.getPosition()) {
case 0:
Log.e("TAG","TAB1");
break;
case 1:
Log.e("TAG","TAB2");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
playbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(OneActivity.this, "One Oynatılıyor", Toast.LENGTH_SHORT).show();
mPlayer.start();
eTime = mPlayer.getDuration();
sTime = mPlayer.getCurrentPosition();
if(oTime == 0){
songPrgs.setMax(eTime);
}
songTime.setText(String.format("%d dk, %d sn", TimeUnit.MILLISECONDS.toMinutes(eTime),
TimeUnit.MILLISECONDS.toSeconds(eTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes(eTime))) );
startTime.setText(String.format("%d dk, %d sn", TimeUnit.MILLISECONDS.toMinutes(sTime),
TimeUnit.MILLISECONDS.toSeconds(sTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes(sTime))) );
songPrgs.setProgress(sTime);
hdlr.postDelayed(UpdateSongTime, 100);
pausebtn.setEnabled(true);
playbtn.setEnabled(false);
}
});
pausebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.pause();
pausebtn.setEnabled(false);
playbtn.setEnabled(true);
Toast.makeText(getApplicationContext(),"One Duraklatıldı", Toast.LENGTH_SHORT).show();
}
});
forwardbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if((sTime + fTime) <= eTime)
{
sTime = sTime + fTime;
mPlayer.seekTo(sTime);
}
else
{
Toast.makeText(getApplicationContext(), "Daha fazla ileri sarılamaz", Toast.LENGTH_SHORT).show();
}
if(!playbtn.isEnabled()){
playbtn.setEnabled(true);
}
}
});
backwardbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if((sTime - bTime) > 0)
{
sTime = sTime - bTime;
mPlayer.seekTo(sTime);
}
else
{
Toast.makeText(getApplicationContext(), "Daha fazla geri sarılamaz", Toast.LENGTH_SHORT).show();
}
if(!playbtn.isEnabled()){
playbtn.setEnabled(true);
}
}
});
}
public Runnable UpdateSongTime = new Runnable() {
#Override
public void run() {
sTime = mPlayer.getCurrentPosition();
startTime.setText(String.format("%d dk, %d sn", TimeUnit.MILLISECONDS.toMinutes(sTime),
TimeUnit.MILLISECONDS.toSeconds(sTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(sTime))) );
songPrgs.setProgress(sTime);
hdlr.postDelayed(this, 100);
songPrgs.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mPlayer != null && fromUser){
mPlayer.seekTo(progress); // clear ' * 1000 '
}
}
});
}
};
public void onBackPressed(){
mPlayer.stop();
finish();
}
//Setting View Pager
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new FirstFragment("Android"), "Android");
adapter.addFrag(new SecondFragment("Ios"), "Ios");
viewPager.setAdapter(adapter);
}
//View Pager fragments setting adapter class
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();//fragment arraylist
private final List<String> mFragmentTitleList = new ArrayList<>();//title arraylist
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
//adding fragments and title method
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
FirstFragment
public class FirstFragment extends Fragment {
private View view;
private String title;//String for tab title
private String ebaka;
// Intent it = getActivity().getIntent();
// String isim = getActivity().getIntent().getStringExtra("FOO");
// Bundle bundle = getActivity().getIntent().getExtras();
// String value = bundle.getString("key1");
private static RecyclerView recyclerView;
public FirstFragment() {
}
#SuppressLint("ValidFragment")
public FirstFragment(String title) {
this.title = title;//Setting tab title
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.dummy_fragment, container, false);
// getActivity().getActionBar().setTitle(title);
setRecyclerView();
return view;
}
//Setting recycler view
private void setRecyclerView() {
recyclerView = (RecyclerView) view
.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView
.setLayoutManager(new LinearLayoutManager(getActivity()));//Linear Items
// String[] eArray=getActivity().getResources().getStringArray(R.array.books);
//
String[] ebaka=getActivity().getResources().getStringArray(R.array.bakara);
ArrayList<String> arrayList = new ArrayList<>();
// arrayList.add("cdscsdc");
for (int i = 0; i < ebaka.length; i++) {
arrayList.add(ebaka[i]);
}
RecyclerView_Adapter adapter = new RecyclerView_Adapter(getActivity(), arrayList);
recyclerView.setAdapter(adapter);// set adapter on recyclerview
}
}
RecyclerView_Adapter
public class RecyclerView_Adapter extends RecyclerView.Adapter<DemoViewHolder> {
private ArrayList<String> arrayList;
private Context context;
public RecyclerView_Adapter(Context context,
ArrayList<String> arrayList) {
this.context = context;
this.arrayList = arrayList;
this.arrayList = arrayList;
}
#Override
public int getItemCount() {
return (null != arrayList ? arrayList.size() : 0);
}
#Override
public void onBindViewHolder(DemoViewHolder holder,
int position) {
Typeface customTypeOne = Typeface.createFromAsset(context.getAssets(), "arial.ttf");
final DemoViewHolder mainHolder = (DemoViewHolder) holder;
//Setting text over textview
mainHolder.title.setText(arrayList.get(position));
mainHolder.title.setTypeface(customTypeOne); // With this code i change font, but it is changing whole apps font. i don't need that.
}
#Override
public DemoViewHolder onCreateViewHolder(
ViewGroup viewGroup, int viewType) {
LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext());
ViewGroup mainGroup = (ViewGroup) mInflater.inflate(
R.layout.item_row, viewGroup, false);
DemoViewHolder mainHolder = new DemoViewHolder(mainGroup) {
#Override
public String toString() {
return super.toString();
}
};
return mainHolder;
}
}
DemoViewHolder
public abstract class DemoViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public DemoViewHolder(View view) {
super(view);
this.title = (TextView) view.findViewById(R.id.cardTitle);
}
}
Update your adapter constructor and onBindViewHolder():
public class RecyclerView_Adapter extends RecyclerView.Adapter<DemoViewHolder> {
private ArrayList<String> arrayList;
private Context context;
//add this
private String comingFrom;
//constructor
public RecyclerView_Adapter(Context context, ArrayList<String> arrayList, String comingFrom) {
this.context = context;
this.arrayList = arrayList;
this.arrayList = arrayList;
this.comingFrom = comingFrom;
}
........
........
#Override
public void onBindViewHolder(DemoViewHolder holder,int position) {
Typeface customTypeOne = Typeface.createFromAsset(context.getAssets(),"arial.ttf");
final DemoViewHolder mainHolder = (DemoViewHolder) holder;
//Setting text over textview
mainHolder.title.setText(arrayList.get(position));
//check in which fragment you are
if(comingFrom.equals("fragment_one")){
//in fragment one set some font
mainHolder.title.setTypeface(........);
}else{
//in fragment two set some other font
mainHolder.title.setTypeface(.........);
}
}
............
}
When initializing adapter from FirstFragment:
.......
.......
RecyclerView_Adapter adapter = new RecyclerView_Adapter(getActivity(), arrayList, "fragment_one");
recyclerView.setAdapter(adapter);// set adapter on recyclerview
........
When initializing adapter from SecondFragment:
.......
.......
RecyclerView_Adapter adapter = new RecyclerView_Adapter(getActivity(), arrayList, "fragment_two");
recyclerView.setAdapter(adapter);// set adapter on recyclerview
........
I want to show all items in RecyclerView in Fragment to RecyclerViewMore in Another Activity when I press "See All Items", but I getting null when I want to receive the data from RecyclerViewMore
//SectionAdapter.java
public class AdapterSectionHotTrendingNews extends RecyclerView.Adapter{
private Context mContext;
private ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews;
public AdapterSectionHotTrendingNews(Context mContext, ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews) {
this.mContext = mContext;
this.modelSectionHotTrendingNews = modelSectionHotTrendingNews;
}
#Override
public SectionHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_section_hottrendingnews, null);
return new SectionHotTrendingNewsViewHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SectionHotTrendingNewsViewHolder sectionHotTrendingNewsViewHolder = (SectionHotTrendingNewsViewHolder) holder;
ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = modelSectionHotTrendingNews.get(position);
//Set
sectionHotTrendingNewsViewHolder.TVSectionTitle.setText(modelSectionHotTrendingNewsX.getHeaderTitle());
ArrayList singleSectionItems = modelSectionHotTrendingNewsX.getAllItemsInSection();
/*AdapterSingleHotLatestNews.RecyclerViewClickListener listenerLatestNews;
listenerLatestNews = new AdapterSingleHotLatestNews.RecyclerViewClickListener() {
#Override
public void onRowHotLatestNewsClick(View view, int position) {
}
#Override
public void onIconHotLatestNewsClick(View view, int position) {
}
};*/
AdapterSingleHotTrendingNews itemListDataAdapter = new AdapterSingleHotTrendingNews(mContext, singleSectionItems);
/*itemRowHolder.recycler_view_list.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
//Allow ScrollView to intercept touch events once again.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle RecyclerView touch events.
v.onTouchEvent(event);
return true;
}
});*/
sectionHotTrendingNewsViewHolder.BTNHotTrendingNewsMore.setOnClickListener(
new View.OnClickListener() { #Override public void onClick(View v) {
Intent intent = new Intent(mContext, TabMoreHotActivity.class);
new Intent().putExtra("MoreNews", modelSectionHotTrendingNews.get(position).getAllItemsInSection());
mContext.startActivity(intent); } });
/*Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
//SetRecyclerView
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setHasFixedSize(true);
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setAdapter(itemListDataAdapter);
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setNestedScrollingEnabled(false);
}
#Override
public int getItemCount() {
int itemCount = modelSectionHotTrendingNews.size();
return itemCount;
}
public class SectionHotTrendingNewsViewHolder extends RecyclerView.ViewHolder {
protected TextView TVSectionTitle;
protected ImageView BTNHotTrendingNewsMore;
protected RecyclerView RecyclerViewSectionHotTrendingNews;
protected RecyclerView RecyclerViewMoreSectionHotTrendingNews;
public SectionHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVSectionTitle = (TextView) itemView.findViewById(R.id.TV_SectionTitle);
BTNHotTrendingNewsMore= (ImageView) itemView.findViewById(R.id.BTN_HotTrendingNewsMore);
RecyclerViewSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerView_Section_HotTrendingNews);
RecyclerViewMoreSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerViewMore_Section_HotTrendingNews);
}
}
}
//SingleAdapter.java
public class AdapterSingleHotTrendingNews extends RecyclerView.Adapter{
private Context mContext;
private ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews;
public AdapterSingleHotTrendingNews(Context mContext, ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews) {
this.mContext = mContext;
this.modelSingleHotTrendingNews = modelSingleHotTrendingNews;
}
//Container
#Override
public SingleHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_single_hottrendingnews, null);
return new SingleHotTrendingNewsViewHolder(v);
}
//Fill Container with Model Setter Getter
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SingleHotTrendingNewsViewHolder singleHotTrendingNewsViewHolder = (SingleHotTrendingNewsViewHolder) holder;
final ModelSingleHotTrendingNews modelSingleHotTrendingNewsX = modelSingleHotTrendingNews.get(position);
//Set
singleHotTrendingNewsViewHolder.TVGameDate.setText(modelSingleHotTrendingNewsX.getGamedate());
singleHotTrendingNewsViewHolder.TVGameDescription.setText(modelSingleHotTrendingNewsX.getGamedescription());
singleHotTrendingNewsViewHolder.IMGGameImage.setImageResource(modelSingleHotTrendingNewsX.getGameimage());
singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Boolean booltrendingnewssaving = modelSingleHotTrendingNewsX.getTrendingnewssaving();
final int id = modelSingleHotTrendingNewsX.getId();
if (booltrendingnewssaving == true){
Toast.makeText(v.getContext(), "Turn Off Saved News " + id, Toast.LENGTH_SHORT).show();
singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_off);
modelSingleHotTrendingNewsX.setTrendingnewssaving(false);
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(booltrendingnewssaving == false) {
Toast.makeText(v.getContext(), "Turn On Saved News " + id, Toast.LENGTH_SHORT).show();
singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_on);
modelSingleHotTrendingNewsX.setTrendingnewssaving(true);
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
singleHotTrendingNewsViewHolder.ROWHotTrendingNewsContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), modelSingleHotTrendingNews.get(position).getGamedescription(), Toast.LENGTH_SHORT).show();
//Passing Data to GameDescriptionActivity
Intent intent = new Intent(mContext, GameDetailActivity.class);
intent.putExtra("ImagePKG", modelSingleHotTrendingNews.get(position).getGameimage());
intent.putExtra("NamePKG", modelSingleHotTrendingNews.get(position).getGamedate());
intent.putExtra("UrlPKG", modelSingleHotTrendingNews.get(position).getId());
intent.putExtra("DescriptionPKG", modelSingleHotTrendingNews.get(position).getGamedescription());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
int itemCount = modelSingleHotTrendingNews.size();
return itemCount;
}
public class SingleHotTrendingNewsViewHolder extends RecyclerView.ViewHolder{
TextView TVGameDate;
TextView TVGameDescription;
ImageView IMGGameImage;
ImageView ICONHotTrendingNewsSaving;
private RelativeLayout ROWHotTrendingNewsContainer;
public SingleHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVGameDate = itemView.findViewById(R.id.TV_GameDate);
TVGameDescription = itemView.findViewById(R.id.TV_GameDescription);
IMGGameImage = itemView.findViewById(R.id.IMG_GameImage);
ICONHotTrendingNewsSaving = itemView.findViewById(R.id.ICON_HotTrendingNewsSaving);
ROWHotTrendingNewsContainer = itemView.findViewById(R.id.ROW_HotTrendingNewsContainer);
}
}
}
//ModelSection.java
public class ModelSectionHotTrendingNews implements Serializable {
private String headerTitle;
private ArrayList<ModelSingleHotTrendingNews> allItemsInSection;
public ModelSectionHotTrendingNews() {
}
public String getHeaderTitle() {
return headerTitle;
}
public void setHeaderTitle(String headerTitle) {
this.headerTitle = headerTitle;
}
public ArrayList<ModelSingleHotTrendingNews> getAllItemsInSection() {
return allItemsInSection;
}
public void setAllItemsInSection(ArrayList<ModelSingleHotTrendingNews> allItemsInSection) {
this.allItemsInSection = allItemsInSection;
}
}
//ModelSingle.java
public class ModelSingleHotTrendingNews implements Serializable {
private int id;
private String gamedate;
private String gamedescription;
private int gameimage;
private Boolean trendingnewssaving;
private String value;
private String message;
public ModelSingleHotTrendingNews(int id, String gamedate, String gamedescription, int gameimage, Boolean trendingnewssaving, String value, String message) {
this.id = id;
this.gamedate = gamedate;
this.gamedescription = gamedescription;
this.gameimage = gameimage;
this.trendingnewssaving = trendingnewssaving;
this.value = value;
this.message = message;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGamedate() {
return gamedate;
}
public void setGamedate(String gamedate) {
this.gamedate = gamedate;
}
public String getGamedescription() {
return gamedescription;
}
public void setGamedescription(String gamedescription) {
this.gamedescription = gamedescription;
}
public int getGameimage() {
return gameimage;
}
public void setGameimage(int gameimage) {
this.gameimage = gameimage;
}
public Boolean getTrendingnewssaving() {
return trendingnewssaving;
}
public void setTrendingnewssaving(Boolean trendingnewssaving) {
this.trendingnewssaving = trendingnewssaving;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
//This function SectionAdapter.java is to send data from RecyclerView in Fragment to RecyclerViewMore Activity
sectionHotTrendingNewsViewHolder.BTNHotTrendingNewsMore.setOnClickListener(
new View.OnClickListener() { #Override public void onClick(View v) {
Intent intent = new Intent(mContext, TabMoreHotActivity.class);
new Intent().putExtra("MoreNews", modelSectionHotTrendingNews.get(position).getAllItemsInSection());
mContext.startActivity(intent); } });
//I use same Model in those RecyclerViews but different Adapter
//I use RecyclerView in Fragment AdapterSection.java,AdapterSingle.java,ModelSection.java,ModelSingle.java
//I user RecyclerViewMore in Activity
AdapterMoreSection.java,AdapterMoreSingle.java,ModelSection.java,ModelSingle.java
//RecyclerViewMoreActivity.java
public class TabMoreHotActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragmentmore_tabhot);
AdapterMoreSectionHotTrendingNews adapterMoreSectionHotTrendingNews;
ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews = null;
Bundle bundle = getIntent().getExtras();
if(bundle!=null)
{
modelSectionHotTrendingNews = (ArrayList<ModelSectionHotTrendingNews>) bundle.getSerializable("MoreNews");
}
//1
RecyclerView RecyclerViewMoreSingleHotTrendingNews = findViewById(R.id.RecyclerViewMore_Single_HotTrendingNews);
RecyclerViewMoreSingleHotTrendingNews.setHasFixedSize(true);
adapterMoreSectionHotTrendingNews = new AdapterMoreSectionHotTrendingNews(this, modelSectionHotTrendingNews);
RecyclerViewMoreSingleHotTrendingNews.setAdapter(adapterMoreSectionHotTrendingNews);
RecyclerViewMoreSingleHotTrendingNews.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
//Optimized
RecyclerViewMoreSingleHotTrendingNews.setHasFixedSize(true);
RecyclerViewMoreSingleHotTrendingNews.setItemViewCacheSize(20);
}
}
//I got this error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.indofun.android.indojoy, PID: 32309
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at com.indofun.android.indojoy.Adapters.AdapterMore_HotTrendingNews.AdapterMoreSectionHotTrendingNews.getItemCount(AdapterMoreSectionHotTrendingNews.java:109)
at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:4042)
at androidx.recyclerview.widget.RecyclerView.onMeasure(RecyclerView.java:3532)
at android.view.View.measure(View.java:23279)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:23279)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:23279)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
at android.view.View.measure(View.java:23279)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:23279)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:23279)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:23279)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:898)
at android.view.View.measure(View.java:23279)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2873)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1910)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2165)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1779)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7810)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
at android.view.Choreographer.doCallbacks(Choreographer.java:723)
at android.view.Choreographer.doFrame(Choreographer.java:658)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
//Provide the code it will help me a lot
//UPDATED
//AdapterMoreSingle
public class AdapterMoreSingleHotTrendingNews extends RecyclerView.Adapter{
private Context mContext;
private ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews;
public AdapterMoreSingleHotTrendingNews(Context mContext, ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews) {
this.mContext = mContext;
this.modelSingleHotTrendingNews = modelSingleHotTrendingNews;
}
//Container
#Override
public SingleMoreHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemmore_single_hottrendingnews, null);
return new SingleMoreHotTrendingNewsViewHolder(v);
}
//Fill Container with Model Setter Getter
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SingleMoreHotTrendingNewsViewHolder singleMoreHotTrendingNewsViewHolder = (SingleMoreHotTrendingNewsViewHolder) holder;
final ModelSingleHotTrendingNews modelSingleHotTrendingNewsX = modelSingleHotTrendingNews.get(position);
//Set
singleMoreHotTrendingNewsViewHolder.TVGameDate.setText(modelSingleHotTrendingNewsX.getGamedate());
singleMoreHotTrendingNewsViewHolder.TVGameDescription.setText(modelSingleHotTrendingNewsX.getGamedescription());
singleMoreHotTrendingNewsViewHolder.IMGGameImage.setImageResource(modelSingleHotTrendingNewsX.getGameimage());
singleMoreHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Boolean booltrendingnewssaving = modelSingleHotTrendingNewsX.getTrendingnewssaving();
final int id = modelSingleHotTrendingNewsX.getId();
if (booltrendingnewssaving == true){
Toast.makeText(v.getContext(), "Turn Off Saved News " + id, Toast.LENGTH_SHORT).show();
singleMoreHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_off);
modelSingleHotTrendingNewsX.setTrendingnewssaving(false);
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(booltrendingnewssaving == false) {
Toast.makeText(v.getContext(), "Turn On Saved News " + id, Toast.LENGTH_SHORT).show();
singleMoreHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_on);
modelSingleHotTrendingNewsX.setTrendingnewssaving(true);
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
singleMoreHotTrendingNewsViewHolder.ROWHotTrendingNewsContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), modelSingleHotTrendingNews.get(position).getGamedescription(), Toast.LENGTH_SHORT).show();
//Passing Data to GameDescriptionActivity
Intent intent = new Intent(mContext, GameDetailActivity.class);
intent.putExtra("ImagePKG", modelSingleHotTrendingNews.get(position).getGameimage());
intent.putExtra("NamePKG", modelSingleHotTrendingNews.get(position).getGamedate());
intent.putExtra("UrlPKG", modelSingleHotTrendingNews.get(position).getId());
intent.putExtra("DescriptionPKG", modelSingleHotTrendingNews.get(position).getGamedescription());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
int itemCount = modelSingleHotTrendingNews.size();
return itemCount;
}
public class SingleMoreHotTrendingNewsViewHolder extends RecyclerView.ViewHolder{
TextView TVGameDate;
TextView TVGameDescription;
ImageView IMGGameImage;
ImageView ICONHotTrendingNewsSaving;
private RelativeLayout ROWHotTrendingNewsContainer;
public SingleMoreHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVGameDate = itemView.findViewById(R.id.TV_GameDate);
TVGameDescription = itemView.findViewById(R.id.TV_GameDescription);
IMGGameImage = itemView.findViewById(R.id.IMG_GameImage);
ICONHotTrendingNewsSaving = itemView.findViewById(R.id.ICON_HotTrendingNewsSaving);
ROWHotTrendingNewsContainer = itemView.findViewById(R.id.ROW_HotTrendingNewsContainer);
}
}
}
//UPDATED2 AdapterSectionMore.java
public class AdapterMoreSectionHotTrendingNews extends RecyclerView.Adapter {
private Context mContext;
private ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews;
public AdapterMoreSectionHotTrendingNews(Context mContext, ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews) {
this.mContext = mContext;
this.modelSectionHotTrendingNews = modelSectionHotTrendingNews;
}
#Override
public SectionMoreHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemmore_section_hottrendingnews, null);
return new SectionMoreHotTrendingNewsViewHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SectionMoreHotTrendingNewsViewHolder sectionMoreHotTrendingNewsViewHolder = (SectionMoreHotTrendingNewsViewHolder) holder;
ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = modelSectionHotTrendingNews.get(position);
//Set
sectionMoreHotTrendingNewsViewHolder.TVSectionTitle.setText(modelSectionHotTrendingNewsX.getHeaderTitle());
// here you have to change your ArrayList to ArrayList<ModelSingleHotTrendingNews>
ArrayList<ModelSingleHotTrendingNews> singleSectionItems = modelSectionHotTrendingNewsX.getAllItemsInSection();
/*AdapterSingleHotLatestNews.RecyclerViewClickListener listenerLatestNews;
listenerLatestNews = new AdapterSingleHotLatestNews.RecyclerViewClickListener() {
#Override
public void onRowHotLatestNewsClick(View view, int position) {
}
#Override
public void onIconHotLatestNewsClick(View view, int position) {
}
};*/
AdapterMoreSingleHotTrendingNews itemListDataAdapter = new AdapterMoreSingleHotTrendingNews(mContext, singleSectionItems);
/*itemRowHolder.recycler_view_list.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
//Allow ScrollView to intercept touch events once again.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle RecyclerView touch events.
v.onTouchEvent(event);
return true;
}
});*/
final String sectionTitle = modelSectionHotTrendingNewsX.getHeaderTitle();
sectionMoreHotTrendingNewsViewHolder.BTNHotTrendingNewsMore.setOnClickListener(
new View.OnClickListener() {
#Override public void onClick(View v) {
//More IN RecyclerViewMore
}
});
/*Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
//SetRecyclerView
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setHasFixedSize(true);
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setAdapter(itemListDataAdapter);
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setNestedScrollingEnabled(false);
}
#Override
public int getItemCount() {
int itemCount = modelSectionHotTrendingNews.size();
return itemCount;
}
public class SectionMoreHotTrendingNewsViewHolder extends RecyclerView.ViewHolder {
protected TextView TVSectionTitle;
protected ImageView BTNHotTrendingNewsMore;
protected RecyclerView RecyclerViewMoreSectionHotTrendingNews;
public SectionMoreHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVSectionTitle = (TextView) itemView.findViewById(R.id.TV_SectionTitle);
BTNHotTrendingNewsMore= (ImageView) itemView.findViewById(R.id.BTN_HotTrendingNewsMore);
RecyclerViewMoreSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerViewMore_Section_HotTrendingNews);
}
}
}
Because you are passing null modelSectionHotTrendingNews to your adapter.
You just need to initialize your ArrayList in your TabMoreHotActivity
And one more thing you have to set layout manger to your recycler view before set adapter.
public class TabMoreHotActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragmentmore_tabhot);
AdapterMoreSectionHotTrendingNews adapterMoreSectionHotTrendingNews;
// here you have to initialize it
ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews = new ArrayList<>();
Bundle bundle = getIntent().getExtras();
if(bundle!=null)
{
modelSectionHotTrendingNews = (ArrayList<ModelSectionHotTrendingNews>) bundle.getSerializable("MoreNews");
}
//1
RecyclerView RecyclerViewMoreSingleHotTrendingNews = findViewById(R.id.RecyclerViewMore_Single_HotTrendingNews);
RecyclerViewMoreSingleHotTrendingNews.setHasFixedSize(true);
adapterMoreSectionHotTrendingNews = new AdapterMoreSectionHotTrendingNews(this, modelSectionHotTrendingNews);
// here have to set layout manager before set adapter
RecyclerViewMoreSingleHotTrendingNews.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
// and then you have to set adapter to recyclerview
RecyclerViewMoreSingleHotTrendingNews.setAdapter(adapterMoreSectionHotTrendingNews);
//Optimized
RecyclerViewMoreSingleHotTrendingNews.setHasFixedSize(true);
RecyclerViewMoreSingleHotTrendingNews.setItemViewCacheSize(20);
}
}
UPDATE
Change ArrayList to ArrayList<ModelSingleHotTrendingNews> inside onBindViewHolder in AdapterMoreSectionHotTrendingNews.
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SectionMoreHotTrendingNewsViewHolder sectionMoreHotTrendingNewsViewHolder = (SectionMoreHotTrendingNewsViewHolder) holder;
ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = modelSectionHotTrendingNews.get(position);
//Set
sectionMoreHotTrendingNewsViewHolder.TVSectionTitle.setText(modelSectionHotTrendingNewsX.getHeaderTitle());
// here you have to change your ArrayList to ArrayList<ModelSingleHotTrendingNews>
ArrayList<ModelSingleHotTrendingNews> singleSectionItems = modelSectionHotTrendingNewsX.getAllItemsInSection();
// reset of your codes here.
For this error
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
By #Jakir answer, you can initialize ArrayList for extra point initialize with specific size (i.e new ArrayList<>(0);) to reduce the memory usage because of array list default a lot memory of 10 objects in memory.
or
check this condition in getItem
#Override
public int getItemCount() {
return modelSectionHotTrendingNews != null && modelSectionHotTrendingNews.size();
}
It will resolve this error.
For serializable parsing in your code
Intent intent = new Intent(mContext, TabMoreHotActivity.class);
// here you create put extra in new intent not the intent that you created
new Intent().putExtra("MoreNews", modelSectionHotTrendingNews.get(position).getAllItemsInSection());
mContext.startActivity(intent);
Change this to
Intent intent = new Intent(mContext, TabMoreHotActivity.class);
// here you create put extra in new intent not the intent that you created
intent.putExtra("MoreNews", modelSectionHotTrendingNews.get(position).getAllItemsInSection());
mContext.startActivity(intent);
Happy coding.... ;)
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.
I want to pass a string value from my adapter class to my fragment. I tried storing the string in a bundle. To retrieve the value i used Bundle b = getArguments(); b.getString("key") the problem is im getting a null pointer exception. Below is the code that saves the string in a bundle. So my question is how can i pass a string value from adapterA to fragmentB.
Thanks in advance.
Adapter.java
public class ToDoRecyclerViewAdapter extends RecyclerView.Adapter<ToDoRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Aktivnost_> mValues;
private final OnListFragmentInteractionListener mListener;
public ToDoRecyclerViewAdapter td;
public ToDoRecyclerViewAdapter(List<Aktivnost_ > items, Context context, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getNaziv());
holder.mDateView.setText(mValues.get(position).getDatum());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
Intent i = new Intent(context.getApplicationContext(), PodrobnostiActivity.class);
i.putExtra("task_id", mValues.get(position).getId_());
context.getApplicationContext().startActivity(i);
Toast.makeText(v.getContext(), "task - " + mValues.get(position).getId_(), Toast.LENGTH_SHORT).show();
}
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getContext());
CharSequence meni[] = new CharSequence[] {"DOING", "FINISHED"};
adb.setItems(meni, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0) {
Bundle b = new Bundle();
DoingFragment d = new DoingFragment();
mValues.get(i).setStanje("doing");
b.putString("doing", mValues.get(i).getStanje());
d.setArguments(b);
} else {
mValues.get(i).setStanje("koncano");
}
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
return true;
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mContentView;
public final TextView mDateView;
public long id;
public Aktivnost_ mItem;
public ViewHolder(View view) {
super(view);
mView = view;
this.id = id;
mDateView = (TextView) view.findViewById(R.id.Date);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
And i want to get the value i set in bundle in this fragment.
Fragment.java
public class DoingFragment extends Fragment {
DoingFragmentRecyclerViewAdapter mAdapter;
private OnListFragmentInteractionListener mListener;
public DoingFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_doingfragment_list, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list_doing);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
mAdapter = new DoingFragmentRecyclerViewAdapter(listAktivnosti(),mListener);
recyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction1(Aktivnost_ item);
}
AppDatabase db;
public void openDB() {
db = new AppDatabase(getContext());
db.open();
}
Aktivnost_ ak;
List<Aktivnost_> array;
public List<Aktivnost_> listAktivnosti() {
array = new ArrayList<>();
openDB();
Bundle b = getArguments();
Cursor cursor = db.getAllRows(b.getString("doing"));
while(cursor.moveToNext()) {
ak = new Aktivnost_();
ak.setId_(cursor.getLong(cursor.getColumnIndex("_id")));
ak.setNaziv(cursor.getString(cursor.getColumnIndex("naziv")));
ak.setDatum(cursor.getString(cursor.getColumnIndex("datum")));
ak.setFk_projekt(cursor.getInt(cursor.getColumnIndex("fk_projekt")));
ak.setUdeleženci(cursor.getString(cursor.getColumnIndex("udelezenci")));
ak.setStanje(cursor.getString(cursor.getColumnIndex("stanje")));
array.add(ak);
}
return array;
}
}
From the code, I can see you are only setting the Bundle parameters in Fragment object, but not using that fragment object further.
You need to display that fragment object first, then it will reflect into your target fragment.