I am trying to send the user to another activity when he clicks on the picture inside the recycle view after gathering the position, the problem whatever I do i still gitting null on the Adapter when using context, please find the codes below and describe to me what is the thing that I missed ?!
the problem is in the codes of onclick method ( last one ):-
package com.example.boc.Teachers;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.boc.R;
import com.example.boc.main.DashboardActivity;
import java.util.ArrayList;
public class TeachersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private LayoutInflater mInflater;
private ArrayList<TeachersModel> items;
private TeacherMain mActivity;
private Context context;
public TeachersAdapter(ArrayList<TeachersModel> data, TeacherMain activity) {
this.items = data;
this.mActivity = activity;
this.mInflater = LayoutInflater.from(mActivity);
}
public void addItem(TeachersModel result) {
items.add(result);
}
public TeachersAdapter(Context context) {
this.context = context;
}
public void setInflater(LayoutInflater layoutInflater){
this.mInflater =layoutInflater;
}
public void replaceItems(ArrayList<TeachersModel> newItems) {
this.items.clear();
for(TeachersModel item: newItems)
this.items.add(item);
}
public void insertItem(TeachersModel item) {
items.add(0, item);
}
public void clearItems(){
items.clear();
}
public void AddResults(ArrayList<TeachersModel> result) {
items.addAll(result);
}
public TeachersModel getItemsAt(int position){
return items.get(position);
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
TeachersModel model = items.get(position);
MessageViewHolder messageViewHolder = (MessageViewHolder) holder;
messageViewHolder.imageViewIcon.setBackgroundResource(model.getImage());
messageViewHolder.textViewName.setText(model.getName());
messageViewHolder.textViewStatus.setText(model.getStatus());
messageViewHolder.textViewMobile.setText(model.getMobile());
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootCategoryView = mInflater.inflate(R.layout.row_item_teachers, parent, false);
return new MessageViewHolder(rootCategoryView, this);
}
private class MessageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imageViewIcon;
private TextView textViewName;
private TextView textViewStatus;
private TextView textViewMobile;
private CardView cardView;
private MessageViewHolder(View itemView, TeachersAdapter adapter) {
super(itemView);
imageViewIcon = (ImageView) itemView.findViewById(R.id.imageViewIcon);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
textViewStatus = (TextView) itemView.findViewById(R.id.textViewStatus);
textViewMobile = (TextView) itemView.findViewById(R.id.textViewMobile);
cardView = (CardView) itemView.findViewById(R.id.cardView);
cardView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final int pos = getAdapterPosition();
if (pos == 0) {
imageViewIcon.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent( context, DashboardActivity.class );
context.startActivity( intent );
}
} );
Toast.makeText(mActivity, "Selected Item Position "+pos, Toast.LENGTH_SHORT).show();
}
}
}
}
I am assuming you are using the constrcutor without passing a context:
//update the constructor to take a context
public TeachersAdapter(ArrayList<TeachersModel> data, TeacherMain activity , Context context) {
this.items = data;
this.mActivity = activity;
this.mInflater = LayoutInflater.from(mActivity);
//add this
this.context = context;
}
Set the click listener in onBindViewHolder:
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
....
....
....
messageViewHolder.imageViewIcon.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, DashboardActivity.class );
context.startActivity(intent);
}
});
}
When you create the adapter in your activity, make sure to pass the correct context:
adapter = new TeachersAdapter(... , .... , getApplicationContext());
Related
Been working on this code for a while and as im new to recyclerList I can't seem to figure out why the button works only once.
Here is the adapter:
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class AdaptadorLista extends RecyclerView.Adapter<AdaptadorLista.ViewHolderLista> {
ArrayList<ComponentesLista> listaComponentes;
public AdaptadorLista(ArrayList<ComponentesLista> listaComponentes) {
this.listaComponentes = listaComponentes;
}
#NonNull
#Override
public ViewHolderLista onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_lista, parent, false);
return new ViewHolderLista(view);
}
#Override
public void onBindViewHolder(ViewHolderLista holder, int position) {
holder.textViewDescripcion.setText(String.valueOf(listaComponentes.get(position).getDescripcion()));
holder.textViewDinero.setText(String.valueOf(listaComponentes.get(position).getDinero()));
holder.textViewCantidad.setText(String.valueOf(listaComponentes.get(position).getCantidad()));
}
#Override
public int getItemCount() {
return listaComponentes.size();
}
public class ViewHolderLista extends RecyclerView.ViewHolder {
private TextView textViewCantidad, textViewDescripcion, textViewDinero;
public ViewHolderLista(#NonNull View itemView) {
super(itemView);
textViewCantidad= (TextView) itemView.findViewById(R.id.textMuestraCantidad);
textViewDescripcion = (TextView) itemView.findViewById(R.id.textMuestraDescripcion);
textViewDinero = (TextView) itemView.findViewById(R.id.textMuestraPrecio);
}
}
}
Here is the object it works with:
public class ComponentesLista {
private String descripcion;
private String cantidad;
private String dinero;
public ComponentesLista() {
}
public ComponentesLista(String descripcion, String cantidad, String dinero) {
this.descripcion = descripcion;
this.cantidad = cantidad;
this.dinero = dinero;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getCantidad() {
return cantidad;
}
public void setCantidad(String cantidad) {
this.cantidad = cantidad;
}
public String getDinero() {
return dinero;
}
public void setDinero(String dinero) {
this.dinero = dinero;
}
}
And here is the main method (It's not the main method, it's another screen I use after a button press but it shouldn't be the issue right?)
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class PantallaLista extends AppCompatActivity {
ArrayList<ComponentesLista> componentesLista;
RecyclerView recyclerLista;
//int cont = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista);
// Seccion ArrayList Lista
componentesLista=new ArrayList<>();
recyclerLista= (RecyclerView) findViewById(R.id.recyclerViewLista);
recyclerLista.setLayoutManager(new LinearLayoutManager(this));
// Botones
Button nuevo = (Button) findViewById(R.id.nuevoButton);
nuevo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
llenarLista();
}
});
Button guardarVolver = (Button) findViewById(R.id.terminarButton);
guardarVolver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(PantallaLista.this, MainActivity.class);
startActivity(intent);
}
});
}
private void llenarLista () {
EditText textoGetDescripcion = (EditText) findViewById(R.id.textInputProducto);
EditText textoGetCantidad = (EditText) findViewById(R.id.textInputCantidad);
EditText textoGetPrecio = (EditText) findViewById(R.id.textInputPrecio);
componentesLista.add(new ComponentesLista(textoGetDescripcion.getText().toString(), textoGetPrecio.getText().toString(), textoGetCantidad.getText().toString()));
AdaptadorLista adapter = new AdaptadorLista(componentesLista);
recyclerLista.setAdapter(adapter);
//System.out.println(textoGetDescripcion.getText().toString() + textoGetPrecio.getText().toString() + textoGetPrecio.getText().toString());
}
}
You are setting an adapter every time you add the item to the list. Whenever you are adding a new item to the list, you've to use adapter.notifyItemInserted(position)
Here's the activiy
public class PantallaLista extends AppCompatActivity {
ArrayList<ComponentesLista> componentesLista;
RecyclerView recyclerLista;
AdaptadorLista adapter;
//int cont = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista);
// Seccion ArrayList Lista
componentesLista=new ArrayList<>();
recyclerLista= (RecyclerView) findViewById(R.id.recyclerViewLista);
recyclerLista.setLayoutManager(new LinearLayoutManager(this));
adapter = new AdaptadorLista(componentesLista);
recyclerLista.setAdapter(adapter);
// Botones
Button nuevo = (Button) findViewById(R.id.nuevoButton);
nuevo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
llenarLista();
}
});
Button guardarVolver = (Button) findViewById(R.id.terminarButton);
guardarVolver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(PantallaLista.this, MainActivity.class);
startActivity(intent);
}
});
}
private void llenarLista () {
EditText textoGetDescripcion = (EditText) findViewById(R.id.textInputProducto);
EditText textoGetCantidad = (EditText) findViewById(R.id.textInputCantidad);
EditText textoGetPrecio = (EditText) findViewById(R.id.textInputPrecio);
ComponentesLista tempData = new ComponentesLista(textoGetDescripcion.getText().toString(), textoGetPrecio.getText().toString(), textoGetCantidad.getText().toString())
adapter.addNewItems(tempData);
}
}
heres the adapter
public class AdaptadorLista extends RecyclerView.Adapter<AdaptadorLista.ViewHolderLista> {
ArrayList<ComponentesLista> listaComponentes;
public AdaptadorLista(ArrayList<ComponentesLista> listaComponentes) {
this.listaComponentes = listaComponentes;
}
public addNewItems(ComponentesLista tempComponent){
this.listaComponentes.add(tempComponent);
notifyDataSetChanged();
}
#NonNull
#Override
public ViewHolderLista onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_lista, parent, false);
return new ViewHolderLista(view);
}
#Override
public void onBindViewHolder(ViewHolderLista holder, int position) {
holder.textViewDescripcion.setText(String.valueOf(listaComponentes.get(position).getDescripcion()));
holder.textViewDinero.setText(String.valueOf(listaComponentes.get(position).getDinero()));
holder.textViewCantidad.setText(String.valueOf(listaComponentes.get(position).getCantidad()));
}
#Override
public int getItemCount() {
return listaComponentes.size();
}
public class ViewHolderLista extends RecyclerView.ViewHolder {
private TextView textViewCantidad, textViewDescripcion, textViewDinero;
public ViewHolderLista(#NonNull View itemView) {
super(itemView);
textViewCantidad= (TextView) itemView.findViewById(R.id.textMuestraCantidad);
textViewDescripcion = (TextView) itemView.findViewById(R.id.textMuestraDescripcion);
textViewDinero = (TextView) itemView.findViewById(R.id.textMuestraPrecio);
}
}
}
please tell if you are not understanding something.
I want to add onClick to recyclerView to send data back to form Activity for update data process. How can I implement onItemClickListner when this code doesn't have adapter in it?
Show_Employees.java:
package com.example.roomdatabaseandroid;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.example.roomdatabaseandroid.DataModel.EmployeeDao;
import com.example.roomdatabaseandroid.DataModel.EmployeeDatabase;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class ShowEmployees extends AppCompatActivity {
private static final int EDIT_COURSE_REQUEST = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_employees);
RecyclerView recyclerView;
FloatingActionButton fab = findViewById(R.id.idFABAdd);
EmployeeDao employeeDao;
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//starting a new activity for adding a new course and passing a constant value in it.
Intent intent = new Intent(ShowEmployees.this, MainActivity.class);
startActivity(intent);
}
});
employeeDao = EmployeeDatabase.getDBInstance(this).employeeDao();
recyclerView = findViewById(R.id.employeeRecyclerView);
EmployeeRecycler employeeRecycler = new EmployeeRecycler(employeeDao.getAllEmployee());
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(employeeRecycler);
//below method is use to add swipe to delete method for item of recycler view.
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
//on recycler view item swiped then we are deleting the item of our recycler view.
employeeDao.deleteEmployee(employeeRecycler.data.get(viewHolder.getAdapterPosition()));
Toast.makeText(ShowEmployees.this, "Employee deleted", Toast.LENGTH_SHORT).show();
}
}).attachToRecyclerView(recyclerView);
}
}
Employee_Recycler.java:
package com.example.roomdatabaseandroid;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.roomdatabaseandroid.DataModel.DataConverter;
import com.example.roomdatabaseandroid.DataModel.Employee;
import java.util.List;
public class EmployeeRecycler extends RecyclerView.Adapter<EmployeeViewHolder> {
List<Employee> data;
public EmployeeRecycler(List<Employee> employees){
data = employees;
}
#NonNull
#Override
public EmployeeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_item_1,
parent,false
);
return new EmployeeViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull EmployeeViewHolder holder, int position) {
Employee employee = data.get(position);
holder.imageView.setImageBitmap(DataConverter.convertByteArraytoImage(employee.getImage()));
holder.firstName.setText(employee.getFirstName());
holder.middleName.setText(employee.getMiddleName());
holder.lastName.setText(employee.getLastName());
holder.dob.setText(employee.getDOB());
holder.gender.setText(employee.getGender());
holder.address.setText(employee.getAddress());
holder.designation.setText(employee.getDesignation());
holder.email.setText(employee.getEmail());
holder.phoneNumber.setText(employee.getPhoneNumber());
}
#Override
public int getItemCount() {
return data.size();
}
}
EmployeeViewHolder.java:
package com.example.roomdatabaseandroid;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class EmployeeViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView firstName,middleName,lastName,email,phoneNumber,address,designation,gender,dob;
public EmployeeViewHolder(#NonNull View itemView) {
super(itemView);
firstName = itemView.findViewById(R.id.idTVFirstName);
middleName = itemView.findViewById(R.id.idTVMiddleName);
lastName = itemView.findViewById(R.id.idTVLastName);
dob = itemView.findViewById(R.id.idTVDOB);
address = itemView.findViewById(R.id.idTVAddress);
gender = itemView.findViewById(R.id.idTVGender);
designation = itemView.findViewById(R.id.idTVDesignation);
email = itemView.findViewById(R.id.idTVEmail);
phoneNumber = itemView.findViewById(R.id.idTVPhoneNumber);
imageView = itemView.findViewById(R.id.profileImageView);
}
}
add an interface
interface AdapterItemClickListener {
void onItemClickListener(Employee employee, int position)
}
your actvity must implement this interface
public class ShowEmployees extends AppCompatActivity implements AdapterItemClickListener {
private static final int EDIT_COURSE_REQUEST = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_employees);
RecyclerView recyclerView;
FloatingActionButton fab = findViewById(R.id.idFABAdd);
EmployeeDao employeeDao;
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//starting a new activity for adding a new course and passing a constant value in it.
Intent intent = new Intent(ShowEmployees.this, MainActivity.class);
startActivity(intent);
}
});
employeeDao = EmployeeDatabase.getDBInstance(this).employeeDao();
recyclerView = findViewById(R.id.employeeRecyclerView);
EmployeeRecycler employeeRecycler = new EmployeeRecycler(employeeDao.getAllEmployee(), this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(employeeRecycler);
//below method is use to add swipe to delete method for item of recycler view.
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
//on recycler view item swiped then we are deleting the item of our recycler view.
employeeDao.deleteEmployee(employeeRecycler.data.get(viewHolder.getAdapterPosition()));
Toast.makeText(ShowEmployees.this, "Employee deleted", Toast.LENGTH_SHORT).show();
}
}).attachToRecyclerView(recyclerView);
}
void onItemClickListener(Employee employee, int position) {
//update or another job
}
}
and your adapter
public class EmployeeRecycler extends RecyclerView.Adapter<EmployeeViewHolder> {
List<Employee> data;
AdapterItemClickListener itemClickListener;
public EmployeeRecycler(List<Employee> employees, AdapterItemClickListener itemClickListener){
data = employees;
this.itemClickListener = itemClickListener;
}
#NonNull
#Override
public EmployeeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_item_1,
parent,false
);
return new EmployeeViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull EmployeeViewHolder holder, int position) {
Employee employee = data.get(position);
holder.imageView.setImageBitmap(DataConverter.convertByteArraytoImage(employee.getImage()));
holder.firstName.setText(employee.getFirstName());
holder.middleName.setText(employee.getMiddleName());
holder.lastName.setText(employee.getLastName());
holder.dob.setText(employee.getDOB());
holder.gender.setText(employee.getGender());
holder.address.setText(employee.getAddress());
holder.designation.setText(employee.getDesignation());
holder.email.setText(employee.getEmail());
holder.phoneNumber.setText(employee.getPhoneNumber());
holder.itemView.setOnClickListener (v -> {
itemClickListener.onItemClickListener(employee, position);
});
}
#Override
public int getItemCount() {
return data.size();
}
}
I'm working on an SMS app which is almost completed but I'm having problem updating the Recyclerview with new SMS, The new SMS isn't showing on list until I close and open my app
I've tried many solutions but I'm not able to make it work, Please Help
Thanks In Advance
My ConverstaionDetailsItemAdapter.java class where I'm extending Recyvlerview.Adapter
public class ConverstaionDetailsItemAdapter extends
RecyclerView.Adapter<ConversationDetailsItemViewHolder> {
Conversation conversation;
List<Message> messages;
Context mContext;
public List<Message> getMessages() {
return messages;
}
public void setMessages(List<Message> messages) {
this.messages = messages;
}
public ConverstaionDetailsItemAdapter(List<Message> pMessages, Context context, Conversation
pConversation) {
this.messages = pMessages;
mContext = context;
this.conversation = pConversation;
}
#Override
public ConversationDetailsItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ConversationDetailsItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_conversations_details_item, parent, false), mContext,conversation);
}
#Override
public void onBindViewHolder(final ConversationDetailsItemViewHolder holder, final int position) {
Message message = messages.get(position);
if (message != null) {
holder.setConversationItem(message, position);
}
}
#Override
public int getItemCount() {
return (messages == null) ? 0 : messages.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
}
My ViewHolder class
public class ConversationDetailsItemViewHolder extends RecyclerView.ViewHolder {
Context mContext;
Conversation conversation;
ImageView imageView;
public static TextView txtContactName, txtMessage, txtMessageTime;
private RelativeLayout rltRoot;
public ConversationDetailsItemViewHolder(View view, Context context, Conversation pConversation) {
super(view);
mContext = context;
conversation = pConversation;
rltRoot = view.findViewById(R.id.rlt_conversation_details_item_root);
txtContactName = view.findViewById(R.id.txt_contact_name);
txtMessageTime = view.findViewById(R.id.text_message_time);
txtMessage = view.findViewById(R.id.text_message);
}
public void setConversationItem(Message item, final int position) {
if(item.getType().equals("1")) {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
txtMessage.setLayoutParams(params);
txtMessage.setBackgroundResource(R.drawable.rounded_rectangle_incoming);
} else {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
txtMessage.setLayoutParams(params);
txtMessage.setBackgroundResource(R.drawable.rounded_rectangle);
}
txtMessage.setText(item.getBody()+"\n");
}
}
I have the similar project, check out my code
package com.example.crimerigestration;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.menu.MenuView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CrimeListFragment extends Fragment {
private boolean mSubtitleVisible;
private RecyclerView mCrimeRecyclerView;
private CrimeAdapter crimeAdapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_list_crime,container,false);
mCrimeRecyclerView=(RecyclerView)v.findViewById(R.id.crime_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
setHasOptionsMenu(true);
updateUI();
return v;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list,menu);
MenuItem menuItem=menu.findItem(R.id.show_subtitle);
if(mSubtitleVisible){
menuItem.setTitle(R.string.hide_subtitle);
}
else {
menuItem.setTitle(R.string.show_subtitle);
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
//return super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.new_crime:
Crime crime=new Crime();
CrimeLab.get(getActivity()).addCrime(crime);
Intent intent=CrimePagerActivity.newIntent(getActivity(),crime.getmID());
startActivity(intent);
return true;
case R.id.show_subtitle:
mSubtitleVisible=!mSubtitleVisible;
getActivity().invalidateOptionsMenu();
updateSubtitle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void updateSubtitle() {
String subtitle=null;
if(mSubtitleVisible){
CrimeLab crimeLab=CrimeLab.get(getActivity());
int count=crimeLab.getsCrimes().size();
subtitle=getString(R.string.subtitle_formate,count);
}
AppCompatActivity appCompatActivity=(AppCompatActivity)getActivity();
appCompatActivity.getSupportActionBar().setSubtitle(subtitle);
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
private void updateUI() {
CrimeLab crimeLab=CrimeLab.get(getActivity());
ArrayList<Crime> crimes=crimeLab.getsCrimes();
if (crimeAdapter==null){
crimeAdapter =new CrimeAdapter(crimes);
mCrimeRecyclerView.setAdapter(crimeAdapter);
}
else {
crimeAdapter.setCrimes(crimes);
crimeAdapter.notifyDataSetChanged();
}
}
private class CrimeHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
private TextView mTitleTextView, mDateTextView;
private ImageView mSolvedImageView;
private Crime mCrime;
public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_crime,parent,false));
mTitleTextView=(TextView) itemView.findViewById(R.id.crime_title);
mDateTextView=(TextView)itemView.findViewById(R.id.crime_date);
mSolvedImageView=(ImageView)itemView.findViewById(R.id.imageView);
itemView.setOnClickListener(this);
}
public void bind(Crime crime){
this.mCrime=crime;
mTitleTextView.setText(mCrime.getmTitle());
mDateTextView.setText(mCrime.getmDate().toString());
mSolvedImageView.setVisibility(mCrime.ismSolved()?View.VISIBLE:View.GONE);
}
#Override
public void onClick(View v) {
Intent intent=CrimePagerActivity.newIntent(getActivity(),mCrime.getmID());
startActivity(intent);
}
}
private class RequireCrimeHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
private TextView mTitleTextView, mDateTextView;
private ImageView mSolvedImageView;
private Button mRequireButton;
private Crime mCrime;
public RequireCrimeHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.requried_to_police,parent,false));
mTitleTextView=(TextView) itemView.findViewById(R.id.crime_title);
mDateTextView=(TextView)itemView.findViewById(R.id.crime_date);
mSolvedImageView=(ImageView)itemView.findViewById(R.id.imageView);
mRequireButton=(Button)itemView.findViewById(R.id.button);
Factory();
itemView.setOnClickListener(this);
}
protected void Factory(){
mRequireButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),"No functionality
available",Toast.LENGTH_LONG).show();
}
});
}
public void bind(Crime crime){
this.mCrime=crime;
mTitleTextView.setText(mCrime.getmTitle());
mDateTextView.setText(mCrime.getmDate().toString());
mSolvedImageView.setVisibility(mCrime.ismSolved()?View.VISIBLE:View.GONE);
}
#Override
public void onClick(View v) {
Intent intent=CrimePagerActivity.newIntent(getActivity(),mCrime.getmID());
startActivity(intent); }
}
private class CrimeAdapter extends RecyclerView.Adapter{
private ArrayList<Crime> mCrime;
public CrimeAdapter(ArrayList<Crime> mCrime) {
this.mCrime = mCrime;
}
#Override
public int getItemViewType(int position) {
if (mCrime.get(position).ismRequire() ){
return 0;
}
else{
return 1;
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
LayoutInflater layoutInflater=LayoutInflater.from(getActivity());
if (viewType==0){
return new RequireCrimeHolder(layoutInflater,parent);
}
else{
return new CrimeHolder(layoutInflater,parent);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int
position) {
Crime crime=mCrime.get(position);
if (crime.ismRequire() ){
RequireCrimeHolder requireCrimeHolder= (RequireCrimeHolder) holder;
requireCrimeHolder.bind(crime);
}
else{
CrimeHolder crimeHolder= (CrimeHolder) holder;
crimeHolder.bind(crime);
}
}
#Override
public int getItemCount() {
return mCrime.size();
}
public void setCrimes(ArrayList<Crime> crime){
this.mCrime=crime;
}
}
}
You should call notifyItemInsert(0) (or size - 1, instead of 0, depending on sort asc/desc). If it doesn't work, try notifyDataSetChanged(), but don't keep it, cause it will kill performance.
Hello Every One I am trying to move from one activity to another using intent in adaptor class of recycler view but I am getting son=me errors in doing so, Following are the errors:
1.PakistaniActivity is not a Enclosing class.
2.Cannot resolve method StatrActivity();
Here is my code:
PakistaniActivity.Java
package com.recycler.hp.navigationbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
public class PakistaniActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pakistani);
RecyclerView rl=findViewById(R.id.list);
rl.setLayoutManager(new LinearLayoutManager(this));
String[] languges={"Badnamiyan", "song2","song3","song4","Song5","song6","song7","song8","song9"};
rl.setAdapter(new Adaptor(languges));
}
}
Adaptor.java
package com.recycler.hp.navigationbar;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.net.URL;
public class Adaptor extends RecyclerView.Adapter<Adaptor.viewholder> {
private String[] data;
public Adaptor(String[] data) {
this.data = data;
}
#Override
public viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_item1, parent, false);
return new viewholder(view);
}
#Override
public void onBindViewHolder(viewholder holder, final int position) {
String title = data[position];
holder.t.setText(title);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
long x;
x=getItemId(position);
if(x==0)
{
Intent intent=new Intent(PakistaniActivity.this,Revival_Activity.class);
startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return data.length;
}
public class viewholder extends RecyclerView.ViewHolder {
ImageView i;
TextView t;
public viewholder(View itemView) {
super(itemView);
i = itemView.findViewById(R.id.img1);
t = itemView.findViewById(R.id.main1);
}
}
}
Try not starting activities inside the adapter. You can use this adapter:
public abstract class ClickableAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
private ClickItemListener clickItemListener;
public void setClickItemListener(ClickItemListener clickItemListener) {
this.clickItemListener = clickItemListener;
}
#Override
public void onBindViewHolder(#NonNull final VH holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (clickItemListener != null)
clickItemListener.onClickItem(holder.itemView, holder.getAdapterPosition());
else
throw new IllegalStateException("Click listener not set");
}
});
}
public interface ClickItemListener {
void onClickItem(View v, int position);
}
}
Then make your adapter extend mine:
public class Adaptor extends ClickableAdapter<Adaptor.viewholder> {
private String[] data;
public Adaptor(String[] data) {
this.data = data;
}
#Override
public viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_item1, parent, false);
return new viewholder(view);
}
#Override
public void onBindViewHolder(viewholder holder, final int position) {
super.onBindViewHolder(holder,position);
String title = data[position];
holder.t.setText(title);
}
#Override
public int getItemCount() {
return data.length;
}
public class viewholder extends RecyclerView.ViewHolder {
ImageView i;
TextView t;
public viewholder(View itemView) {
super(itemView);
i = itemView.findViewById(R.id.img1);
t = itemView.findViewById(R.id.main1);
}
}
}
Finally in your activity you can set the behaviour for the adapter:
Adaptor adapter = new Adaptor(languges)
rl.setAdapter(adapter);
adapter.setClickItemListener(new ClickableAdapter.ClickItemListener() {
#Override
public void onClickItem(View v, int position) {
if(position==0)
{
Intent intent=new Intent(PakistaniActivity.this,Revival_Activity.class);
startActivity(intent);
}
}
});
Write
Intent intent=new Intent(getContext(),Revival_Activity.class);
startActivity(intent);
instead of this
Intent intent=new Intent(PakistaniActivity.this,Revival_Activity.class);
startActivity(intent);
or
pass the context from the from PakistaniActivity to the Adapter class and user the context as the data member of the adapter class
Pass the context of PakistaniActivity into Adapter
new Adaptor(languges,getApplicationContext);
private Context context;
public Adaptor(String[] data,Conetext context) {
this.data = data;
this.context = conetext;
}
Intent intent=new Intent(context,Revival_Activity.class);
startActivity(intent);
Try using this:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
long x;
x=getItemId(position);
if(x==0){
Intent intent = new Intent(getContext(), Revival_Activity.class);
context.startActivity(intent);
I want to change the list contents in a bottom sheet view though click event, but I only got empty sheet. Here is a demo modified from BottomSheetSample(github.com/niravkalola/BottomSheetSample).
mainActivity.java
package com.nkdroid.bottomsheetsample;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends AppCompatActivity implements ItemAdapter.ItemListener {
private Button btnView, btnDialog;
BottomSheetBehavior behavior;
private BottomSheetDialog mBottomSheetDialog;
private ItemAdapter mAdapter;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnView = (Button) findViewById(R.id.btnView);
btnDialog = (Button) findViewById(R.id.btnDialog);
btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAdapter = new ItemAdapter(createItems());
recyclerView.setAdapter(mAdapter);
behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
}
});
btnDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showBottomSheetDialog();
}
});
View bottomSheet = findViewById(R.id.bottom_sheet);
behavior = BottomSheetBehavior.from(bottomSheet);
behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
#Override
public void onStateChanged(#NonNull View bottomSheet, int newState) {
// React to state change
}
#Override
public void onSlide(#NonNull View bottomSheet, float slideOffset) {
// React to dragging events
}
});
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new ItemAdapter(createItems(), this);
recyclerView.setAdapter(mAdapter);
}
private void showBottomSheetDialog() {
if (behavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
mBottomSheetDialog = new BottomSheetDialog(this);
View view = getLayoutInflater().inflate(R.layout.sheet, null);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new ItemAdapter(createItems(), new ItemAdapter.ItemListener() {
#Override
public void onItemClick(Item item) {
if (mBottomSheetDialog != null) {
mBottomSheetDialog.dismiss();
}
}
}));
mBottomSheetDialog.setContentView(view);
mBottomSheetDialog.show();
mBottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
mBottomSheetDialog = null;
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mAdapter.setListener(null);
}
public List<Item> createItems() {
Random r = new Random();
ArrayList<Item> items = new ArrayList<>();
items.add(new Item(R.mipmap.ic_launcher, "Item 1"+ r.nextInt(100)));
items.add(new Item(R.mipmap.ic_launcher, "Item 2"));
items.add(new Item(R.mipmap.ic_launcher, "Item 3"));
items.add(new Item(R.mipmap.ic_launcher, "Item 4"));
return items;
}
#Override
public void onItemClick(Item item) {
behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
}
ItemAdapter.java:
package com.nkdroid.bottomsheetsample;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {
private List<Item> mItems;
private ItemListener mListener;
public ItemAdapter(List<Item> items, ItemListener listener) {
mItems = items;
mListener = listener;
}
public ItemAdapter(List<Item> items) {
mItems = items;
}
public void setListener(ItemListener listener) {
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.setData(mItems.get(position));
}
#Override
public int getItemCount() {
return mItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView imageView;
public TextView textView;
public Item item;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
textView = (TextView) itemView.findViewById(R.id.textView);
}
public void setData(Item item) {
this.item = item;
imageView.setImageResource(item.getDrawableResource());
textView.setText(item.getTitle());
}
#Override
public void onClick(View v) {
if (mListener != null) {
mListener.onItemClick(item);
}
}
}
public interface ItemListener {
void onItemClick(Item item);
}
}
Here are the capture after click show view button for the first and second time:
first click
second click
This is fixed in 24.0.0 i.e. the recyclerView gets updated. But if you are using wrap_content on the bottomsheet as well as recyclerview you will have to use this so that the bottomsheet height is calculated properly.
bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
#Override
public void onStateChanged(#NonNull View bottomSheet, int newState) {
if(newState==BottomSheetBehavior.STATE_EXPANDED){
bottomSheet.requestLayout();
/*or
recyclerView.scrollToPosition(0);
recyclerView.requestLayout();*/
}
}
#Override
public void onSlide(#NonNull View bottomSheet, float slideOffset) {
}
});
If you want to work with earlier versions use
bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
#Override
public void onStateChanged(#NonNull View bottomSheet, int newState) {
if(newState==BottomSheetBehavior.STATE_EXPANDED){
bottomSheet.requestLayout();
bottomSheet.invalidate();
}
}
#Override
public void onSlide(#NonNull View bottomSheet, float slideOffset) {
}
});