Fail to solve E/RecyclerView: No adapter attached; skipping layout - java

When back to previous activity or I get out the app is closed and show this error:
E/RecyclerView: No adapter attached; skipping layout
Within a asycntask in his method onPostExecute I declare a recycleview and RecyclerView.LayoutManager but no have idea what it's wrong. I need your help to solve this problem. Below is my code:
#Override
public void onPostExecute(List<Modules> result) {
if (pDialog.isShowing()){
RecyclerView.LayoutManager Manager =new LinearLayoutManager(DepartureModule.this);
RecyclerView.Adapter adapter = new ModuleAdapter(result);
RecyclerView RVODetails = (RecyclerView) findViewById(R.id.RVODetails);
RVODetails.setLayoutManager(Manager);
RVODetails.setAdapter(adapter);
pDialog.dismiss();
}
and this is my adapter class:
public class ModuleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ItemClickListener itemClickListener;
public final ImageButton Actions;
public final ImageView Image;
public final TextView ModuleCode;
public final TextView ModuleDescription;
public final TextView ModuleDate;
public String ModuleIds;
public ModuleViewHolder(View itemView) {
super(itemView);
Image = (ImageView)itemView.findViewById(R.id.logo);
Actions = (ImageButton)itemView.findViewById(R.id.Actions);
//TitleModuleCode = (TextView)itemView.findViewById(R.id.TitleModuleCode);
ModuleCode = (TextView)itemView.findViewById(R.id.ModuleCode);
//TitleModuleDescription = (TextView)itemView.findViewById(R.id.TitleModuleDescription);
ModuleDescription = (TextView)itemView.findViewById(R.id.ModuleDescription);
ModuleDate = (TextView)itemView.findViewById(R.id.ModuleDate);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
this.itemClickListener.OnItemClick(view,getLayoutPosition());
// Toast.makeText(view.getContext(), "POS" + getLayoutPosition()
// , Toast.LENGTH_LONG).show();
}
public void setItemClickListener(ItemClickListener ItemClick){
this.itemClickListener = ItemClick;
}
}
public ModuleAdapter(List<Modules> Items){
this.Items = Items;
}
#Override
public int getItemCount() {
return Items.size();
}
#Override
public ModuleViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.layout_cardview,viewGroup,false);
return new ModuleViewHolder(view);
}
#Override
public void onBindViewHolder(final ModuleViewHolder ViewHolder, final int position) {
context = ViewHolder.itemView.getContext();
Typeface typeface = Typeface.createFromAsset(context.getAssets(),
"fonts/CaviarDreams.ttf");
ViewHolder.Image.setImageResource(Items.get(position).getImages());
ViewHolder.Actions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ShowPopupMenu(ViewHolder.Actions,position,ViewHolder);
}
});
ViewHolder.ModuleCode.setText(Items.get(position).getModule());
ViewHolder.ModuleCode.setTypeface(typeface); ViewHolder.ModuleDescription.setText(Items.get(position).getDescription());
ViewHolder.ModuleDescription.setTypeface(typeface);
ViewHolder.ModuleDate.setText(Items.get(position).getDate());
ViewHolder.ModuleDate.setTypeface(typeface);
ViewHolder.ModuleIds = Items.get(position).getModuleIds();
ViewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void OnItemClick(View view, int Pos) {
//Toast.makeText(context, "POSITION :" + Pos, Toast.LENGTH_SHORT).show();
}
});
}
private void ShowPopupMenu (final View view, final int position,final ModuleViewHolder holder){
menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.action_modify:
final Connection connectionupdate = new Connection(context,Connection.DATABASE_NAME,null,
Connection.DATABASE_VERSION);
final SQLiteDatabase dbUpdate = connectionupdate.getWritableDatabase();
Typeface typeface = Typeface.createFromAsset(context.getAssets(),"fonts/CaviarDreams.ttf");
AlertDialog.Builder ModifyModule = new AlertDialog.Builder(context);
LayoutInflater modifyinflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
final View viewmodify = modifyinflater.inflate(R.layout.layout_custom_dialog_create_modules,null);
TILM = (TextInputLayout)viewmodify.findViewById(R.id.TILM);
TILM.setTypeface(typeface);
TILD = (TextInputLayout)viewmodify.findViewById(R.id.TILD);
TILD.setTypeface(typeface);
ModuleCodeE = (EditText)viewmodify.findViewById(R.id.ModuleCode);
ModuleCodeE.setTypeface(typeface);
ModuleDescE = (EditText)viewmodify.findViewById(R.id.ModuleDesc);
ModuleDescE.setTypeface(typeface);
ModuleCodeE.setText(Items.get(position).getModule());
ModuleDescE.setText(Items.get(position).getDescription());
final String Id = Items.get(position).getModuleIds();
ModifyModule.setView(viewmodify);
ModifyModule.setIcon(R.drawable.logomini);
ModifyModule.setTitle("Construmuebles FM");
ModifyModule.setMessage(" Modifica los valores en los siguientes campos :");
ModifyModule.setPositiveButton("Actualizar", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ContentValues VUpdate = new ContentValues();
VUpdate.put(Database.CamposModuloDetails.KEY_MODULE_CODE,ModuleCodeE.getText().toString()); VUpdate.put(Database.CamposModuloDetails.KEY_MODULE_DESC,ModuleDescE.getText().toString());
long IdUpdate = dbUpdate.update(Database.MODULE_DETAILS_TABLE,VUpdate,Database.CamposModuloDetails
.KEY_MODULE_DETAILS_ID + " = ?",new String []{Id});
new UpdateCardView(context,IdUpdate).execute();
dialogInterface.dismiss();
}
});
ModifyModule.setNegativeButton("Cancelar", new DialogInterface
.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
ModifyModule.show();
return true;
case R.id.action_delete:
new DeleteCardView(context,holder,position).execute();
return true;
}
return false;
}
});
menu.show();
}
class DeleteCardView extends AsyncTask<Void,Void,Long>{
private ProgressDialog pDialog;
ModuleViewHolder holder;
int position;
public DeleteCardView(Context context,ModuleViewHolder holder,int position) {
pDialog = new ProgressDialog(context);
this.holder = holder;
this.position = position;
}
#Override
protected void onPreExecute() {
pDialog.setMessage(" Eliminado registro...");
pDialog.show();
}
#Override
protected Long doInBackground(Void... voids) {
String ModuleIdCardView = holder.ModuleIds;
Connection connection = new Connection(context, Connection.DATABASE_NAME, null,
Connection.DATABASE_VERSION);
long i = connection.DeleteByIdCardView(ModuleIdCardView);
if (i != 0) {
return i;
} else {
return i;
}
}
#Override
protected void onPostExecute(Long Result) {
if (pDialog.isShowing()){
pDialog.dismiss();
Items.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,Items.size());
if (Items.size()==0){ /**viewPager.setCurrentItem(0);**/ }
}
}
}
}

Rearrange your code as follows
recyclerView = (RecyclerView) findViewById(R.id.RVODetails);
mAdapter = new ModuleAdapter(result);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
}

Related

Android E/RecyclerView: No adapter attached; skipping layout

When I run the app, nothing is visible. Please help me
There seems to be no problem, but I have been wondering about this for a few days.
The debugger shows this warning message:
Android E/RecyclerView: No adapter attached; skipping layout
I don't know what the hell is wrong.
Here is my MainActivity code
private void setUrl(final String dateUrl)
{
myRecyclerView.setAlpha(0.5f);
loadingPanel.setVisibility(View.VISIBLE);
noteTextView.setVisibility(View.GONE);
new Thread(new Runnable() {
#Override
public void run() {
url = "http://data.nba.net/10s/prod/v1/" + dateUrl + "/scoreboard.json";
final RequestQueue requestQueue = Volley.newRequestQueue(NbaApp.getCurrentActivity());
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
jsonObject = response;
gameCardsCreater = new GameCardsCreater(jsonObject);
if (gameCardsCreater.isGameNight()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
gameCardsCreater.populateCards();
setCardsCreater();
myRecyclerView.setEnabled(true);
myRecyclerView.setVisibility(View.VISIBLE);
loadingPanel.setVisibility(View.GONE);
myRecyclerView.setAlpha(1);
runLayoutAnimation(myRecyclerView);
}
});
} else {
myRecyclerView.setEnabled(false);
myRecyclerView.setVisibility(View.GONE);
noteTextView.setVisibility(View.VISIBLE);
noteTextView.setText(R.string.no_games_tonight);
loadingPanel.setVisibility(View.GONE);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
myRecyclerView.setEnabled(false);
myRecyclerView.setVisibility(View.GONE);
noteTextView.setVisibility(View.VISIBLE);
noteTextView.setText(R.string.error_getting_info);
loadingPanel.setVisibility(View.GONE);
}
});
requestQueue.add(objectRequest);
}
}).start();
}
#SuppressLint("ClickableViewAccessibility")
public void setCardsCreater() {
gameArrayList = new ArrayList<>();
gameArrayList = gameCardsCreater.getGameArrayList();
GameAdapter adapter = new GameAdapter(gameArrayList, new CustomItemClickListener() {
#Override
public void onItemClick(View v, int position) {
if (isNetworkConnected()) {
Intent myIntent = new Intent(MainActivity.this, GameActivity.class);
Bundle extras = new Bundle();
extras.putString("gameDate", gameArrayList.get(position).getGameDate());
extras.putString("gameId", gameArrayList.get(position).getGameId());
extras.putString("homeTeamWins", gameArrayList.get(position).getHomeTeamWins());
extras.putString("awayTeamWins", gameArrayList.get(position).getAwayTeamWins());
extras.putBoolean("isGameActivated", gameArrayList.get(position).isGameActive());
extras.putString("homeTeamName", gameArrayList.get(position).getHomeTeamName());
extras.putString("awayTeamName", gameArrayList.get(position).getAwayTeamName());
extras.putBoolean("isGameOver", gameArrayList.get(position).isGameOver());
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
myIntent.putExtras(extras);
MainActivity.this.startActivity(myIntent);
} else {
Toast.makeText(NbaApp.getCurrentActivity(), "Check your internet connection", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onItemLongClick(View v, int position) {
}
});
myRecyclerView.setHasFixedSize(true);
myRecyclerView.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
myRecyclerView.setLayoutManager(llm);
}
2.Here is my RecyclerView adapter code, GameAdapter
public class GameAdapter extends RecyclerView.Adapter<GameAdapter.MyViewHolder> {
private final CustomItemClickListener listener;
private ArrayList<Game> gameList;
public GameAdapter(ArrayList<Game> myValues, CustomItemClickListener listener) {
this.gameList = myValues;
this.listener = listener;
}
static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView homeTeamNameTextView;
private TextView awayTeamNameTextView;
private ImageView awayTeamLogoImageView;
private ImageView homeTeamLogoImageView;
private TextView awayTeamScoreTextView;
private TextView homeTeamScoreTextView;
private TextView awayTeamWinsTextView;
private TextView homeTeamWinsTextView;
private TextView nuggetTextView;
private TextView gameTimeTextView;
MyViewHolder(View itemView) {
super(itemView);
awayTeamNameTextView = itemView.findViewById(R.id.awayteamname);
homeTeamNameTextView = itemView.findViewById(R.id.hometeamname);
awayTeamLogoImageView = itemView.findViewById(R.id.awayteamlogo);
homeTeamLogoImageView = itemView.findViewById(R.id.hometeamlogo);
awayTeamScoreTextView = itemView.findViewById(R.id.awayteamscore);
homeTeamScoreTextView = itemView.findViewById(R.id.hometeamscore);
awayTeamWinsTextView = itemView.findViewById(R.id.awayteamwins);
homeTeamWinsTextView = itemView.findViewById(R.id.hometeamwins);
nuggetTextView = itemView.findViewById(R.id.nuggettext);
gameTimeTextView = itemView.findViewById(R.id.gameTime);
}
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View listItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_game, parent, false);
final MyViewHolder myViewHolder = new MyViewHolder(listItem);
listItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(v, myViewHolder.getAdapterPosition());
}
});
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Game game = gameList.get(position);
holder.homeTeamNameTextView.setText(game.getHomeTeamName());
holder.awayTeamNameTextView.setText(game.getAwayTeamName());
Picasso.get().load(game.getAwayTeamImage()).into(holder.awayTeamLogoImageView);
Picasso.get().load(game.getHomeTeamImage()).into(holder.homeTeamLogoImageView);
holder.awayTeamScoreTextView.setText(game.getAwayTeamScore());
holder.homeTeamScoreTextView.setText(game.getHomeTeamScore());
holder.awayTeamWinsTextView.setText(game.getAwayTeamWins());
holder.homeTeamWinsTextView.setText(game.getHomeTeamWins());
if (game.getNugget().isEmpty())
holder.nuggetTextView.setVisibility(View.GONE);
else
holder.nuggetTextView.setText(game.getNugget());
holder.gameTimeTextView.setText(game.getGameTime());
if (game.isGameActive())
holder.gameTimeTextView.setTextColor(Color.parseColor("#ff0000"));
else
holder.gameTimeTextView.setTextColor(Color.parseColor("#B4B4B4"));
if (!game.getHomeTeamScore().isEmpty() && !game.getAwayTeamScore().isEmpty()) {
if (Integer.parseInt(game.getHomeTeamScore()) > Integer.parseInt(game.getAwayTeamScore())) {
holder.homeTeamScoreTextView.setTextColor(Color.parseColor("#ffffff"));
holder.awayTeamScoreTextView.setTextColor(Color.parseColor("#B4B4B4"));
} else if (Integer.parseInt(game.getHomeTeamScore()) < Integer.parseInt(game.getAwayTeamScore())) {
holder.homeTeamScoreTextView.setTextColor(Color.parseColor("#B4B4B4"));
holder.awayTeamScoreTextView.setTextColor(Color.parseColor("#ffffff"));
} else {
holder.homeTeamScoreTextView.setTextColor(Color.parseColor("#B4B4B4"));
holder.awayTeamScoreTextView.setTextColor(Color.parseColor("#B4B4B4"));
}
}
}
#Override
public int getItemCount() {
return gameList.size();
}
}

get context after returning from adapter to fragment

I am using contextual action bar in my fragment("UnitsFragment.java") to delete and edit items of recyclerview. But when I come back from recyclerview adapter class("UnitsRv.java"). The context seems to be null. I tried returning context from adapter and it worked for function "prepareSelection". However for "onActionItemClicked" under ActionMode.callback, I need to get context so that I can use alertdialog for editing the items.
The "requireContext()" throws this error: Fragment UnitsFragment{e3a36c8 (b4957397-055a-4b1c-8af2-fee89a3e9b35)} not attached to a context.
Here are my codes.
UnitsFragment.java
public class UnitsFragment extends Fragment {
private static final String TAG = "UnitsFragment";
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<UnitsList> unitsLists = new ArrayList<>();
Activity mcontext = getActivity();
Context dcontext;
ActionMode actionMode;
public static ArrayList<UnitsList> selectionList = new ArrayList<>();
public static boolean isInActionMode = false;
List<String> list = DatabaseClient.getInstance(getContext())
.getUserDatabase()
.getUnitDao().findUnitNameList();
public UnitsFragment() {
}
private ActionMode.Callback actionModeCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.menu_item_action, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_edit:
if (selectionList.size() == 1) {
final EditText editText = new EditText(requireContext());
new AlertDialog.Builder(requireContext())
.setTitle("Rename unit name").setView(editText)
.setPositiveButton("Rename", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
UnitsList unitsList = selectionList.get(0);
unitsList.setUnit_name(editText.getText().toString().trim());
isInActionMode = false;
((UnitsRv) mAdapter).changeDataItem(getCheckedLastPosition(), unitsList);
actionMode.finish();
selectionList.clear();
}
})
.create()
.show();
Toast.makeText(getContext(), "Edit", Toast.LENGTH_SHORT).show();
mode.finish();
return true;
}
case R.id.menu_item_delete:
isInActionMode = false;
((UnitsRv) mAdapter).removeData(selectionList);
Toast.makeText(getContext(), "Delete", Toast.LENGTH_SHORT).show();
actionMode.finish();
selectionList.clear();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
actionMode = null;
}
};
private int getCheckedLastPosition() {
ArrayList<UnitsList> dataSet = UnitsRv.getDataSet();
for (int i = 0; i < dataSet.size(); i++) {
if (dataSet.get(i).equals(selectionList.get(0))) {
return i;
}
}
return 0;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_units, container, false);
setHasOptionsMenu(true);
dcontext = rootView.getContext();
Log.d(TAG, "onCreateView1: " + dcontext);
recyclerView = rootView.findViewById(R.id.rv_units);
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
DividerItemDecoration.HORIZONTAL));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
DividerItemDecoration.VERTICAL));
layoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(layoutManager);
for (String string : list) {
unitsLists.add(new UnitsList(string));
}
Log.d(TAG, "onCreateView: " + getContext());
mAdapter = new UnitsRv(mcontext,unitsLists);
recyclerView.setAdapter(mAdapter);
return rootView;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.add, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_new:
final View customLayout = getLayoutInflater().inflate(R.layout.add_unit_dialog, null);
final EditText edt_unit_name = customLayout.findViewById(R.id.edt_new_unit_name);
final AlertDialog dialog = new AlertDialog.Builder(getContext())
.setView(customLayout)
.setTitle("Unit name")
.setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick
.setNegativeButton(android.R.string.cancel, null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Button ok_btn = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
Button cancel_btn = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
ok_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String unit_name = edt_unit_name.getText().toString().trim();
if (!TextUtils.isEmpty(unit_name)) {
String old_unit_name = DatabaseClient.getInstance(getContext())
.getUserDatabase()
.getUnitDao()
.findByUnitName(unit_name);
if (old_unit_name == null) {
DatabaseClient.getInstance(getContext())
.getUserDatabase()
.getUnitDao()
.insertUnits(new UnitsList(unit_name));
unitsLists.add(new UnitsList(unit_name));
dialog.dismiss();
} else {
edt_unit_name.setError("Unit already exists");
}
} else {
edt_unit_name.setError("Can't be empty");
}
}
});
cancel_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
}
});
dialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
public void prepareSelection(Context context,int position) {
if(actionMode == null) {
isInActionMode = true;
for (String string : list) {
unitsLists.add(new UnitsList(string));
}
mAdapter = new UnitsRv(context, unitsLists);
Log.d(TAG, "prepareSelection: " + mAdapter);
Log.d(TAG, "prepareSelection1: " + dcontext);
mcontext = (Activity)context;
actionMode = mcontext.startActionMode(actionModeCallback);
mAdapter.notifyDataSetChanged();
if (!selectionList.contains(unitsLists.get(position))) {
selectionList.add(unitsLists.get(position));
}
updateViewCounter();
}
}
private void updateViewCounter() {
int counter = selectionList.size();
if (counter == 1) {
actionMode.setTitle(counter + "item selected");
} else {
actionMode.setTitle(counter + "items selected");
}
}
}
This is my Adapter class.
UnitsRv.java
public class UnitsRv extends RecyclerView.Adapter<UnitsRv.ViewHolder> {
private static final String TAG = "UnitsRv";
private static ArrayList<UnitsList> munitsLists = new ArrayList<>();
UnitsFragment unitsFragment = new UnitsFragment();
Context mcontext;
public UnitsRv(Context context,ArrayList<UnitsList> unitsLists) {
mcontext = context;
munitsLists = unitsLists;
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
TextView unit_name;
public ViewHolder(View v) {
super(v);
unit_name = v.findViewById(R.id.unit_name);
v.setOnLongClickListener(this);
}
#Override
public void onClick(View view) {
if (UnitsFragment.isInActionMode){
unitsFragment.prepareSelection(mcontext,getAdapterPosition());
notifyItemChanged(getAdapterPosition());
}
}
#Override
public boolean onLongClick(View view) {
Log.d(TAG, "onLongClick: " + getAdapterPosition());
unitsFragment.prepareSelection(view.getContext(),getAdapterPosition());
return true;
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.units_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.unit_name.setText(munitsLists.get(position).getUnit_name());
if (UnitsFragment.isInActionMode){
if (UnitsFragment.selectionList.contains(munitsLists.get(position))){
holder.itemView.setBackgroundResource(R.color.colorSelected);
}
}
}
#Override
public int getItemCount() {
return munitsLists.size();
}
public static ArrayList<UnitsList> getDataSet() {
return munitsLists;
}
public void changeDataItem(int position, UnitsList unitsList) {
munitsLists.set(position, unitsList);
notifyDataSetChanged();
}
public void removeData(ArrayList<UnitsList> list) {
for (UnitsList unitsList : list) {
munitsLists.remove(unitsList);
}
notifyDataSetChanged();
}
}
First, you should not create instance of your UnitsFragment inside your adapter.
You can use EventBus to communicate between Activities, Fragments, Adapters, etc.
Or You can do your task using interface. like below.
Create an interface like this
public interface AdapterCallback {
void prepareSelection(Context context,int position);
}
In your UnitsFragment implement the above interface. like the following
public class UnitsFragment extends Fragment implements AdapterCallback{
// your other codes
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_units, container, false);
setHasOptionsMenu(true);
// .... your other codes
Log.d(TAG, "onCreateView: " + getContext());
// modify below line like this
mAdapter = new UnitsRv(mcontext, unitsLists, this); // here you have to pass an extra parameter that will implement your callback method from adapter.
recyclerView.setAdapter(mAdapter);
return rootView;
}
// ... you other codes
#Override
public void prepareSelection(Context context,int position) {
if(actionMode == null) {
isInActionMode = true;
for (String string : list) {
unitsLists.add(new UnitsList(string));
}
mAdapter = new UnitsRv(context, unitsLists,this); // add this as parameter.
Log.d(TAG, "prepareSelection: " + mAdapter);
Log.d(TAG, "prepareSelection1: " + dcontext);
mcontext = (Activity)context;
actionMode = mcontext.startActionMode(actionModeCallback);
mAdapter.notifyDataSetChanged();
if (!selectionList.contains(unitsLists.get(position))) {
selectionList.add(unitsLists.get(position));
}
updateViewCounter();
}
}
// other codes
}
Now, inside your Adapter you need to add an extra argument in constructor of UnitsRv and call your interface method from adapter ussing mAdapterCallback.
public class UnitsRv extends RecyclerView.Adapter<UnitsRv.ViewHolder> {
private static final String TAG = "UnitsRv";
private static ArrayList<UnitsList> munitsLists = new ArrayList<>();
UnitsFragment unitsFragment = new UnitsFragment(); // remove this line
private AdapterCallback mAdapterCallback; // add this line
Context mcontext;
public UnitsRv(Context context,ArrayList<UnitsList> unitsLists, AdapterCallback callback) {
mcontext = context;
munitsLists = unitsLists;
this.mAdapterCallback = callback; // add this line
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
TextView unit_name;
public ViewHolder(View v) {
super(v);
unit_name = v.findViewById(R.id.unit_name);
v.setOnLongClickListener(this);
}
#Override
public void onClick(View view) {
if (UnitsFragment.isInActionMode){
mAdapterCallback.prepareSelection(mcontext,getAdapterPosition()); // modify this line
notifyItemChanged(getAdapterPosition());
}
}
#Override
public boolean onLongClick(View view) {
Log.d(TAG, "onLongClick: " + getAdapterPosition());
mAdapterCallback.prepareSelection(view.getContext(),getAdapterPosition()); // modify this line
return true;
}
}
// your other codes....
}
You should check for your fragment is attached or not with isAdded()
place if(!isAdded()) return in your onActionItemClicked. and replace requireContext() with getContext() because requireContext() always throws IllegalStateException if fragment is not attached.
override onAttach method to save context in your fragment.
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context= context;
}
Hope this helps.

How to implement getItemViewType() for multiple layout in RecyclerView in a Movie Database app

I am creating a movie app using TMDB api, Retrofit, Gson and Glide. I have two recyclerView and two layout to inflate. But I am unable to inflate 2 layout in recyclerView adapter.
I have already implemented popular and upcoming movie list in 2 different recyclerView. But they are showing using 1 single layout. I want to inflate popular movies in one layout and upcoming movies in another layout. I can't set the condition for getItemViewType() method. How can I check for popular and upcoming movies list in getItemViewType() method and implement it on onCreateViewHolder() method of recyclerView.
MovieAdapter class:
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
private Context context;
private ArrayList<Movie> movieArrayList;
public MovieAdapter(Context context, ArrayList<Movie> movieArrayList) {
this.context = context;
this.movieArrayList = movieArrayList;
}
#NonNull
#Override
public MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_item, parent, false);
return new MovieViewHolder(view);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
// Set values to the list item components
public void onBindViewHolder(#NonNull MovieViewHolder holder, int position) {
holder.movieTitle.setText(movieArrayList.get(position).getOriginalTitle());
holder.rating.setText(String.valueOf(movieArrayList.get(position).getVoteAverage()));
String imagePath = "https://image.tmdb.org/t/p/w500" + movieArrayList.get(position).getPosterPath();
Glide.with(context)
.load(imagePath)
.placeholder(R.drawable.loading)
.into(holder.movieImage);
}
#Override
public int getItemCount() {
return movieArrayList == null ? 0 : movieArrayList.size();
}
public class MovieViewHolder extends RecyclerView.ViewHolder {
TextView movieTitle, rating;
ImageView movieImage;
public MovieViewHolder(#NonNull View itemView) {
super(itemView);
movieImage = itemView.findViewById(R.id.ivMovieImage);
movieTitle = itemView.findViewById(R.id.tvTitle);
rating = itemView.findViewById(R.id.tvRating);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Movie selectedMovie = movieArrayList.get(position);
Intent intent = new Intent(context, MovieActivity.class);
intent.putExtra("movie", selectedMovie);
context.startActivity(intent);
}
}
});
}
}
}
MainActivity class:
public class MainActivity extends AppCompatActivity {
private ArrayList<Movie> popularMovie, topRatedMovie;
private RecyclerView recyclerViewPopular, recyclerViewUpcoming;
private MovieAdapter movieAdapter, upcomingAdapter;
private SwipeRefreshLayout swipeRefreshLayout;
private static ViewPager mPager;
private static int currentPage = 0;
private static int NUM_PAGES = 0;
String[] urls = new String[] {
"https://image.tmdb.org/t/p/w500/udDclJoHjfjb8Ekgsd4FDteOkCU.jpg",
"https://image.tmdb.org/t/p/w500//2bXbqYdUdNVa8VIWXVfclP2ICtT.jpg",
"https://image.tmdb.org/t/p/w500//zfE0R94v1E8cuKAerbskfD3VfUt.jpg",
"https://image.tmdb.org/t/p/w500//lcq8dVxeeOqHvvgcte707K0KVx5.jpg",
"https://image.tmdb.org/t/p/w500//w9kR8qbmQ01HwnvK4alvnQ2ca0L.jpg"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initSlider();
getPopularMovies();
getUpcomingMovies();
swipeRefreshLayout = findViewById(R.id.swipe_layout);
swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimaryDark);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getPopularMovies();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
}
}, 4000);
}
});
}
public void getPopularMovies() {
MovieDataService movieDataService = RetrofitInstance.getService();
Call<MovieDBResponse> callPopular = movieDataService.getPopularMovies(this.getString(R.string.apiKey));
callPopular.enqueue(new Callback<MovieDBResponse>() {
#Override
public void onResponse(Call<MovieDBResponse> call, Response<MovieDBResponse> response) {
MovieDBResponse movieDBResponse = response.body();
if(movieDBResponse!=null && movieDBResponse.getMovies()!=null) {
popularMovie = (ArrayList<Movie>) movieDBResponse.getMovies();
showOnRecyclerView();
}
}
#Override
public void onFailure(Call<MovieDBResponse> call, Throwable t) { }
});
}
public void getUpcomingMovies() {
MovieDataService movieDataService = RetrofitInstance.getService();
Call<MovieDBResponse> callUpcoming = movieDataService.getUpcomingMovies(this.getString(R.string.apiKey));
callUpcoming.enqueue(new Callback<MovieDBResponse>() {
#Override
public void onResponse(Call<MovieDBResponse> call, Response<MovieDBResponse> response) {
MovieDBResponse movieDBResponse = response.body();
if(movieDBResponse!=null && movieDBResponse.getMovies()!=null) {
topRatedMovie = (ArrayList<Movie>) movieDBResponse.getMovies();
showOnRecyclerView();
}
}
#Override
public void onFailure(Call<MovieDBResponse> call, Throwable t) { }
});
}
private void showOnRecyclerView() {
recyclerViewPopular = findViewById(R.id.rvMovies);
recyclerViewUpcoming = findViewById(R.id.rvTopMovies);
RecyclerView.LayoutManager popularLayoutManager = new LinearLayoutManager(this);
RecyclerView.LayoutManager upcomingLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerViewUpcoming.setLayoutManager(upcomingLayoutManager);
recyclerViewPopular.setLayoutManager(popularLayoutManager);
movieAdapter = new MovieAdapter(this, popularMovie);
upcomingAdapter = new MovieAdapter(this, topRatedMovie);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerViewPopular.setLayoutManager(new GridLayoutManager(this, 2));
}else {
recyclerViewPopular.setLayoutManager(new GridLayoutManager(this, 4));
}
recyclerViewPopular.setItemAnimator(new DefaultItemAnimator());
recyclerViewUpcoming.setItemAnimator(new DefaultItemAnimator());
recyclerViewPopular.setAdapter(movieAdapter);
recyclerViewUpcoming.setAdapter(upcomingAdapter);
movieAdapter.notifyDataSetChanged();
upcomingAdapter.notifyDataSetChanged();
}
}
I want to inflate 2 different layout "movie_list_item.xml" and "upcoming_movie_list_item.xml" in onCreateViewHolder() method.
With in your adapter class(MovieAdapter) create a new constructor and add extra params of Int or enum whatever simple for you i am just giving you simple example:-
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
private Context context;
private ArrayList<Movie> movieArrayList;
private int viewType;
public MovieAdapter(Context context, ArrayList < Movie > movieArrayList, int viewType) {
this.context = context;
this.movieArrayList = movieArrayList;
this.viewType=viewType;
}
#NonNull
#Override
public MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
if (viewType == 1) {
//Popular movie layout
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_item, parent, false);
} else {
//upcoming movie layout
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_item, parent, false);
}
return new MovieViewHolder(view);
}
#Override
public int getItemViewType(int position) {
if (viewType == 1)
return 1; //Popular Movie Layout
else
return 2; //Upcoming Movie Layout
// return super.getItemViewType(position);
}
#Override
// Set values to the list item components
public void onBindViewHolder(#NonNull MovieViewHolder holder, int position) {
holder.movieTitle.setText(movieArrayList.get(position).getOriginalTitle());
holder.rating.setText(String.valueOf(movieArrayList.get(position).getVoteAverage()));
String imagePath = "https://image.tmdb.org/t/p/w500" + movieArrayList.get(position).getPosterPath();
Glide.with(context)
.load(imagePath)
.placeholder(R.drawable.loading)
.into(holder.movieImage);
}
#Override
public int getItemCount() {
return movieArrayList == null ? 0 : movieArrayList.size();
}
public class MovieViewHolder extends RecyclerView.ViewHolder {
TextView movieTitle, rating;
ImageView movieImage;
public MovieViewHolder(#NonNull View itemView) {
super(itemView);
movieImage = itemView.findViewById(R.id.ivMovieImage);
movieTitle = itemView.findViewById(R.id.tvTitle);
rating = itemView.findViewById(R.id.tvRating);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Movie selectedMovie = movieArrayList.get(position);
Intent intent = new Intent(context, MovieActivity.class);
intent.putExtra("movie", selectedMovie);
context.startActivity(intent);
}
}
});
}
}
and within your activity change on this method only
private void showOnRecyclerView() {
recyclerViewPopular = findViewById(R.id.rvMovies);
recyclerViewUpcoming = findViewById(R.id.rvTopMovies);
RecyclerView.LayoutManager popularLayoutManager = new LinearLayoutManager(this);
RecyclerView.LayoutManager upcomingLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerViewUpcoming.setLayoutManager(upcomingLayoutManager);
recyclerViewPopular.setLayoutManager(popularLayoutManager);
movieAdapter = new MovieAdapter(this, popularMovie,1);
upcomingAdapter = new MovieAdapter(this, topRatedMovie,2);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerViewPopular.setLayoutManager(new GridLayoutManager(this, 2));
} else {
recyclerViewPopular.setLayoutManager(new GridLayoutManager(this, 4));
}
recyclerViewPopular.setItemAnimator(new DefaultItemAnimator());
recyclerViewUpcoming.setItemAnimator(new DefaultItemAnimator());
recyclerViewPopular.setAdapter(movieAdapter);
recyclerViewUpcoming.setAdapter(upcomingAdapter);
movieAdapter.notifyDataSetChanged();
upcomingAdapter.notifyDataSetChanged();
}
Create layout for movie_empty_item
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
private Context context;
private ArrayList<Movie> movieArrayList;
//add this two line
private static final int EMPTY_VIEW_TYPE = 0;
private static final int NORMAL_VIEW_TYPE = 1;
public MovieAdapter(Context context, ArrayList<Movie> movieArrayList) {
this.context = context;
this.movieArrayList = movieArrayList;
}
#NonNull
#Override
public MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//return viewholder replace like this
if(viewType == NORMAL_VIEW_TYPE) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_item, parent, false);
return new MovieViewHolder(view);
}else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_empty_item, parent, false);
return new EmptyViewHolder(view);
};
}
//getItemViewType return replace like this
#Override
public int getItemViewType(int position) {
return movieArrayList.size()>0?NORMAL_VIEW_TYPE:EMPTY_VIEW_TYPE;
}
#Override
// Set values to the list item components
public void onBindViewHolder(#NonNull MovieViewHolder holder, int position) {
holder.movieTitle.setText(movieArrayList.get(position).getOriginalTitle());
holder.rating.setText(String.valueOf(movieArrayList.get(position).getVoteAverage()));
String imagePath = "https://image.tmdb.org/t/p/w500" + movieArrayList.get(position).getPosterPath();
Glide.with(context)
.load(imagePath)
.placeholder(R.drawable.loading)
.into(holder.movieImage);
}
#Override
public int getItemCount() {
return movieArrayList.size() ? movieArrayList.size():1 ;
}
public class MovieViewHolder extends RecyclerView.ViewHolder {
TextView movieTitle, rating;
ImageView movieImage;
public MovieViewHolder(#NonNull View itemView) {
super(itemView);
movieImage = itemView.findViewById(R.id.ivMovieImage);
movieTitle = itemView.findViewById(R.id.tvTitle);
rating = itemView.findViewById(R.id.tvRating);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Movie selectedMovie = movieArrayList.get(position);
Intent intent = new Intent(context, MovieActivity.class);
intent.putExtra("movie", selectedMovie);
context.startActivity(intent);
}
}
});
}
}
public class EmptyViewHolder extends RecyclerView.ViewHolder {
public EmptyViewHolder(#NonNull View itemView) {
super(itemView);
}
}
}

Error in recyclerView

Can anyone check if there are errors in it. here my code, If there is any error in the code please tell me? I don't know how to fix the code Search.java.
in my RecyclerItemClickListener.java
public interface RecyclerItemClickListener {
void onItemClick(int position);
}
My Adapter HierAdapter.java
public class HireAdapter extends RecyclerView.Adapter<HireAdapter.ViewHolder>{
private ArrayList<HireItem> TeacherItemList;
private Context context;
private RecyclerItemClickListener itemClickListener;
public HireAdapter(Context c, ArrayList<HireItem> teacherItemList, RecyclerItemClickListener listener) {
TeacherItemList = teacherItemList;
context = c;
itemClickListener = listener;
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public final TextView nameText, subjectText,levelText ,cityText;
public ViewHolder(View itemView) {
super(itemView);
nameText = (TextView)itemView.findViewById(R.id.result_name);
subjectText = (TextView)itemView.findViewById(R.id.result_subject);
levelText = (TextView)itemView.findViewById(R.id.result_level);
cityText = (TextView)itemView.findViewById(R.id.result_city);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_teachers,parent,false);
final ViewHolder viewHolder = new ViewHolder(rowView);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickListener.onItemClick(viewHolder.getLayoutPosition());
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.nameText.setText(TeacherItemList.get(position).getResult_name());
holder.subjectText.setText(TeacherItemList.get(position).getResult_subject());
holder.levelText.setText(TeacherItemList.get(position).getResult_level());
holder.cityText.setText(TeacherItemList.get(position).getResult_city());
//Here it is simply write onItemClick listener here
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, ProfileTeaAdapter.class);
context.startActivity(intent);
}
});
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemCount() {
return TeacherItemList.size();
}}
Here Search.java, I wrote notes at each error. Because I did not know how to correct some codes to work with HireAdapter and RecyclerItemClickListener, can anyone solve the error?
public class Search extends Fragment implements RecyclerItemClickListener {
private Context context;
private RecyclerView recyclerView;
private DatabaseReference databaseReference;
private FirebaseAuth firebaseAuth;
private List<HireItem> hireItem = new ArrayList<>();
HireAdapter mAdapter;
ImageView bt_search;
ProgressDialog progressDialog;
Spinner spinner_sort;
String key = "req_skill1";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_search,container,false);
//Getting FireBase Instance
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference("teachers");
//Getting id of Views
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rv_places);
recyclerView.setAdapter(mAdapter);
//
bt_search = (ImageView)view.findViewById(R.id.bt_search);
spinner_sort = (Spinner)view.findViewById(R.id.spinner_sort);
setupSpinner();
List<HireItem> hireItem = new ArrayList<>();
mAdapter = new HireAdapter(getContext(),R.layout.list_item_teachers,hireItem); // error at (getContext(),R.layout.list_item_teachers,hireItem)
bt_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mAdapter != null){
mAdapter.clear(); // error at .clear();
}
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Searching Teachers");
progressDialog.show();
FirebaseDatabase.getInstance().getReference("teachers").orderByChild("subject").startAt(key).endAt(key + "~")
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Teachers child = dataSnapshot.getValue(Teachers.class);
HireItem hireItem = new HireItem(child.teaname, child.city, child.subject, child.level, child.sex,child.mobile, child.qualification, child.skill1, child.experince, child.salary,child.age);
mAdapter.add(hireItem); // error at .add
progressDialog.dismiss();
if(mAdapter == null){
Toast.makeText(getContext(), "No Match Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(mAdapter == null){
Toast.makeText(getContext(), "No Match Found", Toast.LENGTH_SHORT).show();
}
else{
recyclerView.setAdapter(mAdapter); // error at recyclerView
}
}
});
return view;
}
private void setupSpinner(){
ArrayAdapter adapter = ArrayAdapter.createFromResource(getContext(),R.array.array_teacher_sort,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner_sort.setAdapter(adapter);
spinner_sort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
key = (String)adapterView.getItemAtPosition(i);
if(key.equals(getString(R.string.sort_A))){
key = "Math";
}else if(key.equals(getString(R.string.sort_AA))){
key = "computer";
}
else if(key.equals(getString(R.string.sort_AB))){
key = "Biology";
}
else if(key.equals(getString(R.string.sort_AD))){
key = "Physics";
}
else if(key.equals(getString(R.string.sort_AXX))){
key = "Holy Quran";
}
else if(key.equals(getString(R.string.sort_AZ))){
key = "Chysics";
}
else if(key.equals(getString(R.string.sort_AS))){
key = "English";
}
else if(key.equals(getString(R.string.sort_AQ))){
key = "Arabic";
}
else if(key.equals(getString(R.string.sort_ADD))){
key = "Science";
}
else if(key.equals(getString(R.string.sort_AE))){
key = "History";
}
else if(key.equals(getString(R.string.sort_AW))){
key = "Geograpghy";
}
else if(key.equals(getString(R.string.sort_AR))){
key = "Art education";
}
else if(key.equals(getString(R.string.sort_AT))){
key = "Family education";
}
else if(key.equals(getString(R.string.sort_aae))){
key = "Religion";
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onResume() {
super.onResume();
mAdapter.clear(); // error at .clear();
}
#Override
public void onItemClick(int position) {
} }
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_teachers,parent,false);
final ViewHolder viewHolder = new ViewHolder(rowView);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickListener.onItemClick(viewHolder.getLayoutPosition());
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.nameText.setText(TeacherItemList.get(position).getResult_name());
holder.subjectText.setText(TeacherItemList.get(position).getResult_subject());
holder.levelText.setText(TeacherItemList.get(position).getResult_level());
holder.cityText.setText(TeacherItemList.get(position).getResult_city());
//Here it is simply write onItemClick listener here
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, ProfileTeaAdapter.class);
context.startActivity(intent);
}
});
}
Here you are setting onClickListner on the same view twice. The Listener set in the onBindViewHolder will override the Listner set in the onCreateViewHolder method.

List view is not displaying content

I have a simple task that is to take string input from Dialog then add it to listview with checkbox .
What happening is that , I entered test through dialog but it is not displaying after adding and also code doesn't have any error during runtime .
MainActivity.java
public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
ListView list;
MyCustomAdapter dataAdapter ;
List<SubTasksModel> subTasksModelArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.heading);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInputDialog();
}
});
subTasksModelArrayList = new ArrayList<SubTasksModel>();
list = (ListView) findViewById(R.id.list);
dataAdapter = new MyCustomAdapter(this , R.layout.child_row_add_subtask , subTasksModelArrayList);
list.setAdapter(dataAdapter);
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.add_subtask_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.et_task);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Add Subtask", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
/*subTasksModelArrayList = new ArrayList<SubTasksModel>();*/
fillData(editText.getText().toString() , false);
Utility.setListViewHeightBasedOnChildren(list);
}
})
.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void fillData(String s, boolean b) {
final SubTasksModel model = new SubTasksModel();
model.setTask(s);
model.setSelected(b);
subTasksModelArrayList.add(model);
}
}
MyCustomAdapter.java
public class MyCustomAdapter extends BaseAdapter {
public List<SubTasksModel> subTasksModelList;
Context context;
private LayoutInflater mInflater;
public MyCustomAdapter(Context context, int resource, List<SubTasksModel> objects) {
this.context=context;
this.subTasksModelList=objects;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
static class ViewHolder {
LinearLayout linearLayout;
TextView task;
CheckBox cb;
}
#Override
public int getCount() {
return 0;
}
#Override
public SubTasksModel getItem(int position) {
return subTasksModelList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder ;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.child_row_add_subtask, null);
holder.task = (TextView) convertView.findViewById(R.id.tv_subtask);
holder.cb = (CheckBox) convertView.findViewById(R.id.cb_subtask);
holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayout01);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
final int pos = position;
holder.task.setText(subTasksModelList.get(position).getTask());
holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
subTasksModelList.get(pos).setSelected(isChecked);
}
});
/*Log.d("ArrayList"," : "+ subTasksModelList);
SubTasksModel subTasksModel = subTasksModelList.get(position);
holder.task.setText(subTasksModel.getTask());
holder.cb.setChecked(subTasksModel.isSelected());
holder.cb.setTag(subTasksModel);*/
return convertView;
}
}
SubTaskModel.java
public class SubTasksModel {
String task = "";
boolean selected = false;
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
// Utility class is just to set height of listview inside scrollview.
public class Utility {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
Log.d("Params are : " , " : "+ params);
listView.requestLayout();
}
}
#Override
public int getCount() {
return 0;
}
replace it with
#Override
public int getCount() {
return subTasksModelList.size();
}

Categories

Resources